diff --git a/local-test-freerdp-full-01/afc-freerdp/CMakeCPack.cmake b/local-test-freerdp-full-01/afc-freerdp/CMakeCPack.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d28454ff2b63eaf413c0231a471b123169bef94c --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/CMakeCPack.cmake @@ -0,0 +1,98 @@ +# Generate .txt license file for CPack (PackageMaker requires a file extension) +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/LICENSE ${CMAKE_CURRENT_BINARY_DIR}/LICENSE.txt @ONLY) + +# Workaround to remove c++ compiler macros and defines for Eclipse. +# If c++ macros/defines are set __cplusplus is also set which causes +# problems when compiling freerdp/jni. To prevent this problem we set the macros to "". + +if(ANDROID AND CMAKE_EXTRA_GENERATOR STREQUAL "Eclipse CDT4") + set(CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_DEFINED_MACROS "") + message(STATUS "Disabled CXX system defines for eclipse (workaround).") +endif() + +set(CPACK_SOURCE_IGNORE_FILES "/\\\\.git/;/\\\\.gitignore;/CMakeCache.txt") + +if(NOT WIN32) + if(APPLE AND (NOT IOS)) + + if(WITH_SERVER) + set(CPACK_PACKAGE_EXECUTABLES ${CPACK_PACKAGE_EXECUTABLES} "mfreerdp-server") + endif() + endif() + + if(WITH_X11) + set(CPACK_PACKAGE_EXECUTABLES "xfreerdp") + + if(WITH_SERVER) + set(CPACK_PACKAGE_EXECUTABLES ${CPACK_PACKAGE_EXECUTABLES} "xfreerdp-server") + endif() + endif() +endif() + +set(CPACK_SYSTEM_NAME "${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") +set(CPACK_TOPLEVEL_TAG "${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") + +string(TOLOWER ${CMAKE_PROJECT_NAME} CMAKE_PROJECT_NAME_lower) +set(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME_lower}-${FREERDP_VERSION_FULL}-${CPACK_SYSTEM_NAME}") +set(CPACK_SOURCE_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME_lower}-${FREERDP_VERSION_FULL}-${CPACK_SYSTEM_NAME}") + +set(CPACK_PACKAGE_NAME "FreeRDP") +set(CPACK_PACKAGE_VENDOR "FreeRDP") +set(CPACK_PACKAGE_VERSION ${FREERDP_VERSION_FULL}) +set(CPACK_PACKAGE_VERSION_MAJOR ${FREERDP_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${FREERDP_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${FREERDP_VERSION_REVISION}) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "FreeRDP: A Remote Desktop Protocol Implementation") + +set(CPACK_PACKAGE_CONTACT "Marc-Andre Moreau") +set(CPACK_DEBIAN_PACKAGE_MAINTAINER "marcandre.moreau@gmail.com") +set(CPACK_DEBIAN_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR}) + +set(CPACK_PACKAGE_INSTALL_DIRECTORY "FreeRDP") +set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_BINARY_DIR}/LICENSE.txt") +set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_BINARY_DIR}/LICENSE.txt") + +set(CPACK_NSIS_MODIFY_PATH ON) +set(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/resources\\\\FreeRDP_Install.bmp") +set(CPACK_NSIS_MUI_ICON "${PROJECT_SOURCE_DIR}/resources\\\\FreeRDP_Icon_96px.ico") +set(CPACK_NSIS_MUI_UNICON "${PROJECT_SOURCE_DIR}/resource\\\\FreeRDP_Icon_96px.ico") + +set(CPACK_COMPONENTS_ALL client server libraries headers symbols tools) + +if(MSVC) + string(FIND ${CMAKE_MSVC_RUNTIME_LIBRARY} "DLL" IS_SHARED) + + if(NOT IS_SHARED STREQUAL "-1") + set(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP TRUE) + include(InstallRequiredSystemLibraries) + + install(PROGRAMS ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT libraries) + endif() +endif() + +set(CPACK_COMPONENT_CLIENT_DISPLAY_NAME "Client") +set(CPACK_COMPONENT_CLIENT_GROUP "Applications") + +set(CPACK_COMPONENT_SERVER_DISPLAY_NAME "Server") +set(CPACK_COMPONENT_SERVER_GROUP "Applications") + +set(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "Libraries") +set(CPACK_COMPONENT_LIBRARIES_GROUP "Runtime") + +set(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "Headers") +set(CPACK_COMPONENT_HEADERS_GROUP "Development") + +set(CPACK_COMPONENT_SYMBOLS_DISPLAY_NAME "Symbols") +set(CPACK_COMPONENT_SYMBOLS_GROUP "Development") + +set(CPACK_COMPONENT_TOOLS_DISPLAY_NAME "Tools") +set(CPACK_COMPONENT_TOOLS_GROUP "Applications") + +set(CPACK_COMPONENT_GROUP_RUNTIME_DESCRIPTION "Runtime") +set(CPACK_COMPONENT_GROUP_APPLICATIONS_DESCRIPTION "Applications") +set(CPACK_COMPONENT_GROUP_DEVELOPMENT_DESCRIPTION "Development") + +configure_file("${PROJECT_SOURCE_DIR}/CMakeCPackOptions.cmake.in" "${PROJECT_BINARY_DIR}/CMakeCPackOptions.cmake" @ONLY) +set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/CMakeCPackOptions.cmake") + +include(CPack) diff --git a/local-test-freerdp-full-01/afc-freerdp/CMakeCPackOptions.cmake.in b/local-test-freerdp-full-01/afc-freerdp/CMakeCPackOptions.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..826eaa10d46c2af5bca7348f8643f6995f803c13 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/CMakeCPackOptions.cmake.in @@ -0,0 +1,10 @@ +# This file is configured at cmake time, and loaded at cpack time. +# To pass variables to cpack from cmake, they must be configured in this file. + +if("${CPACK_GENERATOR}" STREQUAL "PackageMaker") + if(CMAKE_PACKAGE_QTGUI) + set(CPACK_PACKAGE_DEFAULT_LOCATION "/Applications") + else() + set(CPACK_PACKAGE_DEFAULT_LOCATION "/usr") + endif() +endif() diff --git a/local-test-freerdp-full-01/afc-freerdp/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..af4b3cef3b82d4e47a849413f35d58cd56b84611 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/CMakeLists.txt @@ -0,0 +1,600 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP cmake build script +# +# Copyright 2011 O.S. Systems Software Ltda. +# Copyright 2011 Otavio Salvador +# Copyright 2011 Marc-Andre Moreau +# Copyright 2012 HP Development Company, LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +project(FreeRDP LANGUAGES C) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS ON) + +add_custom_target(fuzzers COMMENT "Build fuzzers") + +if(NOT DEFINED VENDOR) + set(VENDOR "FreeRDP" CACHE STRING "FreeRDP package vendor") +endif() + +if(NOT DEFINED PRODUCT) + set(PRODUCT "FreeRDP" CACHE STRING "FreeRDP package name") +endif() + +if(NOT DEFINED FREERDP_VENDOR) + set(FREERDP_VENDOR 1) +endif() + +if(NOT WIN32 AND NOT ANDROID) + if(APPLE) + set(OPT_DEFAULT_VAL OFF) + else() + set(OPT_DEFAULT_VAL ON) + endif() + option(WITH_X11 "build X11 client/server" ${OPT_DEFAULT_VAL}) +endif() + +# Enable coverity related pragma definitions +if(COVERITY_BUILD) + add_compile_definitions(COVERITY_BUILD) +endif() + +# Include our extra modules +list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/) + +# Check for cmake compatibility (enable/disable features) +include(CheckCmakeCompat) + +# Include cmake modules +if(WITH_CLANG_FORMAT) + include(ClangFormat) +endif() + +include(CompilerFlags) +include(CheckIncludeFiles) +include(CheckLibraryExists) +include(CheckSymbolExists) +include(CheckStructHasMember) +include(TestBigEndian) +include(CompilerDetect) + +include(FindFeature) +include(ShowCMakeVars) +include(ConfigOptions) +include(FeatureSummary) +include(CheckCCompilerFlag) +include(CMakePackageConfigHelpers) +include(InstallFreeRDPMan) +include(GetGitRevisionDescription) +include(SetFreeRDPCMakeInstallDir) +include(Doxygen) + +# Soname versioning +set(BUILD_NUMBER 0) +if($ENV{BUILD_NUMBER}) + set(BUILD_NUMBER $ENV{BUILD_NUMBER}) +endif() + +set(VERSION_REGEX "^(.*)([0-9]+)\\.([0-9]+)\\.([0-9]+)-?(.*)") +set(RAW_VERSION_STRING "3.11.2-dev0") +if(EXISTS "${PROJECT_SOURCE_DIR}/.source_tag") + file(READ ${PROJECT_SOURCE_DIR}/.source_tag RAW_VERSION_STRING) +elseif(USE_VERSION_FROM_GIT_TAG) + git_get_exact_tag(_GIT_TAG --tags --always) + if(NOT ${_GIT_TAG} STREQUAL "n/a") + string(REGEX MATCH ${VERSION_REGEX} FOUND_TAG "${_GIT_TAG}") + if(FOUND_TAG) + set(RAW_VERSION_STRING ${_GIT_TAG}) + endif() + endif() +endif() +string(STRIP ${RAW_VERSION_STRING} RAW_VERSION_STRING) + +string(REGEX REPLACE "${VERSION_REGEX}" "\\2" FREERDP_VERSION_MAJOR "${RAW_VERSION_STRING}") +string(REGEX REPLACE "${VERSION_REGEX}" "\\3" FREERDP_VERSION_MINOR "${RAW_VERSION_STRING}") +string(REGEX REPLACE "${VERSION_REGEX}" "\\4" FREERDP_VERSION_REVISION "${RAW_VERSION_STRING}") +string(REGEX REPLACE "${VERSION_REGEX}" "\\5" FREERDP_VERSION_SUFFIX "${RAW_VERSION_STRING}") + +set(FREERDP_API_VERSION "${FREERDP_VERSION_MAJOR}") +set(FREERDP_VERSION "${FREERDP_VERSION_MAJOR}.${FREERDP_VERSION_MINOR}.${FREERDP_VERSION_REVISION}") +if(FREERDP_VERSION_SUFFIX) + set(FREERDP_VERSION_FULL "${FREERDP_VERSION}-${FREERDP_VERSION_SUFFIX}") +else() + set(FREERDP_VERSION_FULL "${FREERDP_VERSION}") +endif() +message("FREERDP_VERSION=${FREERDP_VERSION_FULL}") + +if(EXISTS "${PROJECT_SOURCE_DIR}/.source_version") + file(READ ${PROJECT_SOURCE_DIR}/.source_version GIT_REVISION) + + string(STRIP ${GIT_REVISION} GIT_REVISION) +elseif(USE_VERSION_FROM_GIT_TAG) + git_get_exact_tag(GIT_REVISION --tags --always) + + if(${GIT_REVISION} STREQUAL "n/a") + git_rev_parse(GIT_REVISION --short) + endif() +endif() + +if(NOT GIT_REVISION) + set(GIT_REVISION ${FREERDP_VERSION}) +endif() + +message(STATUS "Git Revision ${GIT_REVISION}") + +# MSVC compatibility with system headers +add_compile_definitions(NONAMELESSUNION) + +# Make the detected version available as default version for all subprojects +set(FREERDP_DEFAULT_PROJECT_VERSION ${FREERDP_VERSION} CACHE STRING INTERNAL) + +set(FREERDP_MAJOR_DIR "freerdp${FREERDP_VERSION_MAJOR}") +set(FREERDP_INCLUDE_DIR "include/${FREERDP_MAJOR_DIR}/") + +option(WITH_SMARTCARD_EMULATE "Emulate smartcards instead of redirecting readers" ON) +if(WITH_SMARTCARD_EMULATE) + add_compile_definitions(WITH_SMARTCARD_EMULATE) + find_package(ZLIB REQUIRED) +endif() + +option(WITH_FREERDP_DEPRECATED "Build FreeRDP deprecated symbols" OFF) +if(WITH_FREERDP_DEPRECATED) + add_compile_definitions(WITH_FREERDP_DEPRECATED) +endif() + +option(WITH_FREERDP_DEPRECATED_COMMANDLINE "Build FreeRDP deprecated command line options" OFF) +if(WITH_FREERDP_DEPRECATED_COMMANDLINE) + add_compile_definitions(WITH_FREERDP_DEPRECATED_COMMANDLINE) +endif() + +# Make paths absolute +if(CMAKE_INSTALL_PREFIX) + get_filename_component(CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" ABSOLUTE) +endif() +if(FREERDP_EXTERNAL_PATH) + get_filename_component(FREERDP_EXTERNAL_PATH "${FREERDP_EXTERNAL_PATH}" ABSOLUTE) +endif() + +# Allow to search the host machine for git/ccache +if(CMAKE_CROSSCOMPILING) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH) +endif(CMAKE_CROSSCOMPILING) + +find_program(CCACHE ccache) +if(CCACHE AND WITH_CCACHE) + if(NOT DEFINED CMAKE_C_COMPILER_LAUNCHER) + set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE}) + endif(NOT DEFINED CMAKE_C_COMPILER_LAUNCHER) +endif(CCACHE AND WITH_CCACHE) + +if(CMAKE_CROSSCOMPILING) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY) +endif(CMAKE_CROSSCOMPILING) +# /Allow to search the host machine for git/ccache + +# Turn on solution folders (2.8.4+) +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + +option(CTEST_OUTPUT_ON_FAILURE ON "show verbose output on CTest failures") +if(BUILD_TESTING_INTERNAL) + set(EXPORT_ALL_SYMBOLS ON CACHE BOOL "testing default" FORCE) + add_compile_definitions(BUILD_TESTING_INTERNAL) +elseif(BUILD_TESTING) + set(EXPORT_ALL_SYMBOLS OFF CACHE BOOL "testing default" FORCE) +endif() + +include(ExportAllSymbols) + +set(THREAD_PREFER_PTHREAD_FLAG TRUE) + +if(NOT IOS) + find_package(Threads REQUIRED) +endif() + +if(WIN32) + add_compile_definitions(UNICODE _UNICODE) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS) + add_compile_definitions(WIN32_LEAN_AND_MEAN) + add_compile_definitions(_WINSOCK_DEPRECATED_NO_WARNINGS) + + set(CMAKE_DL_LIBS "") + set(CMAKE_USE_RELATIVE_PATH ON) + string(TIMESTAMP RC_VERSION_YEAR "%Y") + + if(NOT DEFINED CMAKE_WINDOWS_VERSION) + set(CMAKE_WINDOWS_VERSION "WIN7") + endif() + + if(CMAKE_WINDOWS_VERSION STREQUAL "WINXP") + add_compile_definitions(WINVER=0x0501 _WIN32_WINNT=0x0501) + elseif(CMAKE_WINDOWS_VERSION STREQUAL "WIN7") + add_compile_definitions(WINVER=0x0601 _WIN32_WINNT=0x0601) + elseif(CMAKE_WINDOWS_VERSION STREQUAL "WIN8") + add_compile_definitions(WINVER=0x0602 _WIN32_WINNT=0x0602) + elseif(CMAKE_WINDOWS_VERSION STREQUAL "WIN10") + add_compile_definitions(WINVER=0x0A00 _WIN32_WINNT=0x0A00) + endif() + + # Set product and vendor for dll and exe version information. + set(RC_VERSION_VENDOR ${VENDOR}) + set(RC_VERSION_PRODUCT ${PRODUCT}) + set(RC_VERSION_PATCH ${BUILD_NUMBER}) + set(RC_VERSION_DESCRIPTION + "${FREERDP_VERSION_FULL} ${GIT_REVISION} ${CMAKE_WINDOWS_VERSION} ${CMAKE_SYSTEM_PROCESSOR}" + ) + + if(FREERDP_EXTERNAL_SSL_PATH) + set(OPENSSL_ROOT_DIR ${FREERDP_EXTERNAL_SSL_PATH}) + endif() +endif() + +add_compile_definitions(FREERDP_EXPORTS) + +# Mac OS X +if(APPLE) + if(IOS) + if(NOT FREERDP_IOS_EXTERNAL_SSL_PATH) + message( + STATUS + "FREERDP_IOS_EXTERNAL_SSL_PATH not set! Required if openssl is not found in the iOS SDK (which usually isn't" + ) + endif() + set(CMAKE_FIND_ROOT_PATH ${CMAKE_FIND_ROOT_PATH} ${FREERDP_IOS_EXTERNAL_SSL_PATH}) + set_property(GLOBAL PROPERTY XCODE_ATTRIBUTE_SKIP_INSTALL YES) + endif(IOS) + + # Temporarily disabled, causes the cmake script to be reexecuted, causing the compilation to fail. + # Workaround: specify the parameter in the command-line + # if(WITH_CLANG) + # set(CMAKE_C_COMPILER "clang") + # endif() + + if(WITH_VERBOSE) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -v") + endif() +endif(APPLE) + +# Android +if(ANDROID) + set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS ${ANDROID_LIBRARY_USE_LIB64_PATHS}) + + if(ANDROID_ABI STREQUAL arm64-v8a) + include(CheckCCompilerFlag) + check_c_compiler_flag("-mfloat-abi=softfp" ABI_SOFTFP_SUPPORTED) + + if(ABI_SOFTFP_SUPPORTED) + # https://github.com/android/ndk/issues/910 + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -mfloat-abi=softfp") + endif() + endif() + + add_compile_definitions("$<$:NDK_DEBUG=1>") + + # NOTE: Manually add -gdwarf-3, as newer toolchains default to -gdwarf-4, + # which is not supported by the gdbserver binary shipped with + # the android NDK (tested with r9b) + add_compile_options("$<$:-gdwarf-3>") + add_link_options(-llog) + + # CMAKE_PREFIX_PATH detection is broken in most Android toolchain files + # Append it to CMAKE_FIND_ROOT_PATH and avoid potential duplicates + list(APPEND CMAKE_FIND_ROOT_PATH ${CMAKE_PREFIX_PATH}) + list(REMOVE_DUPLICATES CMAKE_FIND_ROOT_PATH) + + if(NOT FREERDP_EXTERNAL_PATH) + if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/external/") + set(FREERDP_EXTERNAL_PATH "${CMAKE_CURRENT_SOURCE_DIR}/external/") + else() + message(STATUS "FREERDP_EXTERNAL_PATH not set!") + endif() + endif() + + list(APPEND CMAKE_INCLUDE_PATH ${FREERDP_EXTERNAL_PATH}/${ANDROID_ABI}/include) + list(APPEND CMAKE_LIBRARY_PATH ${FREERDP_EXTERNAL_PATH}/${ANDROID_ABI}/) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) + + if(WITH_GPROF) + configure_file( + ${PROJECT_SOURCE_DIR}/scripts/gprof_generate.sh.in ${PROJECT_BINARY_DIR}/scripts/gprof_generate.sh @ONLY + ) + endif(WITH_GPROF) +endif() + +if(UNIX OR CYGWIN) + set(WAYLAND_FEATURE_TYPE "RECOMMENDED") +else() + set(WAYLAND_FEATURE_TYPE "DISABLED") +endif() + +if(WITH_PCSC_WINPR) + find_package(PCSCWinPR) +endif() + +set(WAYLAND_FEATURE_PURPOSE "Wayland") +set(WAYLAND_FEATURE_DESCRIPTION "Wayland client") + +set(OPENSSL_FEATURE_TYPE "REQUIRED") +set(OPENSSL_FEATURE_PURPOSE "cryptography") +set(OPENSSL_FEATURE_DESCRIPTION "encryption, certificate validation, hashing functions") + +set(MBEDTLS_FEATURE_TYPE "OPTIONAL") +set(MBEDTLS_FEATURE_PURPOSE "cryptography") +set(MBEDTLS_FEATURE_DESCRIPTION "encryption, certificate validation, hashing functions") + +set(PCSC_FEATURE_TYPE "RECOMMENDED") +set(PCSC_FEATURE_PURPOSE "smart card") +set(PCSC_FEATURE_DESCRIPTION "smart card device redirection") + +set(OPENH264_FEATURE_TYPE "OPTIONAL") +set(OPENH264_FEATURE_PURPOSE "codec") +set(OPENH264_FEATURE_DESCRIPTION "use OpenH264 library") + +set(OPENCL_FEATURE_TYPE "OPTIONAL") +set(OPENCL_FEATURE_PURPOSE "codec") +set(OPENCL_FEATURE_DESCRIPTION "use OpenCL library") + +set(GSM_FEATURE_TYPE "OPTIONAL") +set(GSM_FEATURE_PURPOSE "codec") +set(GSM_FEATURE_DESCRIPTION "GSM audio codec library") + +set(LAME_FEATURE_TYPE "OPTIONAL") +set(LAME_FEATURE_PURPOSE "codec") +set(LAME_FEATURE_DESCRIPTION "lame MP3 audio codec library") + +set(FAAD2_FEATURE_TYPE "OPTIONAL") +set(FAAD2_FEATURE_PURPOSE "codec") +set(FAAD2_FEATURE_DESCRIPTION "FAAD2 AAC audio codec library") + +set(FAAC_FEATURE_TYPE "OPTIONAL") +set(FAAC_FEATURE_PURPOSE "codec") +set(FAAC_FEATURE_DESCRIPTION "FAAC AAC audio codec library") + +set(SOXR_FEATURE_TYPE "OPTIONAL") +set(SOXR_FEATURE_PURPOSE "codec") +set(SOXR_FEATURE_DESCRIPTION "SOX audio resample library") + +if(WIN32) + set(WAYLAND_FEATURE_TYPE "DISABLED") + set(PCSC_FEATURE_TYPE "DISABLED") +endif() + +if(APPLE) + set(WAYLAND_FEATURE_TYPE "DISABLED") + if(IOS) + set(PCSC_FEATURE_TYPE "DISABLED") + endif() +endif() + +if(ANDROID) + set(WAYLAND_FEATURE_TYPE "DISABLED") + set(PCSC_FEATURE_TYPE "DISABLED") +endif() + +find_feature(Wayland ${WAYLAND_FEATURE_TYPE} ${WAYLAND_FEATURE_PURPOSE} ${WAYLAND_FEATURE_DESCRIPTION}) + +option(WITH_LIBRESSL "build with LibreSSL" OFF) +if(WITH_LIBRESSL) + find_package(LibreSSL REQUIRED) + include_directories(SYSTEM ${LibreSSL_INCLUDE_DIRS}) + set(OPENSSL_INCLUDE_DIR ${LIBRESSL_INCLUDE_DIR}) + set(OPENSSL_LIBRARIES ${LIBRESSL_LIBRARIES}) + set(OPENSSL_CRYPTO_LIBRARIES ${LIBRESSL_LIBRARIES}) + set(WITH_OPENSSL ON) + set(OPENSSL_FOUND ON) + add_compile_definitions("WITH_LIBRESSL") + add_compile_definitions("WITH_OPENSSL") +else() + find_feature(OpenSSL ${OPENSSL_FEATURE_TYPE} ${OPENSSL_FEATURE_PURPOSE} ${OPENSSL_FEATURE_DESCRIPTION}) + find_feature(MbedTLS ${MBEDTLS_FEATURE_TYPE} ${MBEDTLS_FEATURE_PURPOSE} ${MBEDTLS_FEATURE_DESCRIPTION}) +endif() + +find_feature(PCSC ${PCSC_FEATURE_TYPE} ${PCSC_FEATURE_PURPOSE} ${PCSC_FEATURE_DESCRIPTION}) + +if(WITH_DSP_FFMPEG OR WITH_VIDEO_FFMPEG OR WITH_FFMPEG) + find_package(FFmpeg REQUIRED COMPONENTS AVUTIL AVCODEC) +endif() + +find_feature(OpenH264 ${OPENH264_FEATURE_TYPE} ${OPENH264_FEATURE_PURPOSE} ${OPENH264_FEATURE_DESCRIPTION}) +find_feature(OpenCL ${OPENCL_FEATURE_TYPE} ${OPENCL_FEATURE_PURPOSE} ${OPENCL_FEATURE_DESCRIPTION}) +find_feature(GSM ${GSM_FEATURE_TYPE} ${GSM_FEATURE_PURPOSE} ${GSM_FEATURE_DESCRIPTION}) +find_feature(LAME ${LAME_FEATURE_TYPE} ${LAME_FEATURE_PURPOSE} ${LAME_FEATURE_DESCRIPTION}) +find_feature(FAAD2 ${FAAD2_FEATURE_TYPE} ${FAAD2_FEATURE_PURPOSE} ${FAAD2_FEATURE_DESCRIPTION}) +find_feature(FAAC ${FAAC_FEATURE_TYPE} ${FAAC_FEATURE_PURPOSE} ${FAAC_FEATURE_DESCRIPTION}) +find_feature(soxr ${SOXR_FEATURE_TYPE} ${SOXR_FEATURE_PURPOSE} ${SOXR_FEATURE_DESCRIPTION}) + +if(WITH_OPENH264 AND NOT WITH_OPENH264_LOADING) + option(WITH_OPENH264_LOADING "Use LoadLibrary to load openh264 at runtime" OFF) +endif(WITH_OPENH264 AND NOT WITH_OPENH264_LOADING) + +# Version check, if we have detected FFMPEG but the version is too old +# deactivate it as sound backend. +if(WITH_DSP_FFMPEG) + if(AVCODEC_VERSION VERSION_LESS "57.48.101") + message( + WARNING + "FFmpeg version detected (${AVCODEC_VERSION}) is too old. (Require at least 57.48.101 for sound). Deactivating" + ) + set(WITH_DSP_FFMPEG OFF) + endif() +endif(WITH_DSP_FFMPEG) + +if(WITH_OPENH264 AND NOT OPENH264_FOUND) + message(FATAL_ERROR "OpenH264 support requested but not detected") +endif() +set(WITH_OPENH264 ${OPENH264_FOUND}) + +if(OPENSSL_FOUND) + add_compile_definitions("WITH_OPENSSL") + message(STATUS "Using OpenSSL Version: ${OPENSSL_VERSION}") + include_directories(SYSTEM ${OPENSSL_INCLUDE_DIR}) +endif() + +if(MBEDTLS_FOUND) + add_compile_definitions("WITH_MBEDTLS") +endif() + +if(WITH_OPENH264 OR WITH_MEDIA_FOUNDATION OR WITH_VIDEO_FFMPEG OR WITH_MEDIACODEC) + set(WITH_GFX_H264 ON) +else() + set(WITH_GFX_H264 OFF) +endif() + +# Android expects all libraries to be loadable +# without paths. +if(ANDROID OR WIN32 OR MAC_BUNDLE) + set(PLUGIN_ABS_PATHS_DEFAULT OFF) +else() + set(PLUGIN_ABS_PATHS_DEFAULT ON) +endif() +option(WITH_ABSOLUTE_PLUGIN_LOAD_PATHS "Load plugins with absolute paths" ${PLUGIN_ABS_PATHS_DEFAULT}) + +if(NOT WITH_ABSOLUTE_PLUGIN_LOAD_PATHS) + set(FREERDP_DATA_PATH "share") + if(NOT FREERDP_INSTALL_PREFIX) + set(FREERDP_INSTALL_PREFIX ".") + endif() + set(FREERDP_LIBRARY_PATH ".") + set(FREERDP_PLUGIN_PATH ".") +else() + set(FREERDP_DATA_PATH "${CMAKE_INSTALL_PREFIX}/share/${FREERDP_MAJOR_DIR}") + if(NOT FREERDP_INSTALL_PREFIX) + set(FREERDP_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + endif() + set(FREERDP_LIBRARY_PATH "${CMAKE_INSTALL_LIBDIR}") + if(WIN32) + set(FREERDP_PLUGIN_PATH "${CMAKE_INSTALL_BINDIR}/${FREERDP_MAJOR_DIR}") + else() + set(FREERDP_PLUGIN_PATH "${CMAKE_INSTALL_LIBDIR}/${FREERDP_MAJOR_DIR}") + endif() +endif() +set(FREERDP_ADDIN_PATH "${FREERDP_PLUGIN_PATH}") + +# Path to put extensions +set(FREERDP_EXTENSION_POSTFIX "${FREERDP_MAJOR_DIR}/extensions") +set(FREERDP_EXTENSION_REL_PATH "${CMAKE_INSTALL_LIBDIR}/${FREERDP_EXTENSION_POSTFIX}") +set(FREERDP_EXTENSION_PATH "${CMAKE_INSTALL_FULL_LIBDIR}/${FREERDP_EXTENSION_POSTFIX}") + +# Proxy plugins path +if(NOT DEFINED PROXY_PLUGINDIR) + message("using default plugins location") + set(FREERDP_PROXY_PLUGINDIR "${FREERDP_PLUGIN_PATH}/proxy/") +else() + set(FREERDP_PROXY_PLUGINDIR "${PROXY_PLUGINDIR}") +endif() + +# Unit Tests + +include(CTest) + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + enable_testing() + + if(MSVC) + set(TESTING_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}") + else() + set(TESTING_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/Testing") + endif() +endif() + +include(CommonConfigOptions) + +if(FREERDP_UNIFIED_BUILD) + add_subdirectory(winpr) + if(WITH_WAYLAND) + add_subdirectory(uwac) + endif() + if(WITH_SERVER) + option(WITH_RDTK "build rdtk toolkit" ON) + if(WITH_RDTK) + add_subdirectory(rdtk) + endif() + endif() + + include_directories(${PROJECT_SOURCE_DIR}/winpr/include) + include_directories(${PROJECT_BINARY_DIR}/winpr/include) +else() + find_package(WinPR 3 REQUIRED) + include_directories(SYSTEM ${WinPR_INCLUDE_DIR}) +endif() + +option(WITH_AAD "Compile with support for Azure AD authentication" ${WITH_WINPR_JSON}) + +# Include directories +include_directories(${CMAKE_CURRENT_BINARY_DIR}) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) + +# Sub-directories + +if(WITH_THIRD_PARTY) + add_subdirectory(third-party) + if(NOT "${THIRD_PARTY_INCLUDES}" STREQUAL "") + include_directories(SYSTEM ${THIRD_PARTY_INCLUDES}) + endif() +endif() + +add_subdirectory(libfreerdp) + +if(WITH_CHANNELS) + add_subdirectory(channels) +endif() + +if(WITH_CLIENT_COMMON OR WITH_CLIENT) + add_subdirectory(client) +endif() + +if(WITH_SERVER) + add_subdirectory(server) +endif() + +# Packaging + +set(CMAKE_CPACK_INCLUDE_FILE "CMakeCPack.cmake") + +if(NOT (VENDOR MATCHES "FreeRDP")) + if(DEFINED CLIENT_VENDOR_PATH) + if(EXISTS "${PROJECT_SOURCE_DIR}/${CLIENT_VENDOR_PATH}/CMakeCPack.cmake") + set(CMAKE_CPACK_INCLUDE_FILE "${CLIENT_VENDOR_PATH}/CMakeCPack.cmake") + endif() + endif() +endif() + +#message("VENDOR: ${VENDOR} CLIENT_VENDOR_PATH: ${CLIENT_VENDOR_PATH} CMAKE_CPACK_INCLUDE_FILE: ${CMAKE_CPACK_INCLUDE_FILE}") + +set(FREERDP_BUILD_CONFIG_LIST "") +get_cmake_property(res VARIABLES) +foreach(var ${res}) + if(var MATCHES "^WITH_*|^BUILD_TESTING*|^WINPR_HAVE_*") + list(APPEND FREERDP_BUILD_CONFIG_LIST "${var}=${${var}}") + endif() +endforeach() +string(REPLACE ";" " " FREERDP_BUILD_CONFIG "${FREERDP_BUILD_CONFIG_LIST}") + +add_subdirectory(include) + +include(${CMAKE_CPACK_INCLUDE_FILE}) + +message(STATUS "Intrinsic path configuration:") +#ShowCMakeVars("^CMAKE_INSTALL_PREFIX") +#ShowCMakeVars("^CMAKE_INSTALL_LIBDIR") +showcmakevars("^FREERDP_INSTALL_PREFIX|^FREERDP_LIBRARY_PATH|^FREERDP_PLUGIN_PATH") +showcmakevars("^FREERDP_ADDIN_PATH|^FREERDP_EXTENSION_PATH|^FREERDP_PROXY_PLUGINDIR") diff --git a/local-test-freerdp-full-01/afc-freerdp/ChangeLog b/local-test-freerdp-full-01/afc-freerdp/ChangeLog new file mode 100644 index 0000000000000000000000000000000000000000..8766a4ab862ebd63aae610885b2c5cd801bc9683 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/ChangeLog @@ -0,0 +1,622 @@ +# 2025-02-07 Version 3.11.1 + +A bugfix release addressing two regressions reported against 3.11.0 + +Noteworthy changes: + * Fix a segfault when passing /pth (#11138) + * Fix a regression in planar codec (#11136) + +For a complete and detailed change log since the last release run: +git log 3.11.1...3.11.0 + +# 2025-02-06 Version 3.11.0 + +A new release with bugfixes and code cleanups as well as a few nifty little +features that will improve your meetings. + +Noteworthy changes: + * Updated android client to more recent gradle (#11105, #11110) + * Fix cmake clean target (#109 + * SDL3 bugfixes and API updates (#11092, #11093, #11128) + * Fix keyboard mapping, add working japanese and korean types, deprecate + obsolete functions (#10989, #11035, #11011, #11074, #11037) + * Fix timezone mapping and iteration (#11077, #11079, #11080, #11083) + * Fix YUV reverse filter for AVC444 modes (#11045, #11063, #11066, #11081, #11086, + #11087) + * Fix H.264 encoder wrapper issues (#11117, #11121, #11078) + * MS-RDPECAM: Support for H.264 encoding with VA-API (#10887) + * Fix various CMake, build script and github workflow issues (#10992, #10996, + #11020, #11031, #11030, #11062, #11064, #11069, #11073, #11123, #11109, + #11120, #11053, #11089) + * [codec,planar] fix decoder regression (#11033) + * [client,cmdline] fix vmconnect checks (#11051) + * Fix multi-monitor related checks (#11095) + * Fix various compiler and clang-tidy warnings (#10953, #11003, #11004, + #11007, #11016, #11018, #11019, #11021, #11017, #11000, #11023, #11024, + #11026, #11002, #11028, #11001, #11029, #10999, #11006, #11034, #10998, + #11044, #11050, #11052, #11057, #11059, #11065, #11067, #11068, #11060, + #11071, #11085, #11088, #11099, #11102, #11108, #11124, #11126, #11129, + #11130) + +New Contributors + * @chewi made their first contribution in https://github.com/FreeRDP/FreeRDP/pull/11004 + * @gpotter2 made their first contribution in https://github.com/FreeRDP/FreeRDP/pull/11016 + * @vmpn made their first contribution in https://github.com/FreeRDP/FreeRDP/pull/11092 + +For a complete and detailed change log since the last release run: +git log 3.11.0...3.10.3 + + +# 2024-12-17 Version 3.10.3 + +Follow up release to 3.10.2, as we've discovered a few bugs after release. + +Noteworthy changes: + * Fix usage of GetComputerNameExA (#10988) + * Fix cmake clean target (#10990) + +For a complete and detailed change log since the last release run: +git log 3.10.3...3.10.2 + +# 2024-12-16 Version 3.10.2 + +Follow up release to 3.10.1, as we've discovered a few bugs during release +tests. + +Noteworthy changes: + * Fix initializing ComputerName setting (#10985) + * Fix some warnings and possible leaks (#10985) + +For a complete and detailed change log since the last release run: +git log 3.10.2...3.10.1 + +# 2024-12-16 Version 3.10.1 + +We're happy to present a new release of FreeRDP. +This release contains a few fixes for bugs revealed by checks introduced +with 3.10.0 + +Noteworthy Changes: + * Add FreeBSD as architecture build to our ci (#10980 and others) + * Fix empty include directory creation (#10981) + * fix SIMD detection (#10968) + * improve settings unit test coverage (#10966) + * fix sending server redirection PDU (#10963) + * fix return and use of GetComputerNameA (#10962) + +For a complete and detailed change log since the last release run: +git log 3.10.1...3.10.0 + +# 2024-12-12 Version 3.10.0 + +We're happy to present a new release of FreeRDP. +This one contains some more code cleanups (we've addressed lots of clang-tidy +warnings) as well as some highly anticipated new features and bugfixes. + +So, what is new: +* Enforce use of a supported build type (#10777) +* Enable FDK-AAC support for nightly packages (#10875, #10781) +* Better AAD/AVD support (#10796) +* Build system updates (#10844) +* Enforce spell checking (#10881) +* Split unit tests so a subset can be run during package build (#10776) +* We're shipping a .desktop file now (#10465) +* Build scripts for nightly packages (#10835, #10783) + +Noteworthy changes: +* Fix wStream API bugs (#10885) +* Autoreconnect fixes (#10915) +* Fix monitor layout checks (#10905) +* Enforce code formatting for CMake files (#10895) +* Enable SIMD optimizations by default (#10894) +* WinPR types not based on stdint.h et al (#10754) +* Improve code assertions (#10768) +* Code cleanups (#10763, #10914) + +For a complete and detailed change log since the last release run: +git log 3.10.0...3.9.0 + + +# 2024-10-21 Version 3.9.0 + +We're proud to present the newest release of FreeRDP. +This one brings some major code cleanup (we've addressed lots of clang-tidy +warnings) as well as some highly anticipated new features. +We also did update the API documentation quite a bit (still incomplete though, +help always welcome ;)) + +So, what is new: +* Support for RDPEAR (remote credential guard) /remoteGuard option for non windows clients +* Global configuration file support, allowing to configure certificate + accept/ignore/... default settings for all users +* Simplified manpage generation, eliminates docbook and xmlto dependencies + speeding up builds +* New API for client channels to run tasks on RDP thread +* New extended transport layer API +* RDPECAM MJPEG support +* the first updates of timezone definitions from our automated ci + +Noteworthy changes: +* Fix bugs in SSE4.1/AVX2 image copy (#10720) +* Add warnings for invalid monitor settings during connect (#10672) +* Fix ALSA microphone support (#10664) +* Fix modal windows in RAILS mode (#10629) +* Update experimental SDL3 client (SDL3 API should now have been stabilized, + various pull requests) +* Fix keyboard layouts, the external JSON did miss a few (#10639) + +For a complete and detailed change log since the last release run: +git log 3.9.0...3.8.0 + +# 2024-08-30 Version 3.8.0 + +This is a bugfix release. Due to additional exports required by a bugfix the minor version was incremented + +Noteworthy changes: +* Reduce number of warnings on CI build (make dependency includes SYSTEM) (#10509) +* Fix possible crashes with P11 certificate parsing (#10462, #10463) +* Various clipboard related fixes (#10472, #10476, #10477, #10480, #10484) +* Fix a race condition on DesktopResize (xfreerdp) (#10488) +* Improve certificate warnings (#10489) +* Try all possible resolved IP addresses for a DNS name on connect (#10491) +* Fix an issue with GFX SolidFill alpha data (#10498) +* Various fixes for SDL clients (#10504, #10492, #10471) +* Fix serial and parallel redirection crashes (#10510) +* Fix android build issues with NDK 27 (#10529) +* Improve performance of some WinPR primitives (#10528) +* Fix an issue with autoreconnect (#10523) +* Support ssh-askpass like password reading (#10516) +* Lots of code cleanups to reduce clang-tidy warnings (#10531, #10525, #10521, #10520, #10519, #10518) + +For a complete and detailed change log since the last release run: +git log 3.8.0...3.7.0 + +# 2024-08-08 Version 3.7.0 + +This release has accumulated quite a number of changes. Along bugfixes for 3.6.3 it also +contains a number of improvements for distributors: + +* Support for FDK-AAC for sound and microphone redirection (activate with -DWITH_FDK_AAC=ON build option) + This allows enabling the AAC compression that do not ship faad2 and/or faac +* Support keyboard layouts as JSON resources (activate with -DWITH_KEYBOARD_LAYOUT_FROM_FILE=ON build option, + also requires JSON support) + This allows editing keyboard layouts for existing releases should the need arise +* Support timezones as JSON resources (activate with -DWITH_TIMEZONE_FROM_FILE=ON -DWITH_TIMEZONE_COMPILED=OFF build options, + also requires JSON support) + Allows reading the mapping between IANA and windows timezones from a JSON file, allowing easier updates without recompile +* Improve shadow server compatibility with windows 11 24H2 RDP client + Windows 7 RFX and bitmap updates with multiple rectangles have been deactivated, so adjust shadow to not send such. + +Noteworthy changes: +* Fix ActionScript parameter (#10423) +* Support keyboard layouts as JSON resource (#10394) +* Support timezones as JSON resource and command line argument (#10428 #10393 #10391) +* Deactivate AsyncUpdate (#10402) +* Compatibility fixes for shadow with windows 11 24H2 (#10455 #10422 #10420 #10416) +* Fix SDL client autoreconnect (#10390) +* Fix xfreerdp clipboard locking (#10385) +* Improve logging (#10426 #10441) +* Improve warnings and code checks (#10381 #10401 #10403 #10405 #10406 #10410 #10421 #10454) +* Support FDK-AAC (#10372) +* Fix drive redirection state transitions (#10367 #10374) +* Support mth:// routing token (#10366) +* Ignore unsupported SetThreadPriority (#10363) +* Fix reported documentation and code typos (#10365 #10368 #10370 #10369 #10431 #10446) + +For a complete and detailed change log since the last release run: +git log 3.7.0...3.6.3 + +# 2024-07-08 Version 3.6.3 + +Bugfix release for 3.6.2 issues reported + +Noteworthy changes: +* fix a graphics regression (#10352) +* workaround for a protocol bug of older FreeRDP based servers (#10358) +* fix possible NULL dereference in command line parser (#10348) +* fix intrinsics detection (#10346, #10350) + +For a complete and detailed change log since the last release run: +git log 3.6.3...3.6.2 + + +# 2024-07-04 Version 3.6.2 + +Bugfix release for 3.6.1 issues detected during release tests + +Noteworthy changes: +* Fix xfreerdp and sdl-freerdp manpage names (accidentally changed name) +* Fix crash of wfreerdp + +For a complete and detailed change log since the last release run: +git log 3.6.2...3.6.1 + + +# 2024-07-04 Version 3.6.1 + +Bugfix release for 3.6.0 + +Noteworthy changes: +* Fix missing dependency for ci abi-checker +* Fix build WITH_SSE2/WITH_NEON: only enable support if the compiler + also defines symbols that suggest support. +* Fix incomplete changelog for 3.6.0: + * Improved image copy (#10208) + * Experimental [MS-RDPECAM] support by @oleg0421 (#10258) + * Improved primitives (#10304) + * Connection timeout for HTTP gateway transport (#10288) + +For a complete and detailed change log since the last release run: +git log 3.6.1...3.6.0 + + +# 2024-07-03 Version 3.6.0 + +With this release we did improve decoder speed so you should notice a significant +speed improvement with progressive and other gfx codecs. +We've also eliminated a couple of issues along the way, so an update +is highly recommended. + +Noteworthy changes: +* Improved command line failure logging (#10333) +* p11-kit support (#10081) +* json-c support (#10183) +* (experimental) SDL3 port SDL client (#10195) +* New option '/gfx:frame-ack:off' for connection delay testing (#10214) +* improved decoder speed (#10222, #10235) +* xfreerdp floatbar hide bug (#10237) +* winpr-makecert month bug (#10236) +* kerberos kdcUrl check fixes (#10238) +* timezone updates (#10120, #10144, #10170) +* fixed a capability protocol violation bug (#10132) +* fix SDL client dialog bug terminating on credential dialog (#10134) +* some more oss-fuzz issues (#10126, #10141, #10148, #10161, #10239) +* rails popup window fixes (#10160) + + +For a complete and detailed change log since the last release run: +git log 3.6.0...3.5.1 + + +# 2024-04-22 Version 3.5.1 + +This release eliminates a bunch of issues detected during oss-fuzz runs. +The test coverage was increased and detected issues eliminates, so an update +is highly recommended. + +Noteworthy changes: +* Lots of fixes for oss-fuzz reports +* Timezone detection fixes (#10106) +* SDL key remapping support (#10103) +* Improved help (#10099) +* FreeBSD epoll detection fix (#10097) + +For a complete and detailed change log since the last release run: +git log 3.5.1...3.5.0 + +# 2024-04-16 Version 3.5.0 + +This release focus is on squashing bugs. +The improved test coverage and ci builds revealed a number of previously +unnoticed issues we have addressed and we also got a report from +Evgeny Legerov of Kaspersky Lab identifying a number of out of bound reads +in decoder components and one very nasty out of bound write. + +CVE: +CVE-2024-32041 [Low[ OutOfBound Read in zgfx_decompress_segment +CVE-2024-32039 [Moderate] Integer overflow & OutOfBound Write in clear_decompress_residual_data +CVE-2024-32040 [Low] integer underflow in nsc_rle_decode +CVE-2024-32458 [Low] OutOfBound Read in planar_skip_plane_rle +CVE-2024-32459 [Low] OutOfBound Read in ncrush_decompress +CVE-2024-32460 [Low] OutOfBound Read in interleaved_decompress + +Noteworthy changes: +* location channel support #9981, #9984, #10065 +* bugfixes for report from Evgeny Legerov of Kaspersky Lab #10077 +* fuzzer tests from Evgeny Legerov of Kaspersky Lab #10078 +* bugfixes for coverty scanner #10066, #10068, #10069, #10070, #10075 +* clipboard and generic locking fixes #10076 +* split autoreconnect support from enabling it #10063 +* various nightly and workflow fixes #10064, #10058, #10062 +* always set wm-class to app_id #10051 +* refactored and simplified CMake #10046, #10047 +* fix relative mouse event sending #10010 +* improve and unify check for APIs used (POSIX, win32, mac, ...) #9995 +* fix termination for gateway connections #9985 +* fix drivestoredirect RDP file setting, ignore invalid #9989 +* drop IPP support #10038 + +For a complete and detailed change log since the last release run: +git log 3.5.0...3.4.0 + +# 2024-03-14 Version 3.4.0 + +This release concentrates on improving test coverage and ci builds. +Some usability issues and inconvenient API functions were fixed on the way. + +New features have been introduced (stub for location channel) + +Noteworthy changes: +* fix a bug in RAIL mode not activating window focus (#9973) +* improve logging (#9969, #9943) +* OpenSSL <= 1.1.1 build fixes (#9897) +* improved help (#9899, #9905) +* improved MINGW support (#9914, #9915, #9919, #9964, #9965, #9920) +* fix right control ungrab for xfreerdp (#9960) +* fix RPATH option settings (#9963) +* fix SDL client screen updates (#9962, #9954) +* fix issues with childSession under windows (#9961, #9956, #9922) +* fix xfreerdp crash with +auth-only (#9947) +* fix windows printer channel (#9934) +* add support to enforce gateway policy (#9942) +* improve big endian support (#9927) +* ignore empty proxy environment variables (#9929) +* improve quoting support for command line (#9912) + +For a complete and detailed change log since the last release run: +git log 3.4.0...3.3.0 + + +# 2024-02-22 Version 3.3.0 + +This release concentrates on code cleanup and overall quality improvements. +Some usability issues and inconvenient API functions were fixed on the way. + +New features have been introduced (better image clipboard) but that stays +deactivated by default as we´re in a stable series. + +Check the new CMake options: +* PLUGIN_ABS_PATHS_DEFAULT disables loading of external channels from all + but a specified absolute plugin directory defined by FREERDP_PLUGIN_PATH +* WINPR_UTILS_IMAGE_PNG enables PNG support with libpng in winpr image/clipboard +* WITH_LODEPNG enables PNG support with lodepng library in winpr image/clipboard +* WINPR_UTILS_IMAGE_WEBP enables WEBP support in winpr image/clipboard +* WINPR_UTILS_IMAGE_JPEG enables JPEG support in winpr image/clipboard +* USE_EXECINFO enables or disables backtrace support with execinfo +* WITH_WEBVIEW now defaults to OFF on windows, apple and android (not implemented) + +Noteworthy changes: +* Improved image clipboard (xfreerdp, wlfreerdp) (#9873, #9826) +* Improved SDL client (#9875, #9887, #9883, #9878, #9792) +* Allow plugin loader to only use absolute paths (#9809) +* Improved TLS channel binding (#9838) +* Add GCC/clang attribute malloc wrapper WINPR_ATTR_MALLOC (#9863) +* Major clang-tidy code cleanups and bugfixes (#9799, #9834) +* Provide some defaults for wObject functions (#9799) +* Fix a bug in shadow with GFX breaking mstsc (#9818) +* Improved manpages and help (#9813, #9804) +* Blocking mode via transport IO interface (#9793) + +For a complete and detailed change log since the last release run: +git log 3.3.0...3.2.0 + +# 2024-01-19 Version 3.2.0 + +This release mostly addresses issues reported since the last release. +Fixing some usablity and build issues as well as adding API functions +that are needed from external projects + +Noteworthy changes: +* Fix proxy module load check (#9777) +* Improve kerberos error logging (#9771) +* Improve mac client keyboard handling (#9767) +* Add option to run client dynamic channel synchronous (#9764) +* Move huge struct to heap (#9763) +* Improved failure logging of license module (#9759) +* Improve server side gfx logging (#9757) +* Print shadow server help with printf instead of WLog (#9756) +* Fix SDL client timer initialization (#9754) +* Fix server peer message parsing (#9751) +* Enable NEON instructions if __ARM_NEON is defined (#9748) +* Add new proxy config file option TlsSecLevel (#9741) +* Improve android and mac os build scripts (#9735) +* Do not disable wayland support on BSD (#9730) +* Fix issues with assistance file parsing (#9727, #9728) +* Keyboard handling fixes for wayland client (#9725) +* Fix relative pkg-config file paths (#9720) +* Add new transport IO callback GetPublicKey (#9719) +* Fix wayland client scaling (#9715) + +For a complete and detailed change log since the last release run: +git log 3.2.0...3.1.0 + +# 2023-12-22 Version 3.1.0 + +A new 3.1.0 minor release for the new 3.0.0 series. +This contains bugfixes, adds (better) support for libressl and mbedtls and +brings a bunch of improvements for the SDL client. + +This comes with a price though, we now (optionally) require SDL_image if you +want to build the sdl-client + +Since there are multiple new features, some new files (man pages) and new +optional dependencies we´ve directly incremented the minor version. + +New CMake options: +* SDL_USE_COMPILED_RESOURCES (default ON) builds fonts and images into SDL + client. Set to OFF to install these resources as files. (was already part of + 3.0.0, but worth mentioning here) +* WITH_SDL_IMAGE_DIALOGS (default OFF) Show some nice icons for SDL client + connection dialogs. Requires SDL_image for build. +* WITH_BINARY_VERSIONING (default OFF) Similar as for libraries the binaries, + manpages and resource locations created by FreeRDP project are postfixed + with the API version. Recommended if packagers want to install the package + alongside FreeRDP 2 without conflicts. +* RDTK_FORCE_STATIC_BUILD (default OFF) Build and link RDTK statically into + shadow server. Recommended for packagers as this library is not really used + outside of FreeRDP-shadow. +* UWAC_FORCE_STATIC_BUILD (default OFF) Build and link UWAC statically into + wlfreerdp. Recommended for packagers as this library is not really used + outside of wlfreerdp. + +Noteworthy changes: +* Fix a nasty bug with relative mouse movement (#9677) +* LibreSSL support enhancements (#9691, #9670) +* mbedTLS support enhancements (#9662) +* Improve building on mac OS (#9641) +* New and improved manpages (#9690, #9650) +* Unify CMake common options, add (optional) binary versioning and allow + building rdtk and uwac as static dependencies (#9695) +* SDL client improvements (#9693, #9657, #9659, #9683, #9680, #9657, #9664, + #9656) + +For a complete and detailed change log since the last release run: +git log 3.1.0...3.0.0 + +# 2023-12-12 Version 3.0.0 + +Final 3.0.0 release just a little over two weeks after the last 3.0.0-rc0. +This contains bugfixes, drops some legacy code, implements a small feature +request and adds some improvements to the build system. + +Most notably is the new PreventInSourceBuilds.cmake which does exactly what +the name implies, it aborts builds where source equals build directory. +If you can not use out of source tree builds for some reason, you can +circumvent this measure with the CMake setting -DALLOW_IN_SOURCE_BUILD=ON + +Noteworthy changes: +* add support for AF_VSOCK #9561 +* xfreerdp drop X11 GDI implementation #9492 +* fixed connection freeze with childSession #9594 +* fixed relative mouse input issues #9608 +* fixed issues with drive redirection #9610 +* simplified mac build #9601 +* fixed TSMF to build again #9603 +* fixed command line /gfx parsing bug #9598 +* prevent in source tree build #9550 +* fixed various issues with settings #9595, #9596 +* add E2K cpu support in WinPR #9599 +* fixed wfreerdp DPI settings when used as embedded window #9593 +* android add mouse hover support #9495 + +For a complete and detailed change log since the last release run: +git log 3.0.0..3.0.0-rc0 + +# 2023-11-27 Version 3.0.0-rc0 + +Nearly 2 months of testing, bugfixing and API refinements later we´re +happy to announce the first release candidate for FreeRDP 3.0 +The API should now be considered stable and only minor changes (if at all) +will happen from this point on, so every project using FreeRDP can check +compatibility with upcoming 3.0 + +Noteworthy changes: +* Updated rdpSettings API #9465: + * getter/setter now use enum types for keys (generates compiler warnings for mismatch) + * Refined functions (added missing, dropped problematic ones) + * prepared opaque settings (direct struct access now deprecated) +* Server side [MS-RDPEL] channel #9471 +* Relative mouse movement support #9459 +* relocatable pkg-config files (enable with -DPKG_CONFIG_RELOCATABLE=ON, #9453) +* cliprdr dropped support for fuse2 (#9453) +* added support for uriparser for clipboard file:// parsing (#9455) +* aFreeRDP translation for traditional chinese (zh-rTW) added (#9450) +* fixed sdl-freerdp crash on credential dialog (#9455) +* fixed sdl-freerdp alt+tab in fullscreen (#9442) +* added /connect-child-session option (WIN32 only, #9427) +* fix rfx-image codec setup (#9425) +* added missing cmake configuration for winpr-tools (#9453) +* cleaned up cmake configuration files, dropped no longer required ones (#9455) +* fixed x11 keyboard layout detection (#9433) +* add missing API calls for server implementation (tested against ogon, #9453) +* keep dynamic channels in a hash table instead of a list (#9448) +* keep TSCredentials in server peer instance (#9430) +* fix FFMPEG/AAC encoding (#9576) +* support remote credential guard (#9574) +* fix printing on mac os 14 (#9569) +* improve RPC gateway support (#9508) +* add opus audio support for gnome-remote-desktop (#9575) +* server side handling of mouse cursor channel [MS-RDPEMSC] (#9513) + +For a complete and detailed change log since the last release run: +git log 3.0.0-rc0..3.0.0-beta4 + +# 2023-09-31 Version 3.0.0-beta4 + +Noteworthy changes: +* Improved and fixed AVD authentication, now allows retries for + machines just starting up +* Improve RDP file parser, prepare new fields used by AVD +* Fixed and improved pen support in multitouch implementation (xfreerdp) +* Lots of smaller code and leak cleanups + +For a complete and detailed change log since the last release run: +git log 3.0.0-beta4..3.0.0-beta3 + +# 2023-08-31 Version 3.0.0-beta3 + +Noteworthy changes: +* fix xfreerdp keyboard on mac os +* Various crashes and input check fixes +* Improved logging of autodetect, redirection and fastpath failures +* Smartcard emulation now selectable at runtime +* Allow certificates without a subject to pass client checks +* Fix FindFirstFile issues on android +* Add FREERDP_ENTRY_POINT to silence -Wmissing-prototypes warnings for + library entry points +* Add WINPR_RESTRICT to enable restrict (C99) or __restring (MSVC) + keywords for compiler +* Fix support for older OpenSSL versions + +For a complete and detailed change log since the last release run: +git log 3.0.0-beta3..3.0.0-beta2 + +# 2023-08-03 Version 3.0.0-beta2 + +Noteworthy changes: +* Update CMake defaults, now all features are enabled by default with a platform + independent option if multiple are available. +* SDL client: (basic) multimonitor support +* SDL client: fix dialog cleanup order (crash fix) +* clipboard: fix FUSE shutdown crash +* fixed drive redirection: FindNextFile did miss some files/directories +* improved AAD support: honor rdp file options +* improved (gateway) http failure logging +* improved shadow server error handling +* improved CMake configuration (using find_dependency) +* updated timezone definitions +* mbedTLS build fixed +* improved MINGW build support + +For a complete and detailed change log since the last release run: +git log 3.0.0-beta2..3.0.0-beta1 + +# 2023-07-21 Version 3.0.0-beta1 + +We are pleased to announce the first beta release for the next stable 3.0 +series of FreeRDP. It has been a huge endeavour to implement all the new +shiny bells and whistles as well as clean up the code base and we´re still +ironing out some smaller glitches. +This is the first API breaking change since the 2.0 series and there are +some adjustments to be made for existing applications. +See https://github.com/FreeRDP/FreeRDP/wiki/FreeRDP3-migration-notes for +help (still incomplete) + +Noteworthy changes: +* Support for AAD/AVD authentication +* Support for websocket transport +* Support smartcard authentication (TLS and NLA) +* Full smartcard emulation support (login with certificate + key) +* Rewritten proxy, new module API +* New reference client based on SDL2 (work in progress) +* Rewritten logging, now parsing issues are all writing to the log so + that issues with protocol incompatibilities can be easier analyzed + by just turning on logging +* Full OpenSSL 3 support +* Internal implementations for RC4, MD4 and MD5 (required for non critical + parts in RDP but not part of more recent SSL libraries) +* Updated RDP protocol support +* Improved xfreerdp remote app support +* Reworked internal state machine for both client and server implementations +* Server implementations can now make use of connect-time network autodetection +* Improved clipboard handling, now also support server-to-client file transfer + (currently xfreerdp only) +* EnhancedRemoteApp support: Utilizing the more modern standard allows remote + apps with less glitches and window shadows +* Added client- and server-side handling for RDSTLS +* Support for the graphics redirection channel + +For a complete and detailed change log since the last release run: +git log 3.0.0-beta1..2.10.0 + + diff --git a/local-test-freerdp-full-01/afc-freerdp/LICENSE b/local-test-freerdp-full-01/afc-freerdp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/local-test-freerdp-full-01/afc-freerdp/README.md b/local-test-freerdp-full-01/afc-freerdp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..303b093ebbda79e47161b162d8c7b1d1b3917266 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/README.md @@ -0,0 +1,44 @@ +# FreeRDP: A Remote Desktop Protocol Implementation + +FreeRDP is a free implementation of the Remote Desktop Protocol (RDP), released under the Apache license. +Enjoy the freedom of using your software wherever you want, the way you want it, in a world where +interoperability can finally liberate your computing experience. + +## Code Quality Status + +[![abi-checker](https://github.com/FreeRDP/FreeRDP/actions/workflows/abi-checker.yml/badge.svg)](https://github.com/FreeRDP/FreeRDP/actions/workflows/abi-checker.yml) +[![clang-tidy-review](https://github.com/FreeRDP/FreeRDP/actions/workflows/clang-tidy.yml/badge.svg?event=pull_request_target)](https://github.com/FreeRDP/FreeRDP/actions/workflows/clang-tidy.yml) +[![CodeQL](https://github.com/FreeRDP/FreeRDP/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/FreeRDP/FreeRDP/actions/workflows/codeql-analysis.yml) +[![mingw-builder](https://github.com/FreeRDP/FreeRDP/actions/workflows/mingw.yml/badge.svg)](https://github.com/FreeRDP/FreeRDP/actions/workflows/mingw.yml) +[![[arm,ppc,ricsv] architecture builds](https://github.com/FreeRDP/FreeRDP/actions/workflows/alt-architectures.yml/badge.svg)](https://github.com/FreeRDP/FreeRDP/actions/workflows/alt-architectures.yml) +[![[freebsd] architecture builds](https://github.com/FreeRDP/FreeRDP/actions/workflows/freebsd.yml/badge.svg)](https://github.com/FreeRDP/FreeRDP/actions/workflows/freebsd.yml) +[![coverity](https://scan.coverity.com/projects/616/badge.svg)](https://scan.coverity.com/projects/freerdp) + +## Resources + +Project website: https://www.freerdp.com/ +Issue tracker: https://github.com/FreeRDP/FreeRDP/issues +Sources: https://github.com/FreeRDP/FreeRDP/ +Downloads: https://pub.freerdp.com/releases/ +Wiki: https://github.com/FreeRDP/FreeRDP/wiki +API documentation: https://pub.freerdp.com/api/ + +Security policy: https://github.com/FreeRDP/FreeRDP/security/policy + +Matrix room : #FreeRDP:matrix.org (main) +XMPP channel: #FreeRDP#matrix.org@matrix.org (bridged) +IRC channel : #freerdp @ irc.oftc.net (bridged) +Mailing list: https://lists.sourceforge.net/lists/listinfo/freerdp-devel + +## Microsoft Open Specifications + +Information regarding the Microsoft Open Specifications can be found at: +https://www.microsoft.com/openspecifications/ + +A list of reference documentation is maintained here: +https://github.com/FreeRDP/FreeRDP/wiki/Reference-Documentation + +## Compilation + +Instructions on how to get started compiling FreeRDP can be found on the wiki: +https://github.com/FreeRDP/FreeRDP/wiki/Compilation diff --git a/local-test-freerdp-full-01/afc-freerdp/SECURITY.md b/local-test-freerdp-full-01/afc-freerdp/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..be4373e7cfabdeeeede9a795d97306c9d7800627 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/SECURITY.md @@ -0,0 +1,114 @@ +# FreeRDP Security Policies and Procedures + +This document describes the security policy and procedures for the [FreeRDP Project](https://github.com/FreeRDP/FreeRDP). +The following topics are covered: + + * [Supported Versions](#supported-versions) + * [Reporting a Vulnerability](#reporting-a-vulnerability) + * [Disclosure Procedure](#disclosure-procedure) + + +## Supported versions + +Security is very important for us therefore we try to provide security updates and support for +the latest stable version as well as for the development branch. +Since our development branch is, like the protocol itself, a moving target we won't request CVEs for issues that are *only* found on the development branch. + +The following table shows the currently supported versions: + +| Version | Branch | Supported | +| ------- |--------------| ------------------ | +| < 2.0.0 | stable-1.x | :x: | +| 2.x.x | stable-2.0 | :heavy_check_mark: | +| 3.x.x | stable-3.0 | :white_check_mark: | +| - | master | :white_check_mark: | + + +## Reporting a vulnerability + +**IMPORTANT**: Please, do not file security vulnerabilities as public issues on GitHub + +In advance: **Thank you** for reporting a security vulnerability and making FreeRDP more stable! We really appreciate your effort. +Please let us know who we should give the credit or attributions to. + + +If you have found a security vulnerability in FreeRDP you can either directly open an [Advisory on GitHub](https://github.com/FreeRDP/FreeRDP/security/advisories/new)[^1] or send us an email to mailto:security@freerdp.com + +In case of an email you can use the [FreeRDP security team GPG key](#reporting-gpg-key) for encrypted communication. + +Once we receive a report we will review it and respond as soon as possible. + +### + + +## Disclosure procedure + +When the FreeRDP team receives a report one of the team members will be assigned as primary contact. +The primary contact will do all further communications and coordinate the fix and release process. + +How your report will be handled: + +* When a report is received we will acknowledge the reception and review the reported issue(s) as soon as possible. +* Once confirmed we will determine the affected versions. If not reported via GitHub a [security advisory draft on GitHub](https://github.com/FreeRDP/FreeRDP/security/advisories) will be created for any issue. If it applies we will request a CVE. +* On a private branch we will fix the issue and check the code for any potential similar problem. +* After the fix is validated we will create and publish a new release for all supported versions and publish the advisories. + +## Reporting GPG key + +FreeRDP's security reporting public gpg key https://pub.freerdp.com/FreeRDP-security-team.pub.asc + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGBz+jsBEADaIM94hYfn/xDzncQwXl7/q6+06+ssqO3iUGqFr+0EPS+HxRjD +BeKjVRSkuo0+QLQoZgCwkoltEj1xRWNqCTDMA+oZkZH8L82eqCnUQqgCOyNWAVMH +6u6ValiZH3ruYxergBBHhyR4Ot2ia0xWN8MKTp+emLpzQ7goimGMo0mxR5FiDAdb +QKz1q5bgs3bb2pLpERNF+z13OS10Mzk1zdr++1pov5PWOTBRKmvBtPJKswmDpb0y +jQGeeqBFZwKzx0n6BTzDZtkqzTwvGhbm9Sb+qO0IO66IV8zQhPG/JUfDkByd6mX9 +Ykke0gxoRx54XqoRwZGNydOxMN6g3Oj1+ioWisltYLs/SzW20f3AMCoTeYyfjKtf +01refrA3aRfhDctvW5/s2LP0OEG2P/yQYXiGhK6uVxShz3Oa5dhFwiS8G63omZRH +AEqSk46EhAbbT4xfZ/Np209rhis4KW40cMMpI0F+XpyfT05ZQD6ytHTPgWTxv/OF +G9zy2ysT0kq+t+Hb+1RWQUq/2Dz9Lf6xLZPgqtyzg8xiFxZ4i1kf/VDWa3M76zn3 +qMcj3SPOxKY//wW70jCxf44yD38NvSa1M2Sz/K/RJKWkRWP/jhV1UHYusbzCmsvm +M9JkknNMJvGIjBDjHEVy6dlTaHQoHDY+Me9gsrEX0ZS9xXgAiB2IupabEwARAQAB +tEJGcmVlUkRQIFNlY3VyaXR5IFRlYW0gKGh0dHBzOi8vZnJlZXJkcC5jb20pIDxz +ZWN1cml0eUBmcmVlcmRwLmNvbT6JAk4EEwEKADgWIQRvuAE0sDt7JnxXu0o3Ibww +YbfjNAUCYHP6OwIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRA3IbwwYbfj +NPviD/43NLg7YfjAlvj5GipSmgelLwlIA+L/qbrf4NAB+NZ9oqp3bBdj4e5gZmiI +zd6bkANCqk21YiOE31medUfy+nfBQFVvj0oUg1X16C6RaIX5qA3Dwt5qBwKmDkT5 +j7JlxUS6Eluiau67ePiDYu2Wbp0qYuAmNUNL+Y2NCO9UJiy0Oq6YVXS971D5lC+a +SX0x9pizmFV3zro+l6/3kHTVbPednfX99yz9SZge64aWXo3MXVN8JD0lR3+92l99 +XsFDc+lGeR4azLFIqXC4Cr5Lbk34Hw/VwUC32xxFUaJ2ZmV3pA8bhCtBSxSmxnHS +H3hoBaD1WpuApbW8Psx6qsgoaSUdWsjluA4eQ5afJBf9O2NlT1mim5MAINY4PbWP +o4zq3p1ABVTzuB8tsGA9o6DeYVUUrj7lCv9STdGRhm0472BDkp/gvKMBoPgg3Qez +kvGKK7iVy8R/BOPjh9wP1art5JLVsralXGHA/5Ceid4ojKFzGIC9g3lnAPh+T/eM +duyY9XH4un1r73r6DRqUoczSfHYbxhKxWt0cRNdIadcXXusMPV/w4J4j55WcLrBE +5nopp/prJ5bYegUvRRrwVSFwLDxkE2dh68Zvlh5VWXIPFge0RPEAijYWR5qR2z+/ +VHgPYmliOnWFJN1rzekmWjKFtg5A57FkZyk3cp5x0/2xAX+TIbkCDQRgc/o7ARAA +vw53CoVkMzBlisSEETNdEKQMaiQ8BtbC438v/b1mOOeoE0YCfSW7RyflA/TXHOah +db0s3v/Kk2xmbjeMS9IJXlWviKKnOVMrMZvtJdQ4EKfqc5EpxNx7OiEofA/7n7Xs +1YEt6KjYaM/vgANl9HA2UXzqSFiRhkWjj1WA7vhqCWUArpAMGeCDYab2BBfp6Z4f +W9178N2vHH+Hh/uBwGUDnShU38GH8Nstkdcyw5puiJqNQBfZ1Fz9luzutp6zAgHz +WzobeRPZCCXs7CfxcvpkFS0ctOteQtIRIfP+jbDnldMmClQ87UVcKv0pCCJkMLNk +YUCMAb2UC2boCIf0omeeque4+FOphcO4+R/8jc6cYlQpgwUg2/IwBEEnCqtvo3qu +k6uzONhfWZPtUdJd158MGKGTogXVXGzoGzxIrKkZ4W1VuuMiEmhIQZO8e7/4Iz4a +Zp4qQXI8rsmNJN3lB5a7MWgrZ8mjllYRdfiTEvfQ+PiQqnG6PEHZ82om9kp555gs +15UqhjHAqRRtfXzQvZko0ngAxxZNVFPwK8LnxkyEPClRBC5eV3ljI8cvCfnWD01q +rCzSlSafFHCEUEQOhOrf/bBbXPkYTJw2KlumH5w9R6xQWgqneiD/+Qmqdclzdn36 +Pgbhyu6uSNZehbx5ptt/EM66JSAW7Q7W6Qnz5PNnHgEAEQEAAYkCNgQYAQoAIBYh +BG+4ATSwO3smfFe7SjchvDBht+M0BQJgc/o7AhsMAAoJEDchvDBht+M0JYUQALlV +dwmk6ZFq5dq0utWgutysL47b30BhYwNMVe0/6UW4h4TYaW6B3f58X7ik7EdYciyR +68eYfwKGhuv/y90QaGXJMU13XHpoInSaHQRhn5M/GkN16DBXdBok70Fh9Gx89Zhs +VKF3qwIVx5AO5CwrVA6F/iOiUEW31xiT7VFkbW1Cfl5H+M6nVXSR1bOdmxTObTz7 +CEeJMOVrZs36hVLMWLqZF0igVebO2AsDOY63fy/9MLn8ynCHhnAMvsm9ULWuFzGj +OsJezChduaHqPkopgwihe7jthUn4qWjABbbzKkS6HLBpGAfCzUun+lMpvIEUf+EJ +bpk7gj9xDEP6y96tV/dCeWb4p8N8webR8nVgsRxoEnfIdCkoB80iZGOzKfYYnvdz +ngs8MIL6dC4Nc1/t9ECV4O/w4uwIH65nC1ay0YOK/O/j2SEfnVHQmAuOsgTz+pBn +u6DIA2HsBzFdOCljtf3m4AeAaTbL7MBSDceApqg0lcrhjclqHJo1aJh3M6aVm3gq +yUt7y26Hkh/vYEJwW4gqRho4gb7BvjTZh5LUbrjmRtexFQ1eWM82u23yYS2L+y2Y +ejSKIKmJhXHqsgCVGYw5woZEEMzgpkoIWYG/Eoy+oVuU02QITh/Uc5VRsA9DuwSV +Vw2F8gu/fHiadawxWIhUH+plFVQZc1KwgPcIMW3S +=O0kP +-----END PGP PUBLIC KEY BLOCK----- +``` +[^1]: https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Android/BuildFlags.java.in b/local-test-freerdp-full-01/afc-freerdp/client/Android/BuildFlags.java.in new file mode 100644 index 0000000000000000000000000000000000000000..9b15e47ba707f0a1ea97063bf5d09f5731cb4b7a --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Android/BuildFlags.java.in @@ -0,0 +1,6 @@ +package com.freerdp.freerdpcore.utils; + +public class BuildFlags +{ + private final static boolean USE_OPENSSL_DEFAULT_NAMES = @USE_OPENSSL_DEFAULT_NAMES@; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..761c6247f09cfb121fbe0a3f36164e74af0b1718 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/CMakeLists.txt @@ -0,0 +1,126 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Clients +# +# Copyright 2012 Marc-Andre Moreau +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Clients + +include(CMakeDependentOption) +include(InstallFreeRDPDesktop) + +if(WITH_CLIENT_COMMON) + add_subdirectory(common) +endif() + +if(FREERDP_VENDOR AND WITH_CLIENT) + if(WIN32 AND NOT UWP) + add_subdirectory(Windows) + else() + if(WITH_SAMPLE) + add_subdirectory(Sample) + endif() + endif() + + if(WITH_CLIENT_SDL) + add_subdirectory(SDL) + endif() + + if(WITH_X11) + add_subdirectory(X11) + endif() + + if(WITH_WAYLAND AND WAYLAND_FOUND) + add_subdirectory(Wayland) + endif() + + if(APPLE) + if(IOS) + if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/iOS") + message(STATUS "Adding iOS client") + add_subdirectory(iOS) + endif() + else() + option(WITH_CLIENT_MAC "Build native mac client" ON) + if(WITH_CLIENT_MAC) + add_subdirectory(Mac) + endif() + endif() + endif() + + if(ANDROID) + message(STATUS "Android client module is built with Android Studio project") + endif() +endif() + +# Pick up other clients +if(WITH_CLIENT) + set(FILENAME "ModuleOptions.cmake") + file(GLOB FILEPATHS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*/${FILENAME}") + + foreach(FILEPATH ${FILEPATHS}) + if(${FILEPATH} MATCHES "^([^/]*)/+${FILENAME}") + string(REGEX REPLACE "^([^/]*)/+${FILENAME}" "\\1" FREERDP_CLIENT ${FILEPATH}) + set(FREERDP_CLIENT_ENABLED 0) + include(${FILEPATH}) + if(FREERDP_CLIENT_ENABLED) + if(NOT (${FREERDP_CLIENT_VENDOR} MATCHES "FreeRDP")) + list(APPEND FREERDP_EXTRA_CLIENTS ${FREERDP_CLIENT}) + if(${FREERDP_CLIENT_VENDOR} MATCHES "${VENDOR}") + set(CLIENT_VENDOR_PATH "client/${FREERDP_CLIENT}" PARENT_SCOPE) + endif() + endif() + endif() + endif() + endforeach() + + foreach(FREERDP_CLIENT ${FREERDP_EXTRA_CLIENTS}) + add_subdirectory(${FREERDP_CLIENT}) + endforeach() +endif() + +if(WITH_FUSE) + list(APPEND FREERDP_CLIENT_PC_PRIVATE_LIBS "-lfuse3") +endif() + +list(JOIN FREERDP_CLIENT_PC_PRIVATE_LIBS " " FREERDP_CLIENT_PC_PRIVATE_LIBS) +include(pkg-config-install-prefix) +cleaning_configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/freerdp-client.pc.in + ${CMAKE_CURRENT_BINARY_DIR}/freerdp-client${FREERDP_VERSION_MAJOR}.pc @ONLY +) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/freerdp-client${FREERDP_VERSION_MAJOR}.pc + DESTINATION ${PKG_CONFIG_PC_INSTALL_DIR} +) + +export(PACKAGE freerdp-client) + +setfreerdpcmakeinstalldir(FREERDP_CLIENT_CMAKE_INSTALL_DIR "FreeRDP-Client${FREERDP_VERSION_MAJOR}") + +configure_package_config_file( + FreeRDP-ClientConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ClientConfig.cmake + INSTALL_DESTINATION ${FREERDP_CLIENT_CMAKE_INSTALL_DIR} PATH_VARS FREERDP_INCLUDE_DIR +) + +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ClientConfigVersion.cmake VERSION ${FREERDP_VERSION} + COMPATIBILITY SameMajorVersion +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ClientConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/FreeRDP-ClientConfigVersion.cmake + DESTINATION ${FREERDP_CLIENT_CMAKE_INSTALL_DIR} +) + +install(EXPORT FreeRDP-ClientTargets DESTINATION ${FREERDP_CLIENT_CMAKE_INSTALL_DIR}) diff --git a/local-test-freerdp-full-01/afc-freerdp/client/FreeRDP-ClientConfig.cmake.in b/local-test-freerdp-full-01/afc-freerdp/client/FreeRDP-ClientConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..409dbed4ada0a2aa2d3a0a280ab59291dd98c124 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/FreeRDP-ClientConfig.cmake.in @@ -0,0 +1,16 @@ +include(CMakeFindDependencyMacro) +find_dependency(WinPR @FREERDP_VERSION@) +find_dependency(FreeRDP @FREERDP_VERSION@) +if("@WITH_SMARTCARD_EMULATE@") + find_dependency(ZLIB) +endif() + +@PACKAGE_INIT@ + +set(FreeRDP-Client_VERSION_MAJOR "@FREERDP_VERSION_MAJOR@") +set(FreeRDP-Client_VERSION_MINOR "@FREERDP_VERSION_MINOR@") +set(FreeRDP-Client_VERSION_REVISION "@FREERDP_VERSION_REVISION@") + +set_and_check(FreeRDP-Client_INCLUDE_DIR "@PACKAGE_FREERDP_INCLUDE_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/FreeRDP-ClientTargets.cmake") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f44ebac2c9347495be47ce5b05377d8868fcf0aa --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CMakeLists.txt @@ -0,0 +1,92 @@ +cmake_minimum_required(VERSION 3.13) + +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(MacFreeRDP-library VERSION ${FREERDP_DEFAULT_PROJECT_VERSION}) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +cmake_policy(SET CMP0026 OLD) +cmake_policy(SET CMP0045 OLD) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/) +include(CommonConfigOptions) + +find_library(FOUNDATION_LIBRARY Foundation REQUIRED) +find_library(COCOA_LIBRARY Cocoa REQUIRED) +find_library(APPKIT_LIBRARY AppKit REQUIRED) +find_library(IOKIT_LIBRARY IOKit REQUIRED) +find_library(COREGRAPHICS_LIBRARY CoreGraphics REQUIRED) + +set(EXTRA_LIBS ${COCOA_LIBRARY} ${FOUNDATION_LIBRARY} ${APPKIT_LIBRARY} ${IOKIT_LIBRARY}) + +set(XIBS CertificateDialog.xib PasswordDialog.xib) + +set(SOURCES "") + +set(OBJECTIVE_SOURCES + main.m + mf_client.m + MRDPCursor.m + MRDPView.m + Keyboard.m + Clipboard.m + CertificateDialog.m + PasswordDialog.m +) + +list(APPEND SOURCES ${OBJECTIVE_SOURCES}) + +set(HEADERS + mfreerdp.h + mf_client.h + MRDPCursor.h + MRDPView.h + Keyboard.h + Clipboard.h + CertificateDialog.h + PasswordDialog.h +) + +set(RESOURCES "en.lproj/InfoPlist.strings") + +# Include XIB file in Xcode resources. +if("${CMAKE_GENERATOR}" MATCHES "Xcode") + message(STATUS "Adding Xcode XIB resources for ${MODULE_NAME}") + list(APPEND RESOURCES ${XIBS}) + set(IS_XCODE ON) +endif() + +add_library(${PROJECT_NAME} ../common/client.c ${SOURCES} ${HEADERS} ${RESOURCES}) + +set(LIBS ${EXTRA_LIBS} freerdp-client) + +target_link_libraries(${PROJECT_NAME} PUBLIC ${LIBS}) + +set_target_properties(${PROJECT_NAME} PROPERTIES RESOURCE "${RESOURCES}") + +if(NOT IS_XCODE) + find_program(IBTOOL ibtool REQUIRED HINTS "/usr/bin" "${OSX_DEVELOPER_ROOT}/usr/bin") + + # Compile the .xib files using the 'ibtool' program with the destination being the app package + foreach(xib ${XIBS}) + get_filename_component(XIB_WE ${xib} NAME_WE) + set(NIB ${CMAKE_CURRENT_BINARY_DIR}/${XIB_WE}.nib) + list(APPEND NIBS ${NIB}) + + add_custom_command( + TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${IBTOOL} --errors --warnings --notices --output-format + human-readable-text --compile ${NIB} ${CMAKE_CURRENT_SOURCE_DIR}/${xib} + COMMENT "Compiling ${xib}" + ) + endforeach() + + install(FILES ${NIBS} DESTINATION ${CMAKE_INSTALL_DATADIR}) +endif() + +install(TARGETS ${PROJECT_NAME} COMPONENT client RESOURCE DESTINATION ${CMAKE_INSTALL_DATADIR}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +add_subdirectory(cli) diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.h new file mode 100644 index 0000000000000000000000000000000000000000..6c4455f78d7f5058d1b32a6b4eb59c9819ab33c2 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.h @@ -0,0 +1,60 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thicast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface CertificateDialog : NSWindowController +{ + @public + NSTextField *textCommonName; + NSTextField *textSubject; + NSTextField *textIssuer; + NSTextField *textFingerprint; + NSTextField *textMismatch; + NSTextField *messageLabel; + NSString *serverHostname; + + BOOL hostMismatch; + BOOL changed; + int result; +} +@property(retain) IBOutlet NSTextField *textCommonName; +@property(retain) IBOutlet NSTextField *textSubject; +@property(retain) IBOutlet NSTextField *textIssuer; +@property(retain) IBOutlet NSTextField *textFingerprint; +@property(retain) IBOutlet NSTextField *textMismatch; +@property(retain) IBOutlet NSTextField *messageLabel; + +- (IBAction)onAccept:(NSObject *)sender; +- (IBAction)onTemporary:(NSObject *)sender; +- (IBAction)onCancel:(NSObject *)sender; + +@property(retain) NSString *serverHostname; +@property(retain) NSString *commonName; +@property(retain) NSString *subject; +@property(retain) NSString *issuer; +@property(retain) NSString *fingerprint; +@property BOOL hostMismatch; +@property BOOL changed; +@property(readonly) int result; + +- (int)runModal:(NSWindow *)mainWindow; + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.m new file mode 100644 index 0000000000000000000000000000000000000000..152fbcd4353783db2112cfb9e2b41d8fb41203ef --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.m @@ -0,0 +1,135 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thicast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "CertificateDialog.h" +#import + +#import + +@interface CertificateDialog () + +@property int result; + +@end + +@implementation CertificateDialog + +@synthesize textCommonName; +@synthesize textFingerprint; +@synthesize textIssuer; +@synthesize textSubject; +@synthesize textMismatch; +@synthesize messageLabel; +@synthesize serverHostname; +@synthesize commonName; +@synthesize fingerprint; +@synthesize issuer; +@synthesize subject; +@synthesize hostMismatch; +@synthesize changed; +@synthesize result; + +- (id)init +{ + return [self initWithWindowNibName:@"CertificateDialog"]; +} + +- (void)windowDidLoad +{ + [super windowDidLoad]; + // Implement this method to handle any initialization after your window controller's window has + // been loaded from its nib file. + [self.window setTitle:self.serverHostname]; + if (self.changed) + [self.messageLabel setStringValue:[NSString stringWithFormat:@"Changed certificate for %@", + self.serverHostname]]; + else + [self.messageLabel setStringValue:[NSString stringWithFormat:@"New Certificate for %@", + self.serverHostname]]; + + if (!self.hostMismatch) + [self.textMismatch + setStringValue:[NSString stringWithFormat: + @"NOTE: The server name matches the certificate, good."]]; + else + [self.textMismatch + setStringValue:[NSString + stringWithFormat: + @"ATTENTION: The common name does not match the server name!"]]; + [self.textCommonName setStringValue:self.commonName]; + [self.textFingerprint setStringValue:self.fingerprint]; + [self.textIssuer setStringValue:self.issuer]; + [self.textSubject setStringValue:self.subject]; +} + +- (IBAction)onAccept:(NSObject *)sender +{ + [NSApp stopModalWithCode:1]; +} + +- (IBAction)onTemporary:(NSObject *)sender +{ + [NSApp stopModalWithCode:2]; +} + +- (IBAction)onCancel:(NSObject *)sender +{ + [NSApp stopModalWithCode:0]; +} + +- (int)runModal:(NSWindow *)mainWindow +{ + if ([mainWindow respondsToSelector:@selector(beginSheet:completionHandler:)]) + { + [mainWindow beginSheet:self.window completionHandler:nil]; + self.result = [NSApp runModalForWindow:self.window]; + [mainWindow endSheet:self.window]; + } + else + { + [NSApp beginSheet:self.window + modalForWindow:mainWindow + modalDelegate:nil + didEndSelector:nil + contextInfo:nil]; + self.result = [NSApp runModalForWindow:self.window]; + [NSApp endSheet:self.window]; + } + + [self.window orderOut:nil]; + return self.result; +} + +- (void)dealloc +{ + [textCommonName release]; + [textFingerprint release]; + [textIssuer release]; + [textSubject release]; + [messageLabel release]; + [serverHostname release]; + [commonName release]; + [fingerprint release]; + [issuer release]; + [subject release]; + [super dealloc]; +} + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.xib b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.xib new file mode 100644 index 0000000000000000000000000000000000000000..c154899f1c6fdce035a9d50c009bd73a47fac0de --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/CertificateDialog.xib @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.h new file mode 100644 index 0000000000000000000000000000000000000000..5883d3b09029892adfb841d8ebee3be4f05e5b6a --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.h @@ -0,0 +1,31 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "mfreerdp.h" +#import "mf_client.h" + +#import "freerdp/freerdp.h" +#import "freerdp/channels/channels.h" +#import "freerdp/client/cliprdr.h" + +int mac_cliprdr_send_client_format_list(CliprdrClientContext* cliprdr); + +void mac_cliprdr_init(mfContext* mfc, CliprdrClientContext* cliprdr); +void mac_cliprdr_uninit(mfContext* mfc, CliprdrClientContext* cliprdr); diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.m new file mode 100644 index 0000000000000000000000000000000000000000..e95424878ed834d086131898f07fccb7ed69dc2e --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Clipboard.m @@ -0,0 +1,432 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Clipboard.h" +#import "MRDPView.h" + +int mac_cliprdr_send_client_format_list(CliprdrClientContext *cliprdr) +{ + UINT32 formatId; + UINT32 numFormats; + UINT32 *pFormatIds; + const char *formatName; + CLIPRDR_FORMAT *formats; + CLIPRDR_FORMAT_LIST formatList = { 0 }; + + WINPR_ASSERT(cliprdr); + mfContext *mfc = (mfContext *)cliprdr->custom; + WINPR_ASSERT(mfc); + + pFormatIds = NULL; + numFormats = ClipboardGetFormatIds(mfc->clipboard, &pFormatIds); + + formats = (CLIPRDR_FORMAT *)calloc(numFormats, sizeof(CLIPRDR_FORMAT)); + + if (!formats) + return -1; + + for (UINT32 index = 0; index < numFormats; index++) + { + formatId = pFormatIds[index]; + formatName = ClipboardGetFormatName(mfc->clipboard, formatId); + + formats[index].formatId = formatId; + formats[index].formatName = NULL; + + if ((formatId > CF_MAX) && formatName) + formats[index].formatName = _strdup(formatName); + } + + formatList.common.msgFlags = 0; + formatList.numFormats = numFormats; + formatList.formats = formats; + formatList.common.msgType = CB_FORMAT_LIST; + + mfc->cliprdr->ClientFormatList(mfc->cliprdr, &formatList); + + for (UINT32 index = 0; index < numFormats; index++) + { + free(formats[index].formatName); + } + + free(pFormatIds); + free(formats); + + return 1; +} + +static int mac_cliprdr_send_client_format_list_response(CliprdrClientContext *cliprdr, BOOL status) +{ + CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse; + + formatListResponse.common.msgType = CB_FORMAT_LIST_RESPONSE; + formatListResponse.common.msgFlags = status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL; + formatListResponse.common.dataLen = 0; + + cliprdr->ClientFormatListResponse(cliprdr, &formatListResponse); + + return 1; +} + +static int mac_cliprdr_send_client_format_data_request(CliprdrClientContext *cliprdr, + UINT32 formatId) +{ + CLIPRDR_FORMAT_DATA_REQUEST formatDataRequest = { 0 }; + WINPR_ASSERT(cliprdr); + + mfContext *mfc = (mfContext *)cliprdr->custom; + WINPR_ASSERT(mfc); + + formatDataRequest.common.msgType = CB_FORMAT_DATA_REQUEST; + formatDataRequest.common.msgFlags = 0; + + formatDataRequest.requestedFormatId = formatId; + mfc->requestedFormatId = formatId; + (void)ResetEvent(mfc->clipboardRequestEvent); + + cliprdr->ClientFormatDataRequest(cliprdr, &formatDataRequest); + + return 1; +} + +static int mac_cliprdr_send_client_capabilities(CliprdrClientContext *cliprdr) +{ + CLIPRDR_CAPABILITIES capabilities; + CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet; + + capabilities.cCapabilitiesSets = 1; + capabilities.capabilitySets = (CLIPRDR_CAPABILITY_SET *)&(generalCapabilitySet); + + generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL; + generalCapabilitySet.capabilitySetLength = 12; + + generalCapabilitySet.version = CB_CAPS_VERSION_2; + generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES; + + cliprdr->ClientCapabilities(cliprdr, &capabilities); + + return 1; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT mac_cliprdr_monitor_ready(CliprdrClientContext *cliprdr, + const CLIPRDR_MONITOR_READY *monitorReady) +{ + mfContext *mfc = (mfContext *)cliprdr->custom; + + mfc->clipboardSync = TRUE; + mac_cliprdr_send_client_capabilities(cliprdr); + mac_cliprdr_send_client_format_list(cliprdr); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT mac_cliprdr_server_capabilities(CliprdrClientContext *cliprdr, + const CLIPRDR_CAPABILITIES *capabilities) +{ + CLIPRDR_CAPABILITY_SET *capabilitySet; + mfContext *mfc = (mfContext *)cliprdr->custom; + + for (UINT32 index = 0; index < capabilities->cCapabilitiesSets; index++) + { + capabilitySet = &(capabilities->capabilitySets[index]); + + if ((capabilitySet->capabilitySetType == CB_CAPSTYPE_GENERAL) && + (capabilitySet->capabilitySetLength >= CB_CAPSTYPE_GENERAL_LEN)) + { + CLIPRDR_GENERAL_CAPABILITY_SET *generalCapabilitySet = + (CLIPRDR_GENERAL_CAPABILITY_SET *)capabilitySet; + + mfc->clipboardCapabilities = generalCapabilitySet->generalFlags; + break; + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT mac_cliprdr_server_format_list(CliprdrClientContext *cliprdr, + const CLIPRDR_FORMAT_LIST *formatList) +{ + CLIPRDR_FORMAT *format; + mfContext *mfc = (mfContext *)cliprdr->custom; + + if (mfc->serverFormats) + { + for (UINT32 index = 0; index < mfc->numServerFormats; index++) + { + free(mfc->serverFormats[index].formatName); + } + + free(mfc->serverFormats); + mfc->serverFormats = NULL; + mfc->numServerFormats = 0; + } + + if (formatList->numFormats < 1) + return CHANNEL_RC_OK; + + mfc->numServerFormats = formatList->numFormats; + mfc->serverFormats = (CLIPRDR_FORMAT *)calloc(mfc->numServerFormats, sizeof(CLIPRDR_FORMAT)); + + if (!mfc->serverFormats) + return CHANNEL_RC_NO_MEMORY; + + for (UINT32 index = 0; index < mfc->numServerFormats; index++) + { + mfc->serverFormats[index].formatId = formatList->formats[index].formatId; + mfc->serverFormats[index].formatName = NULL; + + if (formatList->formats[index].formatName) + mfc->serverFormats[index].formatName = _strdup(formatList->formats[index].formatName); + } + + mac_cliprdr_send_client_format_list_response(cliprdr, TRUE); + + for (UINT32 index = 0; index < mfc->numServerFormats; index++) + { + format = &(mfc->serverFormats[index]); + + if (format->formatId == CF_UNICODETEXT) + { + mac_cliprdr_send_client_format_data_request(cliprdr, CF_UNICODETEXT); + break; + } + else if (format->formatId == CF_OEMTEXT) + { + mac_cliprdr_send_client_format_data_request(cliprdr, CF_OEMTEXT); + break; + } + else if (format->formatId == CF_TEXT) + { + mac_cliprdr_send_client_format_data_request(cliprdr, CF_TEXT); + break; + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_format_list_response(CliprdrClientContext *cliprdr, + const CLIPRDR_FORMAT_LIST_RESPONSE *formatListResponse) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_lock_clipboard_data(CliprdrClientContext *cliprdr, + const CLIPRDR_LOCK_CLIPBOARD_DATA *lockClipboardData) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_unlock_clipboard_data(CliprdrClientContext *cliprdr, + const CLIPRDR_UNLOCK_CLIPBOARD_DATA *unlockClipboardData) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_format_data_request(CliprdrClientContext *cliprdr, + const CLIPRDR_FORMAT_DATA_REQUEST *formatDataRequest) +{ + BYTE *data; + UINT32 size; + UINT32 formatId; + CLIPRDR_FORMAT_DATA_RESPONSE response = { 0 }; + + WINPR_ASSERT(cliprdr); + + mfContext *mfc = (mfContext *)cliprdr->custom; + WINPR_ASSERT(mfc); + + formatId = formatDataRequest->requestedFormatId; + data = (BYTE *)ClipboardGetData(mfc->clipboard, formatId, &size); + + response.common.msgFlags = CB_RESPONSE_OK; + response.common.dataLen = size; + response.requestedFormatData = data; + + if (!data) + { + response.common.msgFlags = CB_RESPONSE_FAIL; + response.common.dataLen = 0; + response.requestedFormatData = NULL; + } + + cliprdr->ClientFormatDataResponse(cliprdr, &response); + + free(data); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_format_data_response(CliprdrClientContext *cliprdr, + const CLIPRDR_FORMAT_DATA_RESPONSE *formatDataResponse) +{ + UINT32 formatId; + CLIPRDR_FORMAT *format = NULL; + mfContext *mfc = (mfContext *)cliprdr->custom; + MRDPView *view = (MRDPView *)mfc->view; + + if (formatDataResponse->common.msgFlags & CB_RESPONSE_FAIL) + { + (void)SetEvent(mfc->clipboardRequestEvent); + return ERROR_INTERNAL_ERROR; + } + + for (UINT32 index = 0; index < mfc->numServerFormats; index++) + { + if (mfc->requestedFormatId == mfc->serverFormats[index].formatId) + format = &(mfc->serverFormats[index]); + } + + if (!format) + { + (void)SetEvent(mfc->clipboardRequestEvent); + return ERROR_INTERNAL_ERROR; + } + + if (format->formatName) + formatId = ClipboardRegisterFormat(mfc->clipboard, format->formatName); + else + formatId = format->formatId; + + const size_t size = formatDataResponse->common.dataLen; + + ClipboardSetData(mfc->clipboard, formatId, formatDataResponse->requestedFormatData, size); + + (void)SetEvent(mfc->clipboardRequestEvent); + + if ((formatId == CF_TEXT) || (formatId == CF_OEMTEXT) || (formatId == CF_UNICODETEXT)) + { + formatId = ClipboardRegisterFormat(mfc->clipboard, "text/plain"); + + UINT32 dstSize = 0; + char *data = ClipboardGetData(mfc->clipboard, formatId, &dstSize); + + dstSize = strnlen(data, dstSize); /* we need the size without the null terminator */ + + NSString *str = [[NSString alloc] initWithBytes:(void *)data + length:dstSize + encoding:NSUTF8StringEncoding]; + free(data); + + NSArray *types = [[NSArray alloc] initWithObjects:NSPasteboardTypeString, nil]; + [view->pasteboard_wr declareTypes:types owner:view]; + [view->pasteboard_wr setString:str forType:NSPasteboardTypeString]; + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +mac_cliprdr_server_file_contents_request(CliprdrClientContext *cliprdr, + const CLIPRDR_FILE_CONTENTS_REQUEST *fileContentsRequest) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT mac_cliprdr_server_file_contents_response( + CliprdrClientContext *cliprdr, const CLIPRDR_FILE_CONTENTS_RESPONSE *fileContentsResponse) +{ + return CHANNEL_RC_OK; +} + +void mac_cliprdr_init(mfContext *mfc, CliprdrClientContext *cliprdr) +{ + cliprdr->custom = (void *)mfc; + mfc->cliprdr = cliprdr; + + mfc->clipboard = ClipboardCreate(); + mfc->clipboardRequestEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + + cliprdr->MonitorReady = mac_cliprdr_monitor_ready; + cliprdr->ServerCapabilities = mac_cliprdr_server_capabilities; + cliprdr->ServerFormatList = mac_cliprdr_server_format_list; + cliprdr->ServerFormatListResponse = mac_cliprdr_server_format_list_response; + cliprdr->ServerLockClipboardData = mac_cliprdr_server_lock_clipboard_data; + cliprdr->ServerUnlockClipboardData = mac_cliprdr_server_unlock_clipboard_data; + cliprdr->ServerFormatDataRequest = mac_cliprdr_server_format_data_request; + cliprdr->ServerFormatDataResponse = mac_cliprdr_server_format_data_response; + cliprdr->ServerFileContentsRequest = mac_cliprdr_server_file_contents_request; + cliprdr->ServerFileContentsResponse = mac_cliprdr_server_file_contents_response; +} + +void mac_cliprdr_uninit(mfContext *mfc, CliprdrClientContext *cliprdr) +{ + cliprdr->custom = NULL; + mfc->cliprdr = NULL; + + ClipboardDestroy(mfc->clipboard); + (void)CloseHandle(mfc->clipboardRequestEvent); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Credits.rtf b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Credits.rtf new file mode 100644 index 0000000000000000000000000000000000000000..41b9f401496220d64c772c38621acdae56518dd4 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Credits.rtf @@ -0,0 +1,21 @@ +{\rtf1\ansi\ansicpg1252\cocoartf1138\cocoasubrtf320 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;} +\vieww9600\viewh8400\viewkind0 +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720 + +\f0\b\fs24 \cf0 Engineering: +\b0 \ + Jay sorg\ + Marc-Andre Moreau\ + Vic Lee\ + Otvaio Salvador \ + Laxmikant Rashinkar\ + and others\ +\ + +\b Human Interface Design: +\b0 \ + Laxmikant Rashinkar\ + Jay Sorg\ +} \ No newline at end of file diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Info.plist b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Info.plist new file mode 100644 index 0000000000000000000000000000000000000000..fd111db68072f926ed23042b733d9bbe40c5da05 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Info.plist @@ -0,0 +1,30 @@ + + + + + NSCameraUsageDescription + This application requires camera access to redirect it to the remote host + NSMicrophoneUsageDescription + This application requires microphone access to redirect it to the remote host + CFBundleDevelopmentRegion + English + CFBundleIconFile + + CFBundleIdentifier + FreeRDP.Mac + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.h new file mode 100644 index 0000000000000000000000000000000000000000..27efcdf34c6ba1285f8358208363b0ff44ab1abd --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.h @@ -0,0 +1,27 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +enum APPLE_KEYBOARD_TYPE +{ + APPLE_KEYBOARD_TYPE_ANSI, + APPLE_KEYBOARD_TYPE_ISO, + APPLE_KEYBOARD_TYPE_JIS +}; + +enum APPLE_KEYBOARD_TYPE mac_detect_keyboard_type(void); diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.m new file mode 100644 index 0000000000000000000000000000000000000000..625142d566070ab0aa6c52f7fed92a2413800147 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/Keyboard.m @@ -0,0 +1,240 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "Keyboard.h" + +#include + +#include +#include + +typedef struct +{ + uint32_t ProductId; + enum APPLE_KEYBOARD_TYPE Type; +} APPLE_KEYBOARD_DESC; + +/* VendorID: 0x05AC (Apple, Inc.) */ + +static const APPLE_KEYBOARD_DESC APPLE_KEYBOARDS[] = { + { 0x200, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x201, APPLE_KEYBOARD_TYPE_ANSI }, /* USB Keyboard [Alps or Logitech, M2452] */ + { 0x202, APPLE_KEYBOARD_TYPE_ANSI }, /* Keyboard [ALPS] */ + { 0x203, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x204, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x205, APPLE_KEYBOARD_TYPE_ANSI }, /* Extended Keyboard [Mitsumi] */ + { 0x206, APPLE_KEYBOARD_TYPE_ANSI }, /* Extended Keyboard [Mitsumi] */ + { 0x207, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x208, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x209, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x20A, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x20B, APPLE_KEYBOARD_TYPE_ANSI }, /* Pro Keyboard [Mitsumi, A1048/US layout] */ + { 0x20C, APPLE_KEYBOARD_TYPE_ANSI }, /* Extended Keyboard [Mitsumi] */ + { 0x20D, APPLE_KEYBOARD_TYPE_ANSI }, /* Pro Keyboard [Mitsumi, A1048/JIS layout] */ + { 0x20E, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x20F, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x210, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x211, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x212, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x213, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x214, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x215, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x216, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x217, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x218, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x219, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x21A, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x21B, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x21C, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x21D, APPLE_KEYBOARD_TYPE_ANSI }, /* Aluminum Mini Keyboard (ANSI) */ + { 0x21E, APPLE_KEYBOARD_TYPE_ISO }, /* Aluminum Mini Keyboard (ISO) */ + { 0x21F, APPLE_KEYBOARD_TYPE_JIS }, /* Aluminum Mini Keyboard (JIS) */ + { 0x220, APPLE_KEYBOARD_TYPE_ANSI }, /* Aluminum Keyboard (ANSI) */ + { 0x221, APPLE_KEYBOARD_TYPE_JIS }, /* Aluminum Keyboard (JIS) */ + { 0x222, APPLE_KEYBOARD_TYPE_JIS }, /* Aluminum Keyboard (JIS) */ + { 0x223, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x224, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x225, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x226, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x227, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x228, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x229, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (MacBook Pro) (ANSI) */ + { 0x22A, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (MacBook Pro) (ISO) */ + { 0x22B, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (MacBook Pro) (JIS) */ + { 0x22C, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x22D, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x22E, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x22F, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x230, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (MacBook Pro 4,1) (ANSI) */ + { 0x231, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (MacBook Pro 4,1) (ISO) */ + { 0x232, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (MacBook Pro 4,1) (JIS) */ + { 0x233, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x234, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x235, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x236, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x237, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x238, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x239, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23A, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23B, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23C, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23D, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23E, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x23F, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x240, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x241, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x242, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x243, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x244, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x245, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x246, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x247, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x248, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x249, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x24A, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (MacBook Air) (ISO) */ + { 0x24B, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x24C, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x24D, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (MacBook Air) (ISO) */ + { 0x24E, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x24F, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x250, APPLE_KEYBOARD_TYPE_ISO }, /* Aluminium Keyboard (ISO) */ + { 0x251, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x252, APPLE_KEYBOARD_TYPE_ANSI }, /* Internal Keyboard/Trackpad (ANSI) */ + { 0x253, APPLE_KEYBOARD_TYPE_ISO }, /* Internal Keyboard/Trackpad (ISO) */ + { 0x254, APPLE_KEYBOARD_TYPE_JIS }, /* Internal Keyboard/Trackpad (JIS) */ + { 0x255, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x256, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x257, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x258, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x259, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25A, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25B, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25C, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25D, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25E, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x25F, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x260, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x261, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x262, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x263, APPLE_KEYBOARD_TYPE_ANSI }, /* Apple Internal Keyboard / Trackpad (MacBook Retina) */ + { 0x264, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x265, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x266, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x267, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x268, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x269, APPLE_KEYBOARD_TYPE_ANSI }, + { 0x26A, APPLE_KEYBOARD_TYPE_ANSI } +}; + +static enum APPLE_KEYBOARD_TYPE mac_identify_keyboard_type(uint32_t vendorID, uint32_t productID) +{ + enum APPLE_KEYBOARD_TYPE type = APPLE_KEYBOARD_TYPE_ANSI; + + if (vendorID != 0x05AC) /* Apple, Inc. */ + return type; + + if ((productID < 0x200) || (productID > 0x26A)) + return type; + + type = APPLE_KEYBOARDS[productID - 0x200].Type; + return type; +} + +enum APPLE_KEYBOARD_TYPE mac_detect_keyboard_type(void) +{ + CFSetRef deviceCFSetRef = NULL; + IOHIDDeviceRef inIOHIDDeviceRef = NULL; + IOHIDManagerRef tIOHIDManagerRef = NULL; + IOHIDDeviceRef *tIOHIDDeviceRefs = nil; + enum APPLE_KEYBOARD_TYPE type = APPLE_KEYBOARD_TYPE_ANSI; + tIOHIDManagerRef = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + + if (!tIOHIDManagerRef) + return type; + + IOHIDManagerSetDeviceMatching(tIOHIDManagerRef, NULL); + IOReturn tIOReturn = IOHIDManagerOpen(tIOHIDManagerRef, kIOHIDOptionsTypeNone); + + if (noErr != tIOReturn) + return type; + + deviceCFSetRef = IOHIDManagerCopyDevices(tIOHIDManagerRef); + + if (!deviceCFSetRef) + return type; + + CFIndex deviceIndex, deviceCount = CFSetGetCount(deviceCFSetRef); + tIOHIDDeviceRefs = malloc(sizeof(IOHIDDeviceRef) * deviceCount); + + if (!tIOHIDDeviceRefs) + return type; + + CFSetGetValues(deviceCFSetRef, (const void **)tIOHIDDeviceRefs); + CFRelease(deviceCFSetRef); + deviceCFSetRef = NULL; + + for (deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++) + { + CFTypeRef tCFTypeRef; + uint32_t vendorID = 0; + uint32_t productID = 0; + uint32_t countryCode = 0; + enum APPLE_KEYBOARD_TYPE ltype; + + if (!tIOHIDDeviceRefs[deviceIndex]) + continue; + + inIOHIDDeviceRef = tIOHIDDeviceRefs[deviceIndex]; + tCFTypeRef = IOHIDDeviceGetProperty(inIOHIDDeviceRef, CFSTR(kIOHIDVendorIDKey)); + + if (tCFTypeRef) + CFNumberGetValue((CFNumberRef)tCFTypeRef, kCFNumberSInt32Type, &vendorID); + + tCFTypeRef = IOHIDDeviceGetProperty(inIOHIDDeviceRef, CFSTR(kIOHIDProductIDKey)); + + if (tCFTypeRef) + CFNumberGetValue((CFNumberRef)tCFTypeRef, kCFNumberSInt32Type, &productID); + + tCFTypeRef = IOHIDDeviceGetProperty(inIOHIDDeviceRef, CFSTR(kIOHIDCountryCodeKey)); + + if (tCFTypeRef) + CFNumberGetValue((CFNumberRef)tCFTypeRef, kCFNumberSInt32Type, &countryCode); + + ltype = mac_identify_keyboard_type(vendorID, productID); + + if (ltype != APPLE_KEYBOARD_TYPE_ANSI) + { + type = ltype; + break; + } + } + + free(tIOHIDDeviceRefs); + + if (deviceCFSetRef) + { + CFRelease(deviceCFSetRef); + deviceCFSetRef = NULL; + } + + if (tIOHIDManagerRef) + CFRelease(tIOHIDManagerRef); + + return type; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.h new file mode 100644 index 0000000000000000000000000000000000000000..6b16d793fbc5c9c7b25da521c8cce6d977356d21 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.h @@ -0,0 +1,34 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2012 Thomas Goddard + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#include "freerdp/graphics.h" + +@interface MRDPCursor : NSObject +{ + @public + rdpPointer *pointer; + BYTE *cursor_data; + NSBitmapImageRep *bmiRep; + NSCursor *nsCursor; + NSImage *nsImage; +} + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.m new file mode 100644 index 0000000000000000000000000000000000000000..6df6267699674dcc8499b8a7cf7b121b905978ba --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPCursor.m @@ -0,0 +1,24 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2012 Thomas Goddard + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "MRDPCursor.h" + +@implementation MRDPCursor + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.h new file mode 100644 index 0000000000000000000000000000000000000000..d7d978f0e8e26347e7a0e3f189ebd66b69f6b40e --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.h @@ -0,0 +1,91 @@ +#ifndef FREERDP_CLIENT_MAC_MRDPVIEW_H +#define FREERDP_CLIENT_MAC_MRDPVIEW_H + +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2012 Thomas Goddard + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "mfreerdp.h" +#import "mf_client.h" +#import "Keyboard.h" + +#import + +@interface MRDPView : NSView +{ + mfContext *mfc; + NSBitmapImageRep *bmiRep; + NSMutableArray *cursors; + NSMutableArray *windows; + NSTimer *pasteboard_timer; + NSCursor *currentCursor; + NSRect prevWinPosition; + freerdp *instance; + rdpContext *context; + CGContextRef bitmap_context; + char *pixel_data; + int argc; + char **argv; + DWORD kbdModFlags; + BOOL initialized; + NSPoint savedDragLocation; + BOOL firstCreateWindow; + BOOL isMoveSizeInProgress; + BOOL skipResizeOnce; + BOOL saveInitialDragLoc; + BOOL skipMoveWindowOnce; + @public + NSPasteboard *pasteboard_rd; + NSPasteboard *pasteboard_wr; + int pasteboard_changecount; + int pasteboard_format; + int is_connected; +} + +- (int)rdpStart:(rdpContext *)rdp_context; +- (void)setCursor:(NSCursor *)cursor; +- (void)setScrollOffset:(int)xOffset y:(int)yOffset w:(int)width h:(int)height; + +- (void)onPasteboardTimerFired:(NSTimer *)timer; +- (void)pause; +- (void)resume; +- (void)releaseResources; + +@property(assign) int is_connected; + +@end + +BOOL mac_pre_connect(freerdp *instance); +BOOL mac_post_connect(freerdp *instance); +void mac_post_disconnect(freerdp *instance); +BOOL mac_authenticate_ex(freerdp *instance, char **username, char **password, char **domain, + rdp_auth_reason reason); + +DWORD mac_verify_certificate_ex(freerdp *instance, const char *host, UINT16 port, + const char *common_name, const char *subject, const char *issuer, + const char *fingerprint, DWORD flags); +DWORD mac_verify_changed_certificate_ex(freerdp *instance, const char *host, UINT16 port, + const char *common_name, const char *subject, + const char *issuer, const char *fingerprint, + const char *old_subject, const char *old_issuer, + const char *old_fingerprint, DWORD flags); + +int mac_logon_error_info(freerdp *instance, UINT32 data, UINT32 type); +#endif /* FREERDP_CLIENT_MAC_MRDPVIEW_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.m new file mode 100644 index 0000000000000000000000000000000000000000..bbb7610835893d4c27e466844fbfca42cbac72cb --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/MRDPView.m @@ -0,0 +1,1534 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2012 Thomas Goddard + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "mf_client.h" +#import "mfreerdp.h" +#import "MRDPView.h" +#import "MRDPCursor.h" +#import "Clipboard.h" +#import "PasswordDialog.h" +#import "CertificateDialog.h" + +#include +#include +#include +#include +#include + +#include + +#import "freerdp/freerdp.h" +#import "freerdp/types.h" +#import "freerdp/config.h" +#import "freerdp/channels/channels.h" +#import "freerdp/gdi/gdi.h" +#import "freerdp/gdi/dc.h" +#import "freerdp/gdi/region.h" +#import "freerdp/graphics.h" +#import "freerdp/client/file.h" +#import "freerdp/client/cmdline.h" +#import "freerdp/log.h" + +#import + +#define TAG CLIENT_TAG("mac") + +static BOOL mf_Pointer_New(rdpContext *context, rdpPointer *pointer); +static void mf_Pointer_Free(rdpContext *context, rdpPointer *pointer); +static BOOL mf_Pointer_Set(rdpContext *context, rdpPointer *pointer); +static BOOL mf_Pointer_SetNull(rdpContext *context); +static BOOL mf_Pointer_SetDefault(rdpContext *context); +static BOOL mf_Pointer_SetPosition(rdpContext *context, UINT32 x, UINT32 y); + +static BOOL mac_begin_paint(rdpContext *context); +static BOOL mac_end_paint(rdpContext *context); +static BOOL mac_desktop_resize(rdpContext *context); + +static void input_activity_cb(freerdp *instance); + +static DWORD WINAPI mac_client_thread(void *param); +static void windows_to_apple_cords(MRDPView *view, NSRect *r); +static CGContextRef mac_create_bitmap_context(rdpContext *context); + +@implementation MRDPView + +@synthesize is_connected; + +- (int)rdpStart:(rdpContext *)rdp_context +{ + rdpSettings *settings; + EmbedWindowEventArgs e; + [self initializeView]; + + WINPR_ASSERT(rdp_context); + context = rdp_context; + mfc = (mfContext *)rdp_context; + + instance = context->instance; + WINPR_ASSERT(instance); + + settings = context->settings; + WINPR_ASSERT(settings); + + EventArgsInit(&e, "mfreerdp"); + e.embed = TRUE; + e.handle = (void *)self; + PubSub_OnEmbedWindow(context->pubSub, context, &e); + NSScreen *screen = [[NSScreen screens] objectAtIndex:0]; + NSRect screenFrame = [screen frame]; + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, screenFrame.size.width)) + return -1; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, screenFrame.size.height)) + return -1; + [self enterFullScreenMode:[NSScreen mainScreen] withOptions:nil]; + } + else + { + [self exitFullScreenModeWithOptions:nil]; + } + + mfc->client_height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + mfc->client_width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + + if (!(mfc->common.thread = + CreateThread(NULL, 0, mac_client_thread, (void *)context, 0, &mfc->mainThreadId))) + { + WLog_ERR(TAG, "failed to create client thread"); + return -1; + } + + return 0; +} + +DWORD WINAPI mac_client_thread(void *param) +{ + @autoreleasepool + { + int status; + DWORD rc; + HANDLE events[16] = { 0 }; + HANDLE inputEvent; + DWORD nCount; + DWORD nCountTmp; + DWORD nCountBase; + rdpContext *context = (rdpContext *)param; + mfContext *mfc = (mfContext *)context; + freerdp *instance = context->instance; + MRDPView *view = mfc->view; + rdpSettings *settings = context->settings; + status = freerdp_connect(context->instance); + + if (!status) + { + [view setIs_connected:0]; + return 0; + } + + [view setIs_connected:1]; + nCount = 0; + events[nCount++] = mfc->stopEvent; + + if (!(inputEvent = + freerdp_get_message_queue_event_handle(instance, FREERDP_INPUT_MESSAGE_QUEUE))) + { + WLog_ERR(TAG, "failed to get input event handle"); + goto disconnect; + } + + events[nCount++] = inputEvent; + + nCountBase = nCount; + + while (!freerdp_shall_disconnect_context(instance->context)) + { + nCount = nCountBase; + { + if (!(nCountTmp = freerdp_get_event_handles(context, &events[nCount], 16 - nCount))) + { + WLog_ERR(TAG, "freerdp_get_event_handles failed"); + break; + } + + nCount += nCountTmp; + } + rc = WaitForMultipleObjects(nCount, events, FALSE, INFINITE); + + if (rc >= (WAIT_OBJECT_0 + nCount)) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed (0x%08X)", rc); + break; + } + + if (rc == WAIT_OBJECT_0) + { + /* stop event triggered */ + break; + } + + if (WaitForSingleObject(inputEvent, 0) == WAIT_OBJECT_0) + { + input_activity_cb(instance); + } + + { + if (!freerdp_check_event_handles(context)) + { + WLog_ERR(TAG, "freerdp_check_event_handles failed"); + break; + } + } + } + + disconnect: + [view setIs_connected:0]; + freerdp_disconnect(instance); + + ExitThread(0); + return 0; + } +} + +- (id)initWithFrame:(NSRect)frame +{ + self = [super initWithFrame:frame]; + + if (self) + { + // Initialization code here. + } + + return self; +} + +- (void)viewDidLoad +{ + [self initializeView]; +} + +- (void)initializeView +{ + if (!initialized) + { + cursors = [[NSMutableArray alloc] initWithCapacity:10]; + // setup a mouse tracking area + NSTrackingArea *trackingArea = [[NSTrackingArea alloc] + initWithRect:[self visibleRect] + options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | + NSTrackingCursorUpdate | NSTrackingEnabledDuringMouseDrag | + NSTrackingActiveWhenFirstResponder + owner:self + userInfo:nil]; + [self addTrackingArea:trackingArea]; + // Set the default cursor + currentCursor = [NSCursor arrowCursor]; + initialized = YES; + } +} + +- (void)setCursor:(NSCursor *)cursor +{ + self->currentCursor = cursor; + dispatch_async(dispatch_get_main_queue(), ^{ + [[self window] invalidateCursorRectsForView:self]; + }); +} + +- (void)resetCursorRects +{ + [self addCursorRect:[self visibleRect] cursor:currentCursor]; +} + +- (BOOL)acceptsFirstResponder +{ + return YES; +} + +- (void)mouseMoved:(NSEvent *)event +{ + [super mouseMoved:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + mf_scale_mouse_event(context, PTR_FLAGS_MOVE, x, y); +} + +- (void)mouseDown:(NSEvent *)event +{ + [super mouseDown:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + mf_press_mouse_button(context, 0, x, y, TRUE); +} + +- (void)mouseUp:(NSEvent *)event +{ + [super mouseUp:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + mf_press_mouse_button(context, 0, x, y, FALSE); +} + +- (void)rightMouseDown:(NSEvent *)event +{ + [super rightMouseDown:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + mf_press_mouse_button(context, 1, x, y, TRUE); +} + +- (void)rightMouseUp:(NSEvent *)event +{ + [super rightMouseUp:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + mf_press_mouse_button(context, 1, x, y, FALSE); +} + +- (void)otherMouseDown:(NSEvent *)event +{ + [super otherMouseDown:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + int pressed = [event buttonNumber]; + mf_press_mouse_button(context, pressed, x, y, TRUE); +} + +- (void)otherMouseUp:(NSEvent *)event +{ + [super otherMouseUp:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + int pressed = [event buttonNumber]; + mf_press_mouse_button(context, pressed, x, y, FALSE); +} + +- (void)scrollWheel:(NSEvent *)event +{ + UINT16 flags; + [super scrollWheel:event]; + + if (!self.is_connected) + return; + + float dx = [event deltaX]; + float dy = [event deltaY]; + /* 1 event = 120 units */ + UINT16 units = 0; + + if (fabsf(dy) > FLT_EPSILON) + { + flags = PTR_FLAGS_WHEEL; + units = fabsf(dy) * 120; + + if (dy < 0) + flags |= PTR_FLAGS_WHEEL_NEGATIVE; + } + else if (fabsf(dx) > FLT_EPSILON) + { + flags = PTR_FLAGS_HWHEEL; + units = fabsf(dx) * 120; + + if (dx > 0) + flags |= PTR_FLAGS_WHEEL_NEGATIVE; + } + else + return; + + /* Wheel rotation steps: + * + * positive: 0 ... 0xFF -> slow ... fast + * negative: 0 ... 0xFF -> fast ... slow + */ + UINT16 step = units; + if (step > 0xFF) + step = 0xFF; + + /* Negative rotation, so count down steps from top + * 9bit twos complement */ + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + step = 0x100 - step; + + mf_scale_mouse_event(context, flags | step, 0, 0); +} + +- (void)mouseDragged:(NSEvent *)event +{ + [super mouseDragged:event]; + + if (!self.is_connected) + return; + + NSPoint loc = [event locationInWindow]; + int x = (int)loc.x; + int y = (int)loc.y; + // send mouse motion event to RDP server + mf_scale_mouse_event(context, PTR_FLAGS_MOVE, x, y); +} + +static DWORD fixKeyCode(DWORD keyCode, unichar keyChar, enum APPLE_KEYBOARD_TYPE type) +{ + /** + * In 99% of cases, the given key code is truly keyboard independent. + * This function handles the remaining 1% of edge cases. + * + * Hungarian Keyboard: This is 'QWERTZ' and not 'QWERTY'. + * The '0' key is on the left of the '1' key, where '~' is on a US keyboard. + * A special 'i' letter key with acute is found on the right of the left shift key. + * On the hungarian keyboard, the 'i' key is at the left of the 'Y' key + * Some international keyboards have a corresponding key which would be at + * the left of the 'Z' key when using a QWERTY layout. + * + * The Apple Hungarian keyboard sends inverted key codes for the '0' and 'i' keys. + * When using the US keyboard layout, key codes are left as-is (inverted). + * When using the Hungarian keyboard layout, key codes are swapped (non-inverted). + * This means that when using the Hungarian keyboard layout with a US keyboard, + * the keys corresponding to '0' and 'i' will effectively be inverted. + * + * To fix the '0' and 'i' key inversion, we use the corresponding output character + * provided by OS X and check for a character to key code mismatch: for instance, + * when the output character is '0' for the key code corresponding to the 'i' key. + */ +#if 0 + switch (keyChar) + { + case '0': + case 0x00A7: /* section sign */ + if (keyCode == APPLE_VK_ISO_Section) + keyCode = APPLE_VK_ANSI_Grave; + + break; + + case 0x00ED: /* latin small letter i with acute */ + case 0x00CD: /* latin capital letter i with acute */ + if (keyCode == APPLE_VK_ANSI_Grave) + keyCode = APPLE_VK_ISO_Section; + + break; + } + +#endif + + /* Perform keycode correction for all ISO keyboards */ + + if (type == APPLE_KEYBOARD_TYPE_ISO) + { + if (keyCode == APPLE_VK_ANSI_Grave) + keyCode = APPLE_VK_ISO_Section; + else if (keyCode == APPLE_VK_ISO_Section) + keyCode = APPLE_VK_ANSI_Grave; + } + + return keyCode; +} + +- (void)flagsChanged:(NSEvent *)event +{ + if (!is_connected) + return; + + DWORD modFlags = [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + rdpInput *input = instance->context->input; + +#if defined(WITH_DEBUG_KBD) + WLog_DBG(TAG, "flagsChanged: modFlags: 0x%04X kbdModFlags: 0x%04X", modFlags, kbdModFlags); +#endif + + updateFlagStates(input, modFlags, kbdModFlags); + kbdModFlags = modFlags; +} + +- (void)keyDown:(NSEvent *)event +{ + DWORD keyCode; + DWORD keyFlags; + DWORD vkcode; + DWORD scancode; + unichar keyChar; + NSString *characters; + + if (!is_connected) + return; + + [self flagsChanged:event]; + + keyFlags = KBD_FLAGS_DOWN; + keyCode = [event keyCode]; + characters = [event charactersIgnoringModifiers]; + + if ([characters length] > 0) + { + keyChar = [characters characterAtIndex:0]; + keyCode = fixKeyCode(keyCode, keyChar, mfc->appleKeyboardType); + } + + vkcode = GetVirtualKeyCodeFromKeycode(keyCode, WINPR_KEYCODE_TYPE_APPLE); + scancode = GetVirtualScanCodeFromVirtualKeyCode(vkcode, 4); + keyFlags |= (scancode & KBDEXT) ? KBDEXT : 0; + scancode &= 0xFF; + vkcode &= 0xFF; + +#if defined(WITH_DEBUG_KBD) + WLog_DBG(TAG, "keyDown: keyCode: 0x%04X scancode: 0x%04X vkcode: 0x%04X keyFlags: %d name: %s", + keyCode, scancode, vkcode, keyFlags, GetVirtualKeyName(vkcode)); +#endif + + WINPR_ASSERT(instance->context); + freerdp_input_send_keyboard_event(instance->context->input, keyFlags, scancode); +} + +- (void)keyUp:(NSEvent *)event +{ + DWORD keyCode; + DWORD keyFlags; + DWORD vkcode; + DWORD scancode; + unichar keyChar; + NSString *characters; + + if (!is_connected) + return; + + [self flagsChanged:event]; + + keyFlags = KBD_FLAGS_RELEASE; + keyCode = [event keyCode]; + characters = [event charactersIgnoringModifiers]; + + if ([characters length] > 0) + { + keyChar = [characters characterAtIndex:0]; + keyCode = fixKeyCode(keyCode, keyChar, mfc->appleKeyboardType); + } + + vkcode = GetVirtualKeyCodeFromKeycode(keyCode, WINPR_KEYCODE_TYPE_APPLE); + scancode = GetVirtualScanCodeFromVirtualKeyCode(vkcode, 4); + keyFlags |= (scancode & KBDEXT) ? KBDEXT : 0; + scancode &= 0xFF; + vkcode &= 0xFF; +#if defined(WITH_DEBUG_KBD) + WLog_DBG(TAG, "keyUp: key: 0x%04X scancode: 0x%04X vkcode: 0x%04X keyFlags: %d name: %s", + keyCode, scancode, vkcode, keyFlags, GetVirtualKeyName(vkcode)); +#endif + WINPR_ASSERT(instance->context); + freerdp_input_send_keyboard_event(instance->context->input, keyFlags, scancode); +} + +static BOOL updateFlagState(rdpInput *input, DWORD modFlags, DWORD aKbdModFlags, DWORD flag) +{ + BOOL press = ((modFlags & flag) != 0) && ((aKbdModFlags & flag) == 0); + BOOL release = ((modFlags & flag) == 0) && ((aKbdModFlags & flag) != 0); + DWORD keyFlags = 0; + const char *name = NULL; + DWORD scancode = 0; + + if ((modFlags & flag) == (aKbdModFlags & flag)) + return TRUE; + + switch (flag) + { + case NSEventModifierFlagCapsLock: + name = "NSEventModifierFlagCapsLock"; + scancode = RDP_SCANCODE_CAPSLOCK; + release = press = TRUE; + break; + case NSEventModifierFlagShift: + name = "NSEventModifierFlagShift"; + scancode = RDP_SCANCODE_LSHIFT; + break; + + case NSEventModifierFlagControl: + name = "NSEventModifierFlagControl"; + scancode = RDP_SCANCODE_LCONTROL; + break; + + case NSEventModifierFlagOption: + name = "NSEventModifierFlagOption"; + scancode = RDP_SCANCODE_LMENU; + break; + + case NSEventModifierFlagCommand: + name = "NSEventModifierFlagCommand"; + scancode = RDP_SCANCODE_LWIN; + break; + + case NSEventModifierFlagNumericPad: + name = "NSEventModifierFlagNumericPad"; + scancode = RDP_SCANCODE_NUMLOCK; + release = press = TRUE; + break; + + case NSEventModifierFlagHelp: + name = "NSEventModifierFlagHelp"; + scancode = RDP_SCANCODE_HELP; + break; + + case NSEventModifierFlagFunction: + name = "NSEventModifierFlagFunction"; + scancode = RDP_SCANCODE_HELP; + break; + + default: + WLog_ERR(TAG, "Invalid flag: 0x%08" PRIx32 ", not supported", flag); + return FALSE; + } + + keyFlags = (scancode & KBDEXT); + scancode &= 0xFF; + +#if defined(WITH_DEBUG_KBD) + if (press || release) + WLog_DBG(TAG, "changing flag %s[0x%08" PRIx32 "] to %s", name, flag, + press ? "DOWN" : "RELEASE"); +#endif + + if (press) + { + if (!freerdp_input_send_keyboard_event(input, keyFlags | KBD_FLAGS_DOWN, scancode)) + return FALSE; + } + + if (release) + { + if (!freerdp_input_send_keyboard_event(input, keyFlags | KBD_FLAGS_RELEASE, scancode)) + return FALSE; + } + + return TRUE; +} + +static BOOL updateFlagStates(rdpInput *input, UINT32 modFlags, UINT32 aKbdModFlags) +{ + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagCapsLock); + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagShift); + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagControl); + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagOption); + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagCommand); + updateFlagState(input, modFlags, aKbdModFlags, NSEventModifierFlagNumericPad); + return TRUE; +} + +static BOOL releaseFlagStates(rdpInput *input, UINT32 aKbdModFlags) +{ + return updateFlagStates(input, 0, aKbdModFlags); +} + +- (void)releaseResources +{ + for (int i = 0; i < argc; i++) + free(argv[i]); + + if (!is_connected) + return; + + free(pixel_data); +} + +- (void)drawRect:(NSRect)rect +{ + if (!context) + return; + + if (self->bitmap_context) + { + CGContextRef cgContext = [[NSGraphicsContext currentContext] CGContext]; + CGImageRef cgImage = CGBitmapContextCreateImage(self->bitmap_context); + CGContextSaveGState(cgContext); + CGContextClipToRect( + cgContext, CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)); + CGContextDrawImage(cgContext, + CGRectMake(0, 0, [self bounds].size.width, [self bounds].size.height), + cgImage); + CGContextRestoreGState(cgContext); + CGImageRelease(cgImage); + } + else + { + /* Fill the screen with black */ + [[NSColor blackColor] set]; + NSRectFill([self bounds]); + } +} + +- (void)onPasteboardTimerFired:(NSTimer *)timer +{ + UINT32 formatId; + BOOL formatMatch; + int changeCount; + NSData *formatData; + NSString *formatString; + const char *formatType; + NSPasteboardItem *item; + changeCount = (int)[pasteboard_rd changeCount]; + + if (changeCount == pasteboard_changecount) + return; + + pasteboard_changecount = changeCount; + NSArray *items = [pasteboard_rd pasteboardItems]; + + if ([items count] < 1) + return; + + item = [items objectAtIndex:0]; + /** + * System-Declared Uniform Type Identifiers: + * https://developer.apple.com/library/ios/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html + */ + formatMatch = FALSE; + + for (NSString *type in [item types]) + { + formatType = [type UTF8String]; + + if (strcmp(formatType, "public.utf8-plain-text") == 0) + { + formatData = [item dataForType:type]; + + if (formatData == nil) + { + break; + } + + formatString = [[NSString alloc] initWithData:formatData encoding:NSUTF8StringEncoding]; + + const char *data = [formatString cStringUsingEncoding:NSUTF8StringEncoding]; + const size_t dataLen = [formatString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + formatId = ClipboardRegisterFormat(mfc->clipboard, "text/plain"); + ClipboardSetData(mfc->clipboard, formatId, data, dataLen + 1); + [formatString release]; + + formatMatch = TRUE; + + break; + } + } + + if (!formatMatch) + ClipboardEmpty(mfc->clipboard); + + if (mfc->clipboardSync) + mac_cliprdr_send_client_format_list(mfc->cliprdr); +} + +- (void)pause +{ + dispatch_async(dispatch_get_main_queue(), ^{ + [self->pasteboard_timer invalidate]; + }); + NSArray *trackingAreas = self.trackingAreas; + + for (NSTrackingArea *ta in trackingAreas) + { + [self removeTrackingArea:ta]; + } + releaseFlagStates(instance->context->input, kbdModFlags); + kbdModFlags = 0; +} + +- (void)resume +{ + if (!self.is_connected) + return; + + releaseFlagStates(instance->context->input, kbdModFlags); + kbdModFlags = 0; + freerdp_input_send_focus_in_event(instance->context->input, 0); + + dispatch_async(dispatch_get_main_queue(), ^{ + self->pasteboard_timer = + [NSTimer scheduledTimerWithTimeInterval:0.5 + target:self + selector:@selector(onPasteboardTimerFired:) + userInfo:nil + repeats:YES]; + + NSTrackingArea *trackingArea = [[NSTrackingArea alloc] + initWithRect:[self visibleRect] + options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | + NSTrackingCursorUpdate | NSTrackingEnabledDuringMouseDrag | + NSTrackingActiveWhenFirstResponder + owner:self + userInfo:nil]; + [self addTrackingArea:trackingArea]; + [trackingArea release]; + }); +} + +- (void)setScrollOffset:(int)xOffset y:(int)yOffset w:(int)width h:(int)height +{ + WINPR_ASSERT(mfc); + + mfc->yCurrentScroll = yOffset; + mfc->xCurrentScroll = xOffset; + mfc->client_height = height; + mfc->client_width = width; +} + +static void mac_OnChannelConnectedEventHandler(void *context, const ChannelConnectedEventArgs *e) +{ + rdpSettings *settings; + mfContext *mfc = (mfContext *)context; + + WINPR_ASSERT(mfc); + WINPR_ASSERT(e); + + settings = mfc->common.context.settings; + WINPR_ASSERT(settings); + + if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + mac_cliprdr_init(mfc, (CliprdrClientContext *)e->pInterface); + } + else if (strcmp(e->name, ENCOMSP_SVC_CHANNEL_NAME) == 0) + { + } + else + freerdp_client_OnChannelConnectedEventHandler(context, e); +} + +static void mac_OnChannelDisconnectedEventHandler(void *context, + const ChannelDisconnectedEventArgs *e) +{ + rdpSettings *settings; + mfContext *mfc = (mfContext *)context; + + WINPR_ASSERT(mfc); + WINPR_ASSERT(e); + + settings = mfc->common.context.settings; + WINPR_ASSERT(settings); + + if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + mac_cliprdr_uninit(mfc, (CliprdrClientContext *)e->pInterface); + } + else if (strcmp(e->name, ENCOMSP_SVC_CHANNEL_NAME) == 0) + { + } + else + freerdp_client_OnChannelDisconnectedEventHandler(context, e); +} + +BOOL mac_pre_connect(freerdp *instance) +{ + rdpSettings *settings; + rdpUpdate *update; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + update = instance->context->update; + WINPR_ASSERT(update); + + update->BeginPaint = mac_begin_paint; + update->EndPaint = mac_end_paint; + update->DesktopResize = mac_desktop_resize; + + settings = instance->context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_get_string(settings, FreeRDP_ServerHostname)) + { + WLog_ERR(TAG, "error: server hostname was not specified with /v:[:port]"); + return FALSE; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_MACINTOSH)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_MACINTOSH)) + return FALSE; + PubSub_SubscribeChannelConnected(instance->context->pubSub, mac_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(instance->context->pubSub, + mac_OnChannelDisconnectedEventHandler); + + return TRUE; +} + +BOOL mac_post_connect(freerdp *instance) +{ + rdpGdi *gdi; + rdpPointer rdp_pointer = { 0 }; + mfContext *mfc; + MRDPView *view; + + WINPR_ASSERT(instance); + + mfc = (mfContext *)instance->context; + WINPR_ASSERT(mfc); + + view = (MRDPView *)mfc->view; + WINPR_ASSERT(view); + + rdp_pointer.size = sizeof(rdpPointer); + rdp_pointer.New = mf_Pointer_New; + rdp_pointer.Free = mf_Pointer_Free; + rdp_pointer.Set = mf_Pointer_Set; + rdp_pointer.SetNull = mf_Pointer_SetNull; + rdp_pointer.SetDefault = mf_Pointer_SetDefault; + rdp_pointer.SetPosition = mf_Pointer_SetPosition; + + if (!gdi_init(instance, PIXEL_FORMAT_BGRX32)) + return FALSE; + + gdi = instance->context->gdi; + view->bitmap_context = mac_create_bitmap_context(instance->context); + graphics_register_pointer(instance->context->graphics, &rdp_pointer); + /* setup pasteboard (aka clipboard) for copy operations (write only) */ + view->pasteboard_wr = [NSPasteboard generalPasteboard]; + /* setup pasteboard for read operations */ + dispatch_async(dispatch_get_main_queue(), ^{ + view->pasteboard_rd = [NSPasteboard generalPasteboard]; + view->pasteboard_changecount = -1; + }); + [view resume]; + mfc->appleKeyboardType = mac_detect_keyboard_type(); + return TRUE; +} + +void mac_post_disconnect(freerdp *instance) +{ + mfContext *mfc; + MRDPView *view; + if (!instance || !instance->context) + return; + + mfc = (mfContext *)instance->context; + view = (MRDPView *)mfc->view; + + [view pause]; + + PubSub_UnsubscribeChannelConnected(instance->context->pubSub, + mac_OnChannelConnectedEventHandler); + PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub, + mac_OnChannelDisconnectedEventHandler); + gdi_free(instance); +} + +static BOOL mac_show_auth_dialog(MRDPView *view, NSString *title, char **username, char **password, + char **domain) +{ + WINPR_ASSERT(view); + WINPR_ASSERT(title); + WINPR_ASSERT(username); + WINPR_ASSERT(password); + WINPR_ASSERT(domain); + + PasswordDialog *dialog = [PasswordDialog new]; + + dialog.serverHostname = title; + + if (*username) + dialog.username = [NSString stringWithCString:*username encoding:NSUTF8StringEncoding]; + + if (*password) + dialog.password = [NSString stringWithCString:*password encoding:NSUTF8StringEncoding]; + + if (*domain) + dialog.domain = [NSString stringWithCString:*domain encoding:NSUTF8StringEncoding]; + + free(*username); + free(*password); + free(*domain); + *username = NULL; + *password = NULL; + *domain = NULL; + + dispatch_sync(dispatch_get_main_queue(), ^{ + [dialog performSelectorOnMainThread:@selector(runModal:) + withObject:[view window] + waitUntilDone:TRUE]; + }); + BOOL ok = dialog.modalCode; + + if (ok) + { + const char *submittedUsername = [dialog.username cStringUsingEncoding:NSUTF8StringEncoding]; + const size_t submittedUsernameLen = + [dialog.username lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + if (submittedUsername && (submittedUsernameLen > 0)) + *username = strndup(submittedUsername, submittedUsernameLen); + + if (!(*username)) + return FALSE; + + const char *submittedPassword = [dialog.password cStringUsingEncoding:NSUTF8StringEncoding]; + const size_t submittedPasswordLen = + [dialog.password lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + if (submittedPassword && (submittedPasswordLen > 0)) + *password = strndup(submittedPassword, submittedPasswordLen); + + if (!(*password)) + return FALSE; + + const char *submittedDomain = [dialog.domain cStringUsingEncoding:NSUTF8StringEncoding]; + const size_t submittedDomainLen = + [dialog.domain lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + if (submittedDomain && (submittedDomainLen > 0)) + { + *domain = strndup(submittedDomain, submittedDomainLen); + if (!(*domain)) + return FALSE; + } + } + + return ok; +} + +static BOOL mac_authenticate_raw(freerdp *instance, char **username, char **password, char **domain, + rdp_auth_reason reason) +{ + BOOL pinOnly = FALSE; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + const rdpSettings *settings = instance->context->settings; + mfContext *mfc = (mfContext *)instance->context; + MRDPView *view = (MRDPView *)mfc->view; + NSString *title = NULL; + + switch (reason) + { + case AUTH_SMARTCARD_PIN: + pinOnly = TRUE; + title = [NSString + stringWithFormat:@"%@:%u", + [NSString stringWithCString:freerdp_settings_get_string( + settings, FreeRDP_ServerHostname) + encoding:NSUTF8StringEncoding], + freerdp_settings_get_uint32(settings, FreeRDP_ServerPort)]; + break; + case AUTH_TLS: + case AUTH_RDP: + case AUTH_NLA: + title = [NSString + stringWithFormat:@"%@:%u", + [NSString stringWithCString:freerdp_settings_get_string( + settings, FreeRDP_ServerHostname) + encoding:NSUTF8StringEncoding], + freerdp_settings_get_uint32(settings, FreeRDP_ServerPort)]; + break; + case GW_AUTH_HTTP: + case GW_AUTH_RDG: + case GW_AUTH_RPC: + title = [NSString + stringWithFormat:@"%@:%u", + [NSString stringWithCString:freerdp_settings_get_string( + settings, FreeRDP_GatewayHostname) + encoding:NSUTF8StringEncoding], + freerdp_settings_get_uint32(settings, FreeRDP_GatewayPort)]; + break; + default: + return FALSE; + } + + if (!username || !password || !domain) + return FALSE; + + if (!*username && !pinOnly) + { + if (!mac_show_auth_dialog(view, title, username, password, domain)) + goto fail; + } + else if (!*domain && !pinOnly) + { + if (!mac_show_auth_dialog(view, title, username, password, domain)) + goto fail; + } + else if (!*password) + { + if (!mac_show_auth_dialog(view, title, username, password, domain)) + goto fail; + } + + return TRUE; +fail: + free(*username); + free(*domain); + free(*password); + *username = NULL; + *domain = NULL; + *password = NULL; + return FALSE; +} + +BOOL mac_authenticate_ex(freerdp *instance, char **username, char **password, char **domain, + rdp_auth_reason reason) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(username); + WINPR_ASSERT(password); + WINPR_ASSERT(domain); + + NSString *title; + switch (reason) + { + case AUTH_NLA: + break; + + case AUTH_TLS: + case AUTH_RDP: + case AUTH_SMARTCARD_PIN: /* in this case password is pin code */ + if ((*username) && (*password)) + return TRUE; + break; + case GW_AUTH_HTTP: + case GW_AUTH_RDG: + case GW_AUTH_RPC: + break; + default: + return FALSE; + } + + return mac_authenticate_raw(instance, username, password, domain, reason); +} + +DWORD mac_verify_certificate_ex(freerdp *instance, const char *host, UINT16 port, + const char *common_name, const char *subject, const char *issuer, + const char *fingerprint, DWORD flags) +{ + mfContext *mfc = (mfContext *)instance->context; + MRDPView *view = (MRDPView *)mfc->view; + CertificateDialog *dialog = [CertificateDialog new]; + const char *type = "RDP-Server"; + char hostname[8192] = { 0 }; + + if (flags & VERIFY_CERT_FLAG_GATEWAY) + type = "RDP-Gateway"; + + if (flags & VERIFY_CERT_FLAG_REDIRECT) + type = "RDP-Redirect"; + + sprintf_s(hostname, sizeof(hostname), "%s %s:%" PRIu16, type, host, port); + dialog.serverHostname = [NSString stringWithCString:hostname encoding:NSUTF8StringEncoding]; + dialog.commonName = [NSString stringWithCString:common_name encoding:NSUTF8StringEncoding]; + dialog.subject = [NSString stringWithCString:subject encoding:NSUTF8StringEncoding]; + dialog.issuer = [NSString stringWithCString:issuer encoding:NSUTF8StringEncoding]; + dialog.fingerprint = [NSString stringWithCString:fingerprint encoding:NSUTF8StringEncoding]; + + if (flags & VERIFY_CERT_FLAG_MISMATCH) + dialog.hostMismatch = TRUE; + + if (flags & VERIFY_CERT_FLAG_CHANGED) + dialog.changed = TRUE; + + [dialog performSelectorOnMainThread:@selector(runModal:) + withObject:[view window] + waitUntilDone:TRUE]; + return dialog.result; +} + +DWORD mac_verify_changed_certificate_ex(freerdp *instance, const char *host, UINT16 port, + const char *common_name, const char *subject, + const char *issuer, const char *fingerprint, + const char *old_subject, const char *old_issuer, + const char *old_fingerprint, DWORD flags) +{ + mfContext *mfc = (mfContext *)instance->context; + MRDPView *view = (MRDPView *)mfc->view; + CertificateDialog *dialog = [CertificateDialog new]; + const char *type = "RDP-Server"; + char hostname[8192]; + + if (flags & VERIFY_CERT_FLAG_GATEWAY) + type = "RDP-Gateway"; + + if (flags & VERIFY_CERT_FLAG_REDIRECT) + type = "RDP-Redirect"; + + sprintf_s(hostname, sizeof(hostname), "%s %s:%" PRIu16, type, host, port); + dialog.serverHostname = [NSString stringWithCString:hostname encoding:NSUTF8StringEncoding]; + dialog.commonName = [NSString stringWithCString:common_name encoding:NSUTF8StringEncoding]; + dialog.subject = [NSString stringWithCString:subject encoding:NSUTF8StringEncoding]; + dialog.issuer = [NSString stringWithCString:issuer encoding:NSUTF8StringEncoding]; + dialog.fingerprint = [NSString stringWithCString:fingerprint encoding:NSUTF8StringEncoding]; + + if (flags & VERIFY_CERT_FLAG_MISMATCH) + dialog.hostMismatch = TRUE; + + if (flags & VERIFY_CERT_FLAG_CHANGED) + dialog.changed = TRUE; + + [dialog performSelectorOnMainThread:@selector(runModal:) + withObject:[view window] + waitUntilDone:TRUE]; + return dialog.result; +} + +int mac_logon_error_info(freerdp *instance, UINT32 data, UINT32 type) +{ + const char *str_data = freerdp_get_logon_error_info_data(data); + const char *str_type = freerdp_get_logon_error_info_type(type); + // TODO: Error message dialog + WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type); + return 1; +} + +BOOL mf_Pointer_New(rdpContext *context, rdpPointer *pointer) +{ + rdpGdi *gdi; + NSRect rect; + NSImage *image; + NSPoint hotSpot; + NSCursor *cursor; + BYTE *cursor_data; + NSMutableArray *ma; + NSBitmapImageRep *bmiRep; + MRDPCursor *mrdpCursor = [[MRDPCursor alloc] init]; + mfContext *mfc = (mfContext *)context; + MRDPView *view; + UINT32 format; + + if (!mfc || !context || !pointer) + return FALSE; + + view = (MRDPView *)mfc->view; + gdi = context->gdi; + + if (!gdi || !view) + return FALSE; + + rect.size.width = pointer->width; + rect.size.height = pointer->height; + rect.origin.x = pointer->xPos; + rect.origin.y = pointer->yPos; + cursor_data = (BYTE *)malloc(rect.size.width * rect.size.height * 4); + + if (!cursor_data) + return FALSE; + + mrdpCursor->cursor_data = cursor_data; + format = PIXEL_FORMAT_RGBA32; + + if (!freerdp_image_copy_from_pointer_data(cursor_data, format, 0, 0, 0, pointer->width, + pointer->height, pointer->xorMaskData, + pointer->lengthXorMask, pointer->andMaskData, + pointer->lengthAndMask, pointer->xorBpp, NULL)) + { + free(cursor_data); + mrdpCursor->cursor_data = NULL; + return FALSE; + } + + /* store cursor bitmap image in representation - required by NSImage */ + bmiRep = [[NSBitmapImageRep alloc] + initWithBitmapDataPlanes:(unsigned char **)&cursor_data + pixelsWide:rect.size.width + pixelsHigh:rect.size.height + bitsPerSample:8 + samplesPerPixel:4 + hasAlpha:YES + isPlanar:NO + colorSpaceName:NSDeviceRGBColorSpace + bitmapFormat:0 + bytesPerRow:rect.size.width * FreeRDPGetBytesPerPixel(format) + bitsPerPixel:0]; + mrdpCursor->bmiRep = bmiRep; + /* create an image using above representation */ + image = [[NSImage alloc] initWithSize:[bmiRep size]]; + [image addRepresentation:bmiRep]; + mrdpCursor->nsImage = image; + /* need hotspot to create cursor */ + hotSpot.x = pointer->xPos; + hotSpot.y = pointer->yPos; + cursor = [[NSCursor alloc] initWithImage:image hotSpot:hotSpot]; + mrdpCursor->nsCursor = cursor; + mrdpCursor->pointer = pointer; + /* save cursor for later use in mf_Pointer_Set() */ + ma = view->cursors; + [ma addObject:mrdpCursor]; + return TRUE; +} + +void mf_Pointer_Free(rdpContext *context, rdpPointer *pointer) +{ + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + NSMutableArray *ma = view->cursors; + + for (MRDPCursor *cursor in ma) + { + if (cursor->pointer == pointer) + { + cursor->nsImage = nil; + cursor->nsCursor = nil; + cursor->bmiRep = nil; + free(cursor->cursor_data); + [ma removeObject:cursor]; + return; + } + } +} + +BOOL mf_Pointer_Set(rdpContext *context, rdpPointer *pointer) +{ + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + NSMutableArray *ma = view->cursors; + + for (MRDPCursor *cursor in ma) + { + if (cursor->pointer == pointer) + { + [view setCursor:cursor->nsCursor]; + return TRUE; + } + } + + NSLog(@"Cursor not found"); + return TRUE; +} + +BOOL mf_Pointer_SetNull(rdpContext *context) +{ + return TRUE; +} + +BOOL mf_Pointer_SetDefault(rdpContext *context) +{ + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + [view setCursor:[NSCursor arrowCursor]]; + return TRUE; +} + +static BOOL mf_Pointer_SetPosition(rdpContext *context, UINT32 x, UINT32 y) +{ + mfContext *mfc = (mfContext *)context; + + if (!mfc) + return FALSE; + + /* TODO: Set pointer position */ + return TRUE; +} + +CGContextRef mac_create_bitmap_context(rdpContext *context) +{ + CGContextRef bitmap_context; + rdpGdi *gdi = context->gdi; + UINT32 bpp = FreeRDPGetBytesPerPixel(gdi->dstFormat); + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + + if (bpp == 2) + { + bitmap_context = CGBitmapContextCreate( + gdi->primary_buffer, gdi->width, gdi->height, 5, gdi->stride, colorSpace, + kCGBitmapByteOrder16Little | kCGImageAlphaNoneSkipFirst); + } + else + { + bitmap_context = CGBitmapContextCreate( + gdi->primary_buffer, gdi->width, gdi->height, 8, gdi->stride, colorSpace, + kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst); + } + + CGColorSpaceRelease(colorSpace); + return bitmap_context; +} + +BOOL mac_begin_paint(rdpContext *context) +{ + rdpGdi *gdi = context->gdi; + + if (!gdi) + return FALSE; + + gdi->primary->hdc->hwnd->invalid->null = TRUE; + return TRUE; +} + +BOOL mac_end_paint(rdpContext *context) +{ + rdpGdi *gdi; + HGDI_RGN invalid; + NSRect newDrawRect; + int ww, wh, dw, dh; + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + gdi = context->gdi; + + if (!gdi) + return FALSE; + + ww = mfc->client_width; + wh = mfc->client_height; + dw = freerdp_settings_get_uint32(mfc->common.context.settings, FreeRDP_DesktopWidth); + dh = freerdp_settings_get_uint32(mfc->common.context.settings, FreeRDP_DesktopHeight); + + if ((!context) || (!context->gdi)) + return FALSE; + + if (context->gdi->primary->hdc->hwnd->invalid->null) + return TRUE; + + invalid = gdi->primary->hdc->hwnd->invalid; + newDrawRect.origin.x = invalid->x; + newDrawRect.origin.y = invalid->y; + newDrawRect.size.width = invalid->w; + newDrawRect.size.height = invalid->h; + + if (freerdp_settings_get_bool(mfc->common.context.settings, FreeRDP_SmartSizing) && + (ww != dw || wh != dh)) + { + newDrawRect.origin.y = newDrawRect.origin.y * wh / dh - 1; + newDrawRect.size.height = newDrawRect.size.height * wh / dh + 1; + newDrawRect.origin.x = newDrawRect.origin.x * ww / dw - 1; + newDrawRect.size.width = newDrawRect.size.width * ww / dw + 1; + } + else + { + newDrawRect.origin.y = newDrawRect.origin.y - 1; + newDrawRect.size.height = newDrawRect.size.height + 1; + newDrawRect.origin.x = newDrawRect.origin.x - 1; + newDrawRect.size.width = newDrawRect.size.width + 1; + } + + windows_to_apple_cords(mfc->view, &newDrawRect); + dispatch_sync(dispatch_get_main_queue(), ^{ + [view setNeedsDisplayInRect:newDrawRect]; + }); + gdi->primary->hdc->hwnd->ninvalid = 0; + return TRUE; +} + +BOOL mac_desktop_resize(rdpContext *context) +{ + ResizeWindowEventArgs e; + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + rdpSettings *settings = context->settings; + + if (!context->gdi) + return TRUE; + + /** + * TODO: Fix resizing race condition. We should probably implement a message to be + * put on the update message queue to be able to properly flush pending updates, + * resize, and then continue with post-resizing graphical updates. + */ + CGContextRef old_context = view->bitmap_context; + view->bitmap_context = NULL; + CGContextRelease(old_context); + mfc->width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + mfc->height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!gdi_resize(context->gdi, mfc->width, mfc->height)) + return FALSE; + + view->bitmap_context = mac_create_bitmap_context(context); + + if (!view->bitmap_context) + return FALSE; + + mfc->client_width = mfc->width; + mfc->client_height = mfc->height; + [view setFrameSize:NSMakeSize(mfc->width, mfc->height)]; + EventArgsInit(&e, "mfreerdp"); + e.width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + e.height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + PubSub_OnResizeWindow(context->pubSub, context, &e); + return TRUE; +} + +void input_activity_cb(freerdp *instance) +{ + int status; + wMessage message; + wMessageQueue *queue; + status = 1; + queue = freerdp_get_message_queue(instance, FREERDP_INPUT_MESSAGE_QUEUE); + + if (queue) + { + while (MessageQueue_Peek(queue, &message, TRUE)) + { + status = freerdp_message_queue_process_message(instance, FREERDP_INPUT_MESSAGE_QUEUE, + &message); + + if (!status) + break; + } + } + else + { + WLog_ERR(TAG, "input_activity_cb: No queue!"); + } +} + +/** + * given a rect with 0,0 at the top left (windows cords) + * convert it to a rect with 0,0 at the bottom left (apple cords) + * + * Note: the formula works for conversions in both directions. + * + */ + +void windows_to_apple_cords(MRDPView *view, NSRect *r) +{ + dispatch_sync(dispatch_get_main_queue(), ^{ + r->origin.y = [view frame].size.height - (r->origin.y + r->size.height); + }); +} + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/ModuleOptions.cmake b/local-test-freerdp-full-01/afc-freerdp/client/Mac/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..10ab91c56353215faebc102185116066b453fcb5 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_CLIENT_NAME "mfreerdp") +set(FREERDP_CLIENT_PLATFORM "MacOSX") +set(FREERDP_CLIENT_VENDOR "FreeRDP") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.h new file mode 100644 index 0000000000000000000000000000000000000000..eb24c5c45525b10ec684f91c407555e4d0c09d80 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.h @@ -0,0 +1,49 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2013 Christian Hofstaedtler + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +@interface PasswordDialog : NSWindowController +{ + @public + NSTextField *usernameText; + NSTextField *passwordText; + NSTextField *messageLabel; + NSString *serverHostname; + NSString *username; + NSString *password; + NSString *domain; + BOOL modalCode; +} +@property(retain) IBOutlet NSTextField *usernameText; +@property(retain) IBOutlet NSTextField *passwordText; +@property(retain) IBOutlet NSTextField *messageLabel; + +- (IBAction)onOK:(NSObject *)sender; +- (IBAction)onCancel:(NSObject *)sender; + +@property(retain) NSString *serverHostname; +@property(retain) NSString *username; +@property(retain) NSString *password; +@property(retain) NSString *domain; +@property(readonly) BOOL modalCode; + +- (BOOL)runModal:(NSWindow *)mainWindow; + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.m new file mode 100644 index 0000000000000000000000000000000000000000..aabb102a2adcf8a138b1877c7eb48d73586a89c6 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.m @@ -0,0 +1,140 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2013 Christian Hofstaedtler + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "PasswordDialog.h" +#import + +#import + +@interface PasswordDialog () + +@property BOOL modalCode; + +@end + +@implementation PasswordDialog + +@synthesize usernameText; +@synthesize passwordText; +@synthesize messageLabel; +@synthesize serverHostname; +@synthesize username; +@synthesize password; +@synthesize domain; +@synthesize modalCode; + +- (id)init +{ + return [self initWithWindowNibName:@"PasswordDialog"]; +} + +- (void)windowDidLoad +{ + [super windowDidLoad]; + // Implement this method to handle any initialization after your window controller's window has + // been loaded from its nib file. + [self.window setTitle:self.serverHostname]; + [self.messageLabel + setStringValue:[NSString stringWithFormat:@"Authenticate to %@", self.serverHostname]]; + NSMutableString *domainUser = [[NSMutableString alloc] initWithString:@""]; + + if (self.domain != nil && + [[self.domain stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] + length] > 0) + { + [domainUser appendFormat:@"%@\\", self.domain]; + } + + if (self.username != nil) + { + [domainUser appendString:self.username]; + [self.window makeFirstResponder:self.passwordText]; + } + + [self.usernameText setStringValue:domainUser]; +} + +- (IBAction)onOK:(NSObject *)sender +{ + char *submittedUser = NULL; + char *submittedDomain = NULL; + + if (freerdp_parse_username( + [self.usernameText.stringValue cStringUsingEncoding:NSUTF8StringEncoding], + &submittedUser, &submittedDomain)) + { + if (submittedUser) + self.username = [NSString stringWithCString:submittedUser + encoding:NSUTF8StringEncoding]; + if (submittedDomain) + self.domain = [NSString stringWithCString:submittedDomain + encoding:NSUTF8StringEncoding]; + } + else + { + self.username = self.usernameText.stringValue; + } + + self.password = self.passwordText.stringValue; + free(submittedUser); + free(submittedDomain); + [NSApp stopModalWithCode:TRUE]; +} + +- (IBAction)onCancel:(NSObject *)sender +{ + [NSApp stopModalWithCode:FALSE]; +} + +- (BOOL)runModal:(NSWindow *)mainWindow +{ + if ([mainWindow respondsToSelector:@selector(beginSheet:completionHandler:)]) + { + [mainWindow beginSheet:self.window completionHandler:nil]; + self.modalCode = [NSApp runModalForWindow:self.window]; + [mainWindow endSheet:self.window]; + } + else + { + [NSApp beginSheet:self.window + modalForWindow:mainWindow + modalDelegate:nil + didEndSelector:nil + contextInfo:nil]; + self.modalCode = [NSApp runModalForWindow:self.window]; + [NSApp endSheet:self.window]; + } + + [self.window orderOut:nil]; + return self.modalCode; +} + +- (void)dealloc +{ + [usernameText release]; + [passwordText release]; + [messageLabel release]; + [serverHostname release]; + [username release]; + [password release]; + [domain release]; + [super dealloc]; +} + +@end diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.xib b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.xib new file mode 100644 index 0000000000000000000000000000000000000000..3911c14bdfa4bbf80a626f6cec46c220343a31f2 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/PasswordDialog.xib @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/main.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/main.m new file mode 100644 index 0000000000000000000000000000000000000000..6b1035f879d15f5f1e8a1a00ba2babd23c051573 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/main.m @@ -0,0 +1,25 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * MacFreeRDP + * + * Copyright 2012 Thomas Goddard + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +int main(int argc, char *argv[]) +{ + return NSApplicationMain(argc, argv); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.h new file mode 100644 index 0000000000000000000000000000000000000000..5f21c6cffbd59ac151547cb9509c4718bbdbb404 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.h @@ -0,0 +1,46 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Client + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_MAC_CLIENT_H +#define FREERDP_CLIENT_MAC_CLIENT_H + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + FREERDP_API void mf_press_mouse_button(void* context, int button, int x, int y, BOOL down); + FREERDP_API void mf_scale_mouse_event(void* context, UINT16 flags, UINT16 x, UINT16 y); + FREERDP_API void mf_scale_mouse_event_ex(void* context, UINT16 flags, UINT16 x, UINT16 y); + + /** + * Client Interface + */ + + FREERDP_API int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_CLIENT_MAC_CLIENT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.m b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.m new file mode 100644 index 0000000000000000000000000000000000000000..1dcc1577ccacd21c7f2aadf1210a23c5a556ae56 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mf_client.m @@ -0,0 +1,220 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Interface + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "mfreerdp.h" + +#include + +#include +#include +#include + +#include "MRDPView.h" + +/** + * Client Interface + */ + +static BOOL mfreerdp_client_global_init(void) +{ + freerdp_handle_signals(); + return TRUE; +} + +static void mfreerdp_client_global_uninit(void) +{ +} + +static int mfreerdp_client_start(rdpContext *context) +{ + MRDPView *view; + mfContext *mfc = (mfContext *)context; + + if (mfc->view == NULL) + { + // view not specified beforehand. Create view dynamically + mfc->view = [[MRDPView alloc] + initWithFrame:NSMakeRect( + 0, 0, + freerdp_settings_get_uint32(context->settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(context->settings, + FreeRDP_DesktopHeight))]; + mfc->view_ownership = TRUE; + } + + view = (MRDPView *)mfc->view; + return [view rdpStart:context]; +} + +static int mfreerdp_client_stop(rdpContext *context) +{ + mfContext *mfc = (mfContext *)context; + + freerdp_client_common_stop(context); + + if (mfc->view_ownership) + { + MRDPView *view = (MRDPView *)mfc->view; + [view releaseResources]; + [view release]; + mfc->view = nil; + } + + return 0; +} + +static BOOL mfreerdp_client_new(freerdp *instance, rdpContext *context) +{ + mfContext *mfc; + + WINPR_ASSERT(instance); + + mfc = (mfContext *)instance->context; + WINPR_ASSERT(mfc); + + mfc->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); + if (!mfc->stopEvent) + return FALSE; + context->instance->PreConnect = mac_pre_connect; + context->instance->PostConnect = mac_post_connect; + context->instance->PostDisconnect = mac_post_disconnect; + context->instance->AuthenticateEx = mac_authenticate_ex; + context->instance->VerifyCertificateEx = mac_verify_certificate_ex; + context->instance->VerifyChangedCertificateEx = mac_verify_changed_certificate_ex; + context->instance->LogonErrorInfo = mac_logon_error_info; + return TRUE; +} + +static void mfreerdp_client_free(freerdp *instance, rdpContext *context) +{ + mfContext *mfc; + + if (!instance || !context) + return; + + mfc = (mfContext *)instance->context; + (void)CloseHandle(mfc->stopEvent); +} + +static void mf_scale_mouse_coordinates(mfContext *mfc, UINT16 *px, UINT16 *py) +{ + UINT16 x = *px; + UINT16 y = *py; + UINT32 ww = mfc->client_width; + UINT32 wh = mfc->client_height; + UINT32 dw = freerdp_settings_get_uint32(mfc->common.context.settings, FreeRDP_DesktopWidth); + UINT32 dh = freerdp_settings_get_uint32(mfc->common.context.settings, FreeRDP_DesktopHeight); + + if (!freerdp_settings_get_bool(mfc->common.context.settings, FreeRDP_SmartSizing) || + ((ww == dw) && (wh == dh))) + { + y = y + mfc->yCurrentScroll; + x = x + mfc->xCurrentScroll; + + y -= (dh - wh); + x -= (dw - ww); + } + else + { + y = y * dh / wh + mfc->yCurrentScroll; + x = x * dw / ww + mfc->xCurrentScroll; + } + + *px = x; + *py = y; +} + +void mf_scale_mouse_event(void *context, UINT16 flags, UINT16 x, UINT16 y) +{ + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + // Convert to windows coordinates + y = [view frame].size.height - y; + + if ((flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL)) == 0) + mf_scale_mouse_coordinates(mfc, &x, &y); + freerdp_client_send_button_event(&mfc->common, FALSE, flags, x, y); +} + +void mf_scale_mouse_event_ex(void *context, UINT16 flags, UINT16 x, UINT16 y) +{ + mfContext *mfc = (mfContext *)context; + MRDPView *view = (MRDPView *)mfc->view; + // Convert to windows coordinates + y = [view frame].size.height - y; + + mf_scale_mouse_coordinates(mfc, &x, &y); + freerdp_client_send_extended_button_event(&mfc->common, FALSE, flags, x, y); +} + +void mf_press_mouse_button(void *context, int button, int x, int y, BOOL down) +{ + UINT16 flags = 0; + UINT16 xflags = 0; + + if (down) + { + flags |= PTR_FLAGS_DOWN; + xflags |= PTR_XFLAGS_DOWN; + } + + switch (button) + { + case 0: + mf_scale_mouse_event(context, flags | PTR_FLAGS_BUTTON1, x, y); + break; + + case 1: + mf_scale_mouse_event(context, flags | PTR_FLAGS_BUTTON2, x, y); + break; + + case 2: + mf_scale_mouse_event(context, flags | PTR_FLAGS_BUTTON3, x, y); + break; + + case 3: + mf_scale_mouse_event_ex(context, xflags | PTR_XFLAGS_BUTTON1, x, y); + break; + + case 4: + mf_scale_mouse_event_ex(context, xflags | PTR_XFLAGS_BUTTON2, x, y); + break; + + default: + break; + } +} + +int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS *pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + + pEntryPoints->Version = 1; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->GlobalInit = mfreerdp_client_global_init; + pEntryPoints->GlobalUninit = mfreerdp_client_global_uninit; + pEntryPoints->ContextSize = sizeof(mfContext); + pEntryPoints->ClientNew = mfreerdp_client_new; + pEntryPoints->ClientFree = mfreerdp_client_free; + pEntryPoints->ClientStart = mfreerdp_client_start; + pEntryPoints->ClientStop = mfreerdp_client_stop; + return 0; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Mac/mfreerdp.h b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..bc9315027e81362ccb3be55b5df8daf3d62545e0 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Mac/mfreerdp.h @@ -0,0 +1,86 @@ +#ifndef FREERDP_CLIENT_MAC_FREERDP_H +#define FREERDP_CLIENT_MAC_FREERDP_H + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "Keyboard.h" +#include + +typedef struct +{ + rdpClientContext common; + + void* view; + BOOL view_ownership; + + int width; + int height; + int offset_x; + int offset_y; + int fs_toggle; + int fullscreen; + int percentscreen; + char window_title[64]; + int client_x; + int client_y; + int client_width; + int client_height; + + HANDLE stopEvent; + HANDLE keyboardThread; + enum APPLE_KEYBOARD_TYPE appleKeyboardType; + + DWORD mainThreadId; + DWORD keyboardThreadId; + + BOOL clipboardSync; + wClipboard* clipboard; + UINT32 numServerFormats; + UINT32 requestedFormatId; + HANDLE clipboardRequestEvent; + CLIPRDR_FORMAT* serverFormats; + CliprdrClientContext* cliprdr; + UINT32 clipboardCapabilities; + + rdpFile* connectionRdpFile; + + // Keep track of window size and position, disable when in fullscreen mode. + BOOL disablewindowtracking; + + // These variables are required for horizontal scrolling. + BOOL updating_scrollbars; + BOOL xScrollVisible; + int xMinScroll; // minimum horizontal scroll value + int xCurrentScroll; // current horizontal scroll value + int xMaxScroll; // maximum horizontal scroll value + + // These variables are required for vertical scrolling. + BOOL yScrollVisible; + int yMinScroll; // minimum vertical scroll value + int yCurrentScroll; // current vertical scroll value + int yMaxScroll; // maximum vertical scroll value + + CGEventFlags kbdFlags; +} mfContext; + +#endif /* FREERDP_CLIENT_MAC_FREERDP_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/SDL/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/SDL/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd67ec593328e8003d480b1389b3e0f0da5f2607 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/SDL/CMakeLists.txt @@ -0,0 +1,104 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP SDL Client +# +# Copyright 2024 Armin Novak +# Copyright 2024 Thincast Technologies GmbH +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(sdl-freerdp LANGUAGES CXX VERSION ${FREERDP_DEFAULT_PROJECT_VERSION}) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS ON) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/) +include(CommonConfigOptions) + +include(ConfigureFreeRDP) +include(CXXCompilerFlags) + +option(WITH_DEBUG_SDL_EVENTS "[dangerous, not for release builds!] Debug SDL events" ${DEFAULT_DEBUG_OPTION}) +option(WITH_DEBUG_SDL_KBD_EVENTS "[dangerous, not for release builds!] Debug SDL keyboard events" + ${DEFAULT_DEBUG_OPTION} +) +option(WITH_WIN_CONSOLE "Build ${PROJECT_NAME} with console support" ON) +option(WITH_SDL_LINK_SHARED "link SDL dynamic or static" ON) + +if(WITH_WIN_CONSOLE) + set(WIN32_GUI_FLAG "TRUE") +else() + set(WIN32_GUI_FLAG "WIN32") +endif() + +if(WITH_DEBUG_SDL_EVENTS) + add_compile_definitions(WITH_DEBUG_SDL_EVENTS) +endif() +if(WITH_DEBUG_SDL_KBD_EVENTS) + add_compile_definitions(WITH_DEBUG_SDL_KBD_EVENTS) +endif() + +include(CMakeDependentOption) + +# Require 2.0.20 for ubuntu 22.04. +# older versions do not have the SDL2::SDL2 et al targets +find_package(SDL2 2.0.20) +find_package(SDL3) + +cmake_dependent_option(WITH_CLIENT_SDL_VERSIONED "append sdl version to client binaries" OFF WITH_CLIENT_SDL OFF) +cmake_dependent_option( + WITH_CLIENT_SDL2 "[experimental] build experimental SDL2 client" ${SDL2_FOUND} WITH_CLIENT_SDL OFF +) +cmake_dependent_option( + WITH_CLIENT_SDL3 "[experimental] build experimental SDL3 client" ${SDL3_FOUND} WITH_CLIENT_SDL OFF +) + +if(WITH_CLIENT_SDL2 AND WITH_CLIENT_SDL3) + message("Building both, SDL2 and SDL3 clients, forcing WITH_CLIENT_SDL_VERSIONED=ON") + set(WITH_CLIENT_SDL_VERSIONED ON) +endif() + +if(NOT SDL2_FOUND AND NOT SDL3_FOUND) + message(WARNING "No SDL library detected, giving up. Install SDL2 or SDL3 development package to fix") +endif() + +if((WITH_CLIENT_SDL2 AND SDL2_FOUND) OR (WITH_CLIENT_SDL3 AND SDL3_FOUND)) + add_subdirectory(common) + include_directories(common) +endif() + +if(WITH_CLIENT_SDL2) + if(SDL2_FOUND) + add_subdirectory(SDL2) + else() + message(WARNING "SDL2 requested but not found, continuing build without SDL2 client") + endif() +endif() + +if(WITH_CLIENT_SDL3) + if(SDL3_FOUND) + add_subdirectory(SDL3) + else() + message(WARNING "SDL3 requested but not found, continuing build without SDL3 client") + endif() +endif() diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/Sample/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4783ca6b92183e29276b62676afa563a7a63c937 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/CMakeLists.txt @@ -0,0 +1,48 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Sample UI cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +cmake_minimum_required(VERSION 3.13) + +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(sfreerdp LANGUAGES C VERSION ${FREERDP_DEFAULT_PROJECT_VERSION}) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS ON) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/) +include(CommonConfigOptions) + +include(ConfigureFreeRDP) + +set(SRCS tf_channels.c tf_channels.h tf_freerdp.h tf_freerdp.c) + +addtargetwithresourcefile(${PROJECT_NAME} TRUE "${PROJECT_VERSION}" SRCS) + +set(LIBS freerdp-client freerdp winpr) +target_link_libraries(${PROJECT_NAME} PRIVATE ${LIBS}) + +set_property(TARGET ${PROJECT_NAME} PROPERTY FOLDER "Client/Sample") +install(TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT client) +install_freerdp_desktop("${PROJECT_NAME}") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/ModuleOptions.cmake b/local-test-freerdp-full-01/afc-freerdp/client/Sample/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..1594cfed9eb953ac7a9033fc727645aaf7c3b78e --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_CLIENT_NAME "sfreerdp") +set(FREERDP_CLIENT_PLATFORM "Sample") +set(FREERDP_CLIENT_VENDOR "FreeRDP") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.c b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..efd451d5e854f7ff8b4ce17446635b968a02267a --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.c @@ -0,0 +1,73 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Sample Client Channels + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include "tf_channels.h" +#include "tf_freerdp.h" + +void tf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e) +{ + tfContext* tf = (tfContext*)context; + + WINPR_ASSERT(tf); + WINPR_ASSERT(e); + + if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + CliprdrClientContext* clip = (CliprdrClientContext*)e->pInterface; + WINPR_ASSERT(clip); + clip->custom = context; + } + else + freerdp_client_OnChannelConnectedEventHandler(&tf->common, e); +} + +void tf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e) +{ + tfContext* tf = (tfContext*)context; + + WINPR_ASSERT(tf); + WINPR_ASSERT(e); + + if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + CliprdrClientContext* clip = (CliprdrClientContext*)e->pInterface; + WINPR_ASSERT(clip); + clip->custom = NULL; + } + else + freerdp_client_OnChannelDisconnectedEventHandler(&tf->common, e); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.h b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.h new file mode 100644 index 0000000000000000000000000000000000000000..d00a5c2f0223d22064053fc36bfec48e44bcb0a4 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_channels.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Sample Client Channels + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_SAMPLE_CHANNELS_H +#define FREERDP_CLIENT_SAMPLE_CHANNELS_H + +#include +#include + +int tf_on_channel_connected(freerdp* instance, const char* name, void* pInterface); +int tf_on_channel_disconnected(freerdp* instance, const char* name, void* pInterface); + +void tf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e); +void tf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e); + +#endif /* FREERDP_CLIENT_SAMPLE_CHANNELS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.c b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..7915635def08da6de8cb313443aa8e0a10631303 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.c @@ -0,0 +1,417 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Test UI + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2016,2018 Armin Novak + * Copyright 2016,2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "tf_channels.h" +#include "tf_freerdp.h" + +#define TAG CLIENT_TAG("sample") + +/* This function is called whenever a new frame starts. + * It can be used to reset invalidated areas. */ +static BOOL tf_begin_paint(rdpContext* context) +{ + rdpGdi* gdi = NULL; + + WINPR_ASSERT(context); + + gdi = context->gdi; + WINPR_ASSERT(gdi); + WINPR_ASSERT(gdi->primary); + WINPR_ASSERT(gdi->primary->hdc); + WINPR_ASSERT(gdi->primary->hdc->hwnd); + WINPR_ASSERT(gdi->primary->hdc->hwnd->invalid); + gdi->primary->hdc->hwnd->invalid->null = TRUE; + return TRUE; +} + +/* This function is called when the library completed composing a new + * frame. Read out the changed areas and blit them to your output device. + * The image buffer will have the format specified by gdi_init + */ +static BOOL tf_end_paint(rdpContext* context) +{ + rdpGdi* gdi = NULL; + + WINPR_ASSERT(context); + + gdi = context->gdi; + WINPR_ASSERT(gdi); + WINPR_ASSERT(gdi->primary); + WINPR_ASSERT(gdi->primary->hdc); + WINPR_ASSERT(gdi->primary->hdc->hwnd); + WINPR_ASSERT(gdi->primary->hdc->hwnd->invalid); + + if (gdi->primary->hdc->hwnd->invalid->null) + return TRUE; + + return TRUE; +} + +static BOOL tf_desktop_resize(rdpContext* context) +{ + rdpGdi* gdi = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(context); + + settings = context->settings; + WINPR_ASSERT(settings); + + gdi = context->gdi; + return gdi_resize(gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); +} + +/* This function is called to output a System BEEP */ +static BOOL tf_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) +{ + /* TODO: Implement */ + WINPR_UNUSED(context); + WINPR_UNUSED(play_sound); + return TRUE; +} + +/* This function is called to update the keyboard indocator LED */ +static BOOL tf_keyboard_set_indicators(rdpContext* context, UINT16 led_flags) +{ + /* TODO: Set local keyboard indicator LED status */ + WINPR_UNUSED(context); + WINPR_UNUSED(led_flags); + return TRUE; +} + +/* This function is called to set the IME state */ +static BOOL tf_keyboard_set_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, + UINT32 imeConvMode) +{ + if (!context) + return FALSE; + + WLog_WARN(TAG, + "KeyboardSetImeStatus(unitId=%04" PRIx16 ", imeState=%08" PRIx32 + ", imeConvMode=%08" PRIx32 ") ignored", + imeId, imeState, imeConvMode); + return TRUE; +} + +/* Called before a connection is established. + * Set all configuration options to support and load channels here. */ +static BOOL tf_pre_connect(freerdp* instance) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + settings = instance->context->settings; + WINPR_ASSERT(settings); + + /* If the callbacks provide the PEM all certificate options can be extracted, otherwise + * only the certificate fingerprint is available. */ + if (!freerdp_settings_set_bool(settings, FreeRDP_CertificateCallbackPreferPEM, TRUE)) + return FALSE; + + /* Optional OS identifier sent to server */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_UNIX)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_NATIVE_XSERVER)) + return FALSE; + /* OrderSupport is initialized at this point. + * Only override it if you plan to implement custom order + * callbacks or deactivate certain features. */ + /* Register the channel listeners. + * They are required to set up / tear down channels if they are loaded. */ + PubSub_SubscribeChannelConnected(instance->context->pubSub, tf_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(instance->context->pubSub, + tf_OnChannelDisconnectedEventHandler); + + /* TODO: Any code your client requires */ + return TRUE; +} + +/* Called after a RDP connection was successfully established. + * Settings might have changed during negotiation of client / server feature + * support. + * + * Set up local framebuffers and paing callbacks. + * If required, register pointer callbacks to change the local mouse cursor + * when hovering over the RDP window + */ +static BOOL tf_post_connect(freerdp* instance) +{ + rdpContext* context = NULL; + + if (!gdi_init(instance, PIXEL_FORMAT_XRGB32)) + return FALSE; + + context = instance->context; + WINPR_ASSERT(context); + WINPR_ASSERT(context->update); + + /* With this setting we disable all graphics processing in the library. + * + * This allows low resource (client) protocol parsing. + */ + if (!freerdp_settings_set_bool(context->settings, FreeRDP_DeactivateClientDecoding, TRUE)) + return FALSE; + + context->update->BeginPaint = tf_begin_paint; + context->update->EndPaint = tf_end_paint; + context->update->PlaySound = tf_play_sound; + context->update->DesktopResize = tf_desktop_resize; + context->update->SetKeyboardIndicators = tf_keyboard_set_indicators; + context->update->SetKeyboardImeStatus = tf_keyboard_set_ime_status; + return TRUE; +} + +/* This function is called whether a session ends by failure or success. + * Clean up everything allocated by pre_connect and post_connect. + */ +static void tf_post_disconnect(freerdp* instance) +{ + tfContext* context = NULL; + + if (!instance) + return; + + if (!instance->context) + return; + + context = (tfContext*)instance->context; + PubSub_UnsubscribeChannelConnected(instance->context->pubSub, + tf_OnChannelConnectedEventHandler); + PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub, + tf_OnChannelDisconnectedEventHandler); + gdi_free(instance); + /* TODO : Clean up custom stuff */ + WINPR_UNUSED(context); +} + +/* RDP main loop. + * Connects RDP, loops while running and handles event and dispatch, cleans up + * after the connection ends. */ +static DWORD WINAPI tf_client_thread_proc(LPVOID arg) +{ + freerdp* instance = (freerdp*)arg; + DWORD nCount = 0; + DWORD status = 0; + DWORD result = 0; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + BOOL rc = freerdp_connect(instance); + + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + if (freerdp_settings_get_bool(instance->context->settings, FreeRDP_AuthenticationOnly)) + { + result = freerdp_get_last_error(instance->context); + freerdp_abort_connect_context(instance->context); + WLog_ERR(TAG, "Authentication only, exit status 0x%08" PRIx32 "", result); + goto disconnect; + } + + if (!rc) + { + result = freerdp_get_last_error(instance->context); + WLog_ERR(TAG, "connection failure 0x%08" PRIx32, result); + return result; + } + + while (!freerdp_shall_disconnect_context(instance->context)) + { + nCount = freerdp_get_event_handles(instance->context, handles, ARRAYSIZE(handles)); + + if (nCount == 0) + { + WLog_ERR(TAG, "freerdp_get_event_handles failed"); + break; + } + + status = WaitForMultipleObjects(nCount, handles, FALSE, 100); + + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed with %" PRIu32 "", status); + break; + } + + if (!freerdp_check_event_handles(instance->context)) + { + if (freerdp_get_last_error(instance->context) == FREERDP_ERROR_SUCCESS) + WLog_ERR(TAG, "Failed to check FreeRDP event handles"); + + break; + } + } + +disconnect: + freerdp_disconnect(instance); + return result; +} + +/* Optional global initializer. + * Here we just register a signal handler to print out stack traces + * if available. */ +static BOOL tf_client_global_init(void) +{ + if (freerdp_handle_signals() != 0) + return FALSE; + + return TRUE; +} + +/* Optional global tear down */ +static void tf_client_global_uninit(void) +{ +} + +static int tf_logon_error_info(freerdp* instance, UINT32 data, UINT32 type) +{ + tfContext* tf = NULL; + const char* str_data = freerdp_get_logon_error_info_data(data); + const char* str_type = freerdp_get_logon_error_info_type(type); + + if (!instance || !instance->context) + return -1; + + tf = (tfContext*)instance->context; + WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type); + WINPR_UNUSED(tf); + + return 1; +} + +static BOOL tf_client_new(freerdp* instance, rdpContext* context) +{ + tfContext* tf = (tfContext*)context; + + if (!instance || !context) + return FALSE; + + instance->PreConnect = tf_pre_connect; + instance->PostConnect = tf_post_connect; + instance->PostDisconnect = tf_post_disconnect; + instance->LogonErrorInfo = tf_logon_error_info; + /* TODO: Client display set up */ + WINPR_UNUSED(tf); + return TRUE; +} + +static void tf_client_free(freerdp* instance, rdpContext* context) +{ + tfContext* tf = (tfContext*)instance->context; + + if (!context) + return; + + /* TODO: Client display tear down */ + WINPR_UNUSED(tf); +} + +static int tf_client_start(rdpContext* context) +{ + /* TODO: Start client related stuff */ + WINPR_UNUSED(context); + return 0; +} + +static int tf_client_stop(rdpContext* context) +{ + /* TODO: Stop client related stuff */ + WINPR_UNUSED(context); + return 0; +} + +static int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + + ZeroMemory(pEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS)); + pEntryPoints->Version = RDP_CLIENT_INTERFACE_VERSION; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->GlobalInit = tf_client_global_init; + pEntryPoints->GlobalUninit = tf_client_global_uninit; + pEntryPoints->ContextSize = sizeof(tfContext); + pEntryPoints->ClientNew = tf_client_new; + pEntryPoints->ClientFree = tf_client_free; + pEntryPoints->ClientStart = tf_client_start; + pEntryPoints->ClientStop = tf_client_stop; + return 0; +} + +int main(int argc, char* argv[]) +{ + int rc = -1; + RDP_CLIENT_ENTRY_POINTS clientEntryPoints = { 0 }; + + RdpClientEntry(&clientEntryPoints); + rdpContext* context = freerdp_client_context_new(&clientEntryPoints); + + if (!context) + goto fail; + + const int status = + freerdp_client_settings_parse_command_line(context->settings, argc, argv, FALSE); + if (status) + { + rc = freerdp_client_settings_command_line_status_print(context->settings, status, argc, + argv); + goto fail; + } + + if (!stream_dump_register_handlers(context, CONNECTION_STATE_MCS_CREATE_REQUEST, FALSE)) + goto fail; + + if (freerdp_client_start(context) != 0) + goto fail; + + const DWORD res = tf_client_thread_proc(context->instance); + rc = (int)res; + + if (freerdp_client_stop(context) != 0) + rc = -1; + +fail: + freerdp_client_context_free(context); + return rc; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.h b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..c9b52951b847f01a86b04d30276ec701e88ccff8 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Sample/tf_freerdp.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Sample Client + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_SAMPLE_H +#define FREERDP_CLIENT_SAMPLE_H + +#include +#include +#include +#include +#include + +typedef struct +{ + rdpClientContext common; + + /* Channels */ +} tfContext; + +#endif /* FREERDP_CLIENT_SAMPLE_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a237a59969d560ce5893bef7e575fa2b91a4dd9 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/CMakeLists.txt @@ -0,0 +1,56 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Wayland Client cmake build script +# +# Copyright 2014 Manuel Bachmann +# Copyright 2015 David Fort +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set(MODULE_NAME "wlfreerdp") +set(MODULE_PREFIX "FREERDP_CLIENT_WAYLAND") + +include_directories(SYSTEM ${WAYLAND_INCLUDE_DIR}) + +set(${MODULE_PREFIX}_SRCS + wlfreerdp.c + wlfreerdp.h + wlf_disp.c + wlf_disp.h + wlf_pointer.c + wlf_pointer.h + wlf_input.c + wlf_input.h + wlf_cliprdr.c + wlf_cliprdr.h + wlf_channels.c + wlf_channels.h +) + +if(FREERDP_UNIFIED_BUILD) + include_directories(${PROJECT_SOURCE_DIR}/uwac/include) + include_directories(${PROJECT_BINARY_DIR}/uwac/include) +else() + find_package(uwac 0 REQUIRED) + include_directories(SYSTEM ${UWAC_INCLUDE_DIR}) +endif() + +list(APPEND ${MODULE_PREFIX}_LIBS freerdp-client freerdp uwac) + +addtargetwithresourcefile(${MODULE_NAME} TRUE ${FREERDP_VERSION} ${MODULE_PREFIX}_SRCS) + +target_link_libraries(${MODULE_NAME} ${${MODULE_PREFIX}_LIBS}) + +install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT client) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Client/Wayland") +generate_and_install_freerdp_man_from_template(${MODULE_NAME} "1" "${FREERDP_API_VERSION}") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..3a11407e92ec3899447f218116a031dbda4bd4aa --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.c @@ -0,0 +1,79 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Channels + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include + +#include "wlf_channels.h" +#include "wlf_cliprdr.h" +#include "wlf_disp.h" +#include "wlfreerdp.h" + +void wlf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e) +{ + wlfContext* wlf = (wlfContext*)context; + + WINPR_ASSERT(wlf); + WINPR_ASSERT(e); + + if (FALSE) + { + } + else if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + wlf_cliprdr_init(wlf->clipboard, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + wlf_disp_init(wlf->disp, (DispClientContext*)e->pInterface); + } + else + freerdp_client_OnChannelConnectedEventHandler(context, e); +} + +void wlf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e) +{ + wlfContext* wlf = (wlfContext*)context; + + WINPR_ASSERT(wlf); + WINPR_ASSERT(e); + + if (FALSE) + { + } + else if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + wlf_cliprdr_uninit(wlf->clipboard, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + wlf_disp_uninit(wlf->disp, (DispClientContext*)e->pInterface); + } + else + freerdp_client_OnChannelDisconnectedEventHandler(context, e); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.h new file mode 100644 index 0000000000000000000000000000000000000000..e8760316b150a6fe944fdb4a0bf42f76bb4b5c9e --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_channels.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Channels + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WAYLAND_CHANNELS_H +#define FREERDP_CLIENT_WAYLAND_CHANNELS_H + +#include +#include +#include +#include +#include +#include +#include + +int wlf_on_channel_connected(freerdp* instance, const char* name, void* pInterface); +int wlf_on_channel_disconnected(freerdp* instance, const char* name, void* pInterface); + +void wlf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e); +void wlf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e); + +#endif /* FREERDP_CLIENT_WAYLAND_CHANNELS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.c new file mode 100644 index 0000000000000000000000000000000000000000..1be612b13a4f683c6f51dab150fcd590549b550f --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.c @@ -0,0 +1,1018 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Clipboard Redirection + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "wlf_cliprdr.h" + +#define TAG CLIENT_TAG("wayland.cliprdr") + +#define mime_text_plain "text/plain" +// NOLINTNEXTLINE(bugprone-suspicious-missing-comma) +static const char mime_text_utf8[] = mime_text_plain ";charset=utf-8"; + +// NOLINTNEXTLINE(bugprone-suspicious-missing-comma) +static const char* mime_text[] = { mime_text_plain, mime_text_utf8, "UTF8_STRING", + "COMPOUND_TEXT", "TEXT", "STRING" }; + +static const char mime_png[] = "image/png"; +static const char mime_webp[] = "image/webp"; +static const char mime_jpg[] = "image/jpeg"; +static const char mime_tiff[] = "image/tiff"; +static const char mime_uri_list[] = "text/uri-list"; +static const char mime_html[] = "text/html"; + +#define BMP_MIME_LIST "image/bmp", "image/x-bmp", "image/x-MS-bmp", "image/x-win-bitmap" +static const char* mime_bitmap[] = { BMP_MIME_LIST }; +static const char* mime_image[] = { mime_png, mime_webp, mime_jpg, mime_tiff, BMP_MIME_LIST }; + +static const char mime_gnome_copied_files[] = "x-special/gnome-copied-files"; +static const char mime_mate_copied_files[] = "x-special/mate-copied-files"; + +static const char type_FileGroupDescriptorW[] = "FileGroupDescriptorW"; +static const char type_HtmlFormat[] = "HTML Format"; + +typedef struct +{ + FILE* responseFile; + UINT32 responseFormat; + char* responseMime; +} wlf_request; + +typedef struct +{ + const FILE* responseFile; + UINT32 responseFormat; + const char* responseMime; +} wlf_const_request; + +struct wlf_clipboard +{ + wlfContext* wfc; + rdpChannels* channels; + CliprdrClientContext* context; + wLog* log; + + UwacSeat* seat; + wClipboard* system; + + size_t numClientFormats; + CLIPRDR_FORMAT* clientFormats; + + size_t numServerFormats; + CLIPRDR_FORMAT* serverFormats; + + BOOL sync; + + CRITICAL_SECTION lock; + CliprdrFileContext* file; + + wQueue* request_queue; +}; + +static void wlf_request_free(void* rq) +{ + wlf_request* request = rq; + if (request) + { + free(request->responseMime); + if (request->responseFile) + (void)fclose(request->responseFile); + } + free(request); +} + +static wlf_request* wlf_request_new(void) +{ + return calloc(1, sizeof(wlf_request)); +} + +static void* wlf_request_clone(const void* oth) +{ + const wlf_request* other = (const wlf_request*)oth; + wlf_request* copy = wlf_request_new(); + if (!copy) + return NULL; + *copy = *other; + if (other->responseMime) + { + copy->responseMime = _strdup(other->responseMime); + if (!copy->responseMime) + goto fail; + } + return copy; +fail: + wlf_request_free(copy); + return NULL; +} + +static BOOL wlf_mime_is_file(const char* mime) +{ + if (strncmp(mime_uri_list, mime, sizeof(mime_uri_list)) == 0) + return TRUE; + if (strncmp(mime_gnome_copied_files, mime, sizeof(mime_gnome_copied_files)) == 0) + return TRUE; + if (strncmp(mime_mate_copied_files, mime, sizeof(mime_mate_copied_files)) == 0) + return TRUE; + return FALSE; +} + +static BOOL wlf_mime_is_text(const char* mime) +{ + for (size_t x = 0; x < ARRAYSIZE(mime_text); x++) + { + if (strcmp(mime, mime_text[x]) == 0) + return TRUE; + } + + return FALSE; +} + +static BOOL wlf_mime_is_image(const char* mime) +{ + for (size_t x = 0; x < ARRAYSIZE(mime_image); x++) + { + if (strcmp(mime, mime_image[x]) == 0) + return TRUE; + } + + return FALSE; +} + +static BOOL wlf_mime_is_html(const char* mime) +{ + if (strcmp(mime, mime_html) == 0) + return TRUE; + + return FALSE; +} + +static void wlf_cliprdr_free_server_formats(wfClipboard* clipboard) +{ + if (clipboard && clipboard->serverFormats) + { + for (size_t j = 0; j < clipboard->numServerFormats; j++) + { + CLIPRDR_FORMAT* format = &clipboard->serverFormats[j]; + free(format->formatName); + } + + free(clipboard->serverFormats); + clipboard->serverFormats = NULL; + clipboard->numServerFormats = 0; + } + + if (clipboard) + UwacClipboardOfferDestroy(clipboard->seat); +} + +static void wlf_cliprdr_free_client_formats(wfClipboard* clipboard) +{ + if (clipboard && clipboard->numClientFormats) + { + for (size_t j = 0; j < clipboard->numClientFormats; j++) + { + CLIPRDR_FORMAT* format = &clipboard->clientFormats[j]; + free(format->formatName); + } + + free(clipboard->clientFormats); + clipboard->clientFormats = NULL; + clipboard->numClientFormats = 0; + } + + if (clipboard) + UwacClipboardOfferDestroy(clipboard->seat); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_send_client_format_list(wfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + const CLIPRDR_FORMAT_LIST formatList = { .common.msgFlags = 0, + .numFormats = (UINT32)clipboard->numClientFormats, + .formats = clipboard->clientFormats, + .common.msgType = CB_FORMAT_LIST }; + + cliprdr_file_context_clear(clipboard->file); + + WLog_VRB(TAG, "-------------- client format list [%" PRIu32 "] ------------------", + formatList.numFormats); + for (UINT32 x = 0; x < formatList.numFormats; x++) + { + const CLIPRDR_FORMAT* format = &formatList.formats[x]; + WLog_VRB(TAG, "client announces %" PRIu32 " [%s][%s]", format->formatId, + ClipboardGetFormatIdString(format->formatId), format->formatName); + } + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatList); + return clipboard->context->ClientFormatList(clipboard->context, &formatList); +} + +static void wfl_cliprdr_add_client_format_id(wfClipboard* clipboard, UINT32 formatId) +{ + CLIPRDR_FORMAT* format = NULL; + const char* name = ClipboardGetFormatName(clipboard->system, formatId); + + for (size_t x = 0; x < clipboard->numClientFormats; x++) + { + format = &clipboard->clientFormats[x]; + + if (format->formatId == formatId) + return; + } + + format = realloc(clipboard->clientFormats, + (clipboard->numClientFormats + 1) * sizeof(CLIPRDR_FORMAT)); + + if (!format) + return; + + clipboard->clientFormats = format; + format = &clipboard->clientFormats[clipboard->numClientFormats++]; + format->formatId = formatId; + format->formatName = NULL; + + if (name && (formatId >= CF_MAX)) + format->formatName = _strdup(name); +} + +static BOOL wlf_cliprdr_add_client_format(wfClipboard* clipboard, const char* mime) +{ + WINPR_ASSERT(mime); + ClipboardLock(clipboard->system); + if (wlf_mime_is_html(mime)) + { + UINT32 formatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat); + wfl_cliprdr_add_client_format_id(clipboard, formatId); + } + else if (wlf_mime_is_text(mime)) + { + wfl_cliprdr_add_client_format_id(clipboard, CF_TEXT); + wfl_cliprdr_add_client_format_id(clipboard, CF_OEMTEXT); + wfl_cliprdr_add_client_format_id(clipboard, CF_UNICODETEXT); + } + else if (wlf_mime_is_image(mime)) + { + for (size_t x = 0; x < ARRAYSIZE(mime_image); x++) + { + const char* mime_bmp = mime_image[x]; + UINT32 formatId = ClipboardGetFormatId(clipboard->system, mime_bmp); + if (formatId != 0) + wfl_cliprdr_add_client_format_id(clipboard, formatId); + } + wfl_cliprdr_add_client_format_id(clipboard, CF_DIB); + wfl_cliprdr_add_client_format_id(clipboard, CF_TIFF); + } + else if (wlf_mime_is_file(mime)) + { + const UINT32 fileFormatId = + ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + wfl_cliprdr_add_client_format_id(clipboard, fileFormatId); + } + + ClipboardUnlock(clipboard->system); + if (wlf_cliprdr_send_client_format_list(clipboard) != CHANNEL_RC_OK) + return FALSE; + return TRUE; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_send_data_request(wfClipboard* clipboard, const wlf_const_request* rq) +{ + WINPR_ASSERT(rq); + + CLIPRDR_FORMAT_DATA_REQUEST request = { .requestedFormatId = rq->responseFormat }; + + if (!Queue_Enqueue(clipboard->request_queue, rq)) + return ERROR_INTERNAL_ERROR; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatDataRequest); + return clipboard->context->ClientFormatDataRequest(clipboard->context, &request); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_send_data_response(wfClipboard* clipboard, const BYTE* data, size_t size) +{ + CLIPRDR_FORMAT_DATA_RESPONSE response = { 0 }; + + if (size > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + + response.common.msgFlags = (data) ? CB_RESPONSE_OK : CB_RESPONSE_FAIL; + response.common.dataLen = (UINT32)size; + response.requestedFormatData = data; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatDataResponse); + return clipboard->context->ClientFormatDataResponse(clipboard->context, &response); +} + +BOOL wlf_cliprdr_handle_event(wfClipboard* clipboard, const UwacClipboardEvent* event) +{ + if (!clipboard || !event) + return FALSE; + + if (!clipboard->context) + return TRUE; + + switch (event->type) + { + case UWAC_EVENT_CLIPBOARD_AVAILABLE: + clipboard->seat = event->seat; + return TRUE; + + case UWAC_EVENT_CLIPBOARD_OFFER: + WLog_Print(clipboard->log, WLOG_DEBUG, "client announces mime %s", event->mime); + return wlf_cliprdr_add_client_format(clipboard, event->mime); + + case UWAC_EVENT_CLIPBOARD_SELECT: + WLog_Print(clipboard->log, WLOG_DEBUG, "client announces new data"); + wlf_cliprdr_free_client_formats(clipboard); + return TRUE; + + default: + return FALSE; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_send_client_capabilities(wfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet = { + .capabilitySetType = CB_CAPSTYPE_GENERAL, + .capabilitySetLength = 12, + .version = CB_CAPS_VERSION_2, + .generalFlags = + CB_USE_LONG_FORMAT_NAMES | cliprdr_file_context_current_flags(clipboard->file) + }; + CLIPRDR_CAPABILITIES capabilities = { .cCapabilitiesSets = 1, + .capabilitySets = + (CLIPRDR_CAPABILITY_SET*)&(generalCapabilitySet) }; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientCapabilities); + return clipboard->context->ClientCapabilities(clipboard->context, &capabilities); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_send_client_format_list_response(wfClipboard* clipboard, BOOL status) +{ + const CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse = { + .common.msgType = CB_FORMAT_LIST_RESPONSE, + .common.msgFlags = status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL, + .common.dataLen = 0 + }; + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatListResponse); + return clipboard->context->ClientFormatListResponse(clipboard->context, &formatListResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_monitor_ready(CliprdrClientContext* context, + const CLIPRDR_MONITOR_READY* monitorReady) +{ + UINT ret = 0; + + WINPR_UNUSED(monitorReady); + WINPR_ASSERT(context); + WINPR_ASSERT(monitorReady); + + wfClipboard* clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + if ((ret = wlf_cliprdr_send_client_capabilities(clipboard)) != CHANNEL_RC_OK) + return ret; + + if ((ret = wlf_cliprdr_send_client_format_list(clipboard)) != CHANNEL_RC_OK) + return ret; + + clipboard->sync = TRUE; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_server_capabilities(CliprdrClientContext* context, + const CLIPRDR_CAPABILITIES* capabilities) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(capabilities); + + const BYTE* capsPtr = (const BYTE*)capabilities->capabilitySets; + WINPR_ASSERT(capsPtr); + + wfClipboard* clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + if (!cliprdr_file_context_remote_set_flags(clipboard->file, 0)) + return ERROR_INTERNAL_ERROR; + + for (UINT32 i = 0; i < capabilities->cCapabilitiesSets; i++) + { + const CLIPRDR_CAPABILITY_SET* caps = (const CLIPRDR_CAPABILITY_SET*)capsPtr; + + if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL) + { + const CLIPRDR_GENERAL_CAPABILITY_SET* generalCaps = + (const CLIPRDR_GENERAL_CAPABILITY_SET*)caps; + + if (!cliprdr_file_context_remote_set_flags(clipboard->file, generalCaps->generalFlags)) + return ERROR_INTERNAL_ERROR; + } + + capsPtr += caps->capabilitySetLength; + } + + return CHANNEL_RC_OK; +} + +static UINT32 wlf_get_server_format_id(const wfClipboard* clipboard, const char* name) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(name); + + for (UINT32 x = 0; x < clipboard->numServerFormats; x++) + { + const CLIPRDR_FORMAT* format = &clipboard->serverFormats[x]; + if (!format->formatName) + continue; + if (strcmp(name, format->formatName) == 0) + return format->formatId; + } + return 0; +} + +static const char* wlf_get_server_format_name(const wfClipboard* clipboard, UINT32 formatId) +{ + WINPR_ASSERT(clipboard); + + for (UINT32 x = 0; x < clipboard->numServerFormats; x++) + { + const CLIPRDR_FORMAT* format = &clipboard->serverFormats[x]; + if (format->formatId == formatId) + return format->formatName; + } + return NULL; +} + +static void wlf_cliprdr_transfer_data(UwacSeat* seat, void* context, const char* mime, int fd) +{ + wfClipboard* clipboard = (wfClipboard*)context; + WINPR_UNUSED(seat); + + EnterCriticalSection(&clipboard->lock); + + wlf_const_request request = { 0 }; + if (wlf_mime_is_html(mime)) + { + request.responseMime = mime_html; + request.responseFormat = wlf_get_server_format_id(clipboard, type_HtmlFormat); + } + else if (wlf_mime_is_file(mime)) + { + request.responseMime = mime; + request.responseFormat = wlf_get_server_format_id(clipboard, type_FileGroupDescriptorW); + } + else if (wlf_mime_is_text(mime)) + { + request.responseMime = mime_text_plain; + request.responseFormat = CF_UNICODETEXT; + } + else if (wlf_mime_is_image(mime)) + { + request.responseMime = mime; + if (strcmp(mime, mime_tiff) == 0) + request.responseFormat = CF_TIFF; + else + request.responseFormat = CF_DIB; + } + + if (request.responseMime != NULL) + { + request.responseFile = fdopen(fd, "w"); + + if (request.responseFile) + wlf_cliprdr_send_data_request(clipboard, &request); + else + WLog_Print(clipboard->log, WLOG_ERROR, + "failed to open clipboard file descriptor for MIME %s", + request.responseMime); + } + + LeaveCriticalSection(&clipboard->lock); +} + +static void wlf_cliprdr_cancel_data(UwacSeat* seat, void* context) +{ + wfClipboard* clipboard = (wfClipboard*)context; + + WINPR_UNUSED(seat); + WINPR_ASSERT(clipboard); + cliprdr_file_context_clear(clipboard->file); +} + +/** + * Called when the clipboard changes server side. + * + * Clear the local clipboard offer and replace it with a new one + * that announces the formats we get listed here. + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wlf_cliprdr_server_format_list(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST* formatList) +{ + BOOL html = FALSE; + BOOL text = FALSE; + BOOL image = FALSE; + BOOL file = FALSE; + + if (!context || !context->custom) + return ERROR_INVALID_PARAMETER; + + wfClipboard* clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + wlf_cliprdr_free_server_formats(clipboard); + cliprdr_file_context_clear(clipboard->file); + + if (!(clipboard->serverFormats = + (CLIPRDR_FORMAT*)calloc(formatList->numFormats, sizeof(CLIPRDR_FORMAT)))) + { + WLog_Print(clipboard->log, WLOG_ERROR, + "failed to allocate %" PRIuz " CLIPRDR_FORMAT structs", + clipboard->numServerFormats); + return CHANNEL_RC_NO_MEMORY; + } + + clipboard->numServerFormats = formatList->numFormats; + + if (!clipboard->seat) + { + WLog_Print(clipboard->log, WLOG_ERROR, + "clipboard->seat=NULL, check your client implementation"); + return ERROR_INTERNAL_ERROR; + } + + for (UINT32 i = 0; i < formatList->numFormats; i++) + { + const CLIPRDR_FORMAT* format = &formatList->formats[i]; + CLIPRDR_FORMAT* srvFormat = &clipboard->serverFormats[i]; + srvFormat->formatId = format->formatId; + + if (format->formatName) + { + srvFormat->formatName = _strdup(format->formatName); + + if (!srvFormat->formatName) + { + wlf_cliprdr_free_server_formats(clipboard); + return CHANNEL_RC_NO_MEMORY; + } + } + + if (format->formatName) + { + if (strcmp(format->formatName, type_HtmlFormat) == 0) + { + text = TRUE; + html = TRUE; + } + else if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0) + { + file = TRUE; + text = TRUE; + } + } + else + { + switch (format->formatId) + { + case CF_TEXT: + case CF_OEMTEXT: + case CF_UNICODETEXT: + text = TRUE; + break; + + case CF_DIB: + image = TRUE; + break; + + default: + break; + } + } + } + + if (html) + { + UwacClipboardOfferCreate(clipboard->seat, mime_html); + } + + if (file && cliprdr_file_context_has_local_support(clipboard->file)) + { + UwacClipboardOfferCreate(clipboard->seat, mime_uri_list); + UwacClipboardOfferCreate(clipboard->seat, mime_gnome_copied_files); + UwacClipboardOfferCreate(clipboard->seat, mime_mate_copied_files); + } + + if (text) + { + for (size_t x = 0; x < ARRAYSIZE(mime_text); x++) + UwacClipboardOfferCreate(clipboard->seat, mime_text[x]); + } + + if (image) + { + for (size_t x = 0; x < ARRAYSIZE(mime_image); x++) + UwacClipboardOfferCreate(clipboard->seat, mime_image[x]); + } + + UwacClipboardOfferAnnounce(clipboard->seat, clipboard, wlf_cliprdr_transfer_data, + wlf_cliprdr_cancel_data); + return wlf_cliprdr_send_client_format_list_response(clipboard, TRUE); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wlf_cliprdr_server_format_list_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(formatListResponse); + + if (formatListResponse->common.msgFlags & CB_RESPONSE_FAIL) + WLog_WARN(TAG, "format list update failed"); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wlf_cliprdr_server_format_data_request(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest) +{ + UINT rc = CHANNEL_RC_OK; + char* data = NULL; + size_t size = 0; + const char* mime = NULL; + UINT32 formatId = 0; + UINT32 localFormatId = 0; + wfClipboard* clipboard = 0; + + UINT32 dsize = 0; + BYTE* ddata = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(formatDataRequest); + + localFormatId = formatId = formatDataRequest->requestedFormatId; + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + ClipboardLock(clipboard->system); + const UINT32 fileFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + const UINT32 htmlFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat); + + switch (formatId) + { + case CF_TEXT: + case CF_OEMTEXT: + case CF_UNICODETEXT: + localFormatId = ClipboardGetFormatId(clipboard->system, mime_text_plain); + mime = mime_text_utf8; + break; + + case CF_DIB: + case CF_DIBV5: + mime = mime_bitmap[0]; + break; + + case CF_TIFF: + mime = mime_tiff; + break; + + default: + if (formatId == fileFormatId) + { + localFormatId = ClipboardGetFormatId(clipboard->system, mime_uri_list); + mime = mime_uri_list; + } + else if (formatId == htmlFormatId) + { + localFormatId = ClipboardGetFormatId(clipboard->system, mime_html); + mime = mime_html; + } + else + goto fail; + break; + } + + data = UwacClipboardDataGet(clipboard->seat, mime, &size); + + if (!data || (size > UINT32_MAX)) + goto fail; + + if (fileFormatId == formatId) + { + if (!cliprdr_file_context_update_client_data(clipboard->file, data, size)) + goto fail; + } + + const BOOL res = ClipboardSetData(clipboard->system, localFormatId, data, (UINT32)size); + free(data); + + UINT32 len = 0; + data = NULL; + if (res) + data = ClipboardGetData(clipboard->system, formatId, &len); + + if (!res || !data) + goto fail; + + if (fileFormatId == formatId) + { + const UINT32 flags = cliprdr_file_context_remote_get_flags(clipboard->file); + const UINT32 error = cliprdr_serialize_file_list_ex( + flags, (const FILEDESCRIPTORW*)data, len / sizeof(FILEDESCRIPTORW), &ddata, &dsize); + if (error) + goto fail; + } +fail: + ClipboardUnlock(clipboard->system); + rc = wlf_cliprdr_send_data_response(clipboard, ddata, dsize); + free(data); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wlf_cliprdr_server_format_data_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse) +{ + UINT rc = ERROR_INTERNAL_ERROR; + + WINPR_ASSERT(context); + WINPR_ASSERT(formatDataResponse); + + const UINT32 size = formatDataResponse->common.dataLen; + const BYTE* data = formatDataResponse->requestedFormatData; + + wfClipboard* clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + wlf_request* request = Queue_Dequeue(clipboard->request_queue); + if (!request) + goto fail; + + rc = CHANNEL_RC_OK; + if (formatDataResponse->common.msgFlags & CB_RESPONSE_FAIL) + { + WLog_WARN(TAG, "clipboard data request for format %" PRIu32 " [%s], mime %s failed", + request->responseFormat, ClipboardGetFormatIdString(request->responseFormat), + request->responseMime); + goto fail; + } + rc = ERROR_INTERNAL_ERROR; + + ClipboardLock(clipboard->system); + EnterCriticalSection(&clipboard->lock); + + BYTE* cdata = NULL; + UINT32 srcFormatId = 0; + UINT32 dstFormatId = 0; + switch (request->responseFormat) + { + case CF_TEXT: + case CF_OEMTEXT: + case CF_UNICODETEXT: + srcFormatId = request->responseFormat; + dstFormatId = ClipboardGetFormatId(clipboard->system, request->responseMime); + break; + + case CF_DIB: + case CF_DIBV5: + srcFormatId = request->responseFormat; + dstFormatId = ClipboardGetFormatId(clipboard->system, request->responseMime); + break; + + default: + { + const char* name = wlf_get_server_format_name(clipboard, request->responseFormat); + if (name) + { + if (strcmp(type_FileGroupDescriptorW, name) == 0) + { + srcFormatId = + ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + dstFormatId = ClipboardGetFormatId(clipboard->system, request->responseMime); + + if (!cliprdr_file_context_update_server_data(clipboard->file, clipboard->system, + data, size)) + goto unlock; + } + else if (strcmp(type_HtmlFormat, name) == 0) + { + srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat); + dstFormatId = ClipboardGetFormatId(clipboard->system, request->responseMime); + } + } + } + break; + } + + UINT32 len = 0; + + const BOOL sres = ClipboardSetData(clipboard->system, srcFormatId, data, size); + if (sres) + cdata = ClipboardGetData(clipboard->system, dstFormatId, &len); + + if (!sres || !cdata) + goto unlock; + + if (request->responseFile) + { + const size_t res = fwrite(cdata, 1, len, request->responseFile); + if (res == len) + rc = CHANNEL_RC_OK; + } + else + rc = CHANNEL_RC_OK; + +unlock: + free(cdata); + ClipboardUnlock(clipboard->system); + LeaveCriticalSection(&clipboard->lock); +fail: + wlf_request_free(request); + return rc; +} + +wfClipboard* wlf_clipboard_new(wlfContext* wfc) +{ + rdpChannels* channels = NULL; + wfClipboard* clipboard = NULL; + + WINPR_ASSERT(wfc); + + clipboard = (wfClipboard*)calloc(1, sizeof(wfClipboard)); + + if (!clipboard) + goto fail; + + InitializeCriticalSection(&clipboard->lock); + clipboard->wfc = wfc; + channels = wfc->common.context.channels; + clipboard->log = WLog_Get(TAG); + clipboard->channels = channels; + clipboard->system = ClipboardCreate(); + if (!clipboard->system) + goto fail; + + clipboard->file = cliprdr_file_context_new(clipboard); + if (!clipboard->file) + goto fail; + + if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE)) + goto fail; + + clipboard->request_queue = Queue_New(TRUE, -1, -1); + if (!clipboard->request_queue) + goto fail; + + wObject* obj = Queue_Object(clipboard->request_queue); + WINPR_ASSERT(obj); + obj->fnObjectFree = wlf_request_free; + obj->fnObjectNew = wlf_request_clone; + + return clipboard; + +fail: + wlf_clipboard_free(clipboard); + return NULL; +} + +void wlf_clipboard_free(wfClipboard* clipboard) +{ + if (!clipboard) + return; + + cliprdr_file_context_free(clipboard->file); + + wlf_cliprdr_free_server_formats(clipboard); + wlf_cliprdr_free_client_formats(clipboard); + ClipboardDestroy(clipboard->system); + + EnterCriticalSection(&clipboard->lock); + + Queue_Free(clipboard->request_queue); + LeaveCriticalSection(&clipboard->lock); + DeleteCriticalSection(&clipboard->lock); + free(clipboard); +} + +BOOL wlf_cliprdr_init(wfClipboard* clipboard, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(cliprdr); + + clipboard->context = cliprdr; + cliprdr->MonitorReady = wlf_cliprdr_monitor_ready; + cliprdr->ServerCapabilities = wlf_cliprdr_server_capabilities; + cliprdr->ServerFormatList = wlf_cliprdr_server_format_list; + cliprdr->ServerFormatListResponse = wlf_cliprdr_server_format_list_response; + cliprdr->ServerFormatDataRequest = wlf_cliprdr_server_format_data_request; + cliprdr->ServerFormatDataResponse = wlf_cliprdr_server_format_data_response; + + return cliprdr_file_context_init(clipboard->file, cliprdr); +} + +BOOL wlf_cliprdr_uninit(wfClipboard* clipboard, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(clipboard); + if (!cliprdr_file_context_uninit(clipboard->file, cliprdr)) + return FALSE; + + if (cliprdr) + cliprdr->custom = NULL; + + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.h new file mode 100644 index 0000000000000000000000000000000000000000..07d58bcff9a8b8c99478caf69a312eaf0e40c7b5 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_cliprdr.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Clipboard Redirection + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WAYLAND_CLIPRDR_H +#define FREERDP_CLIENT_WAYLAND_CLIPRDR_H + +#include "wlfreerdp.h" + +#include + +wfClipboard* wlf_clipboard_new(wlfContext* wfc); +void wlf_clipboard_free(wfClipboard* clipboard); + +BOOL wlf_cliprdr_init(wfClipboard* clipboard, CliprdrClientContext* cliprdr); +BOOL wlf_cliprdr_uninit(wfClipboard* clipboard, CliprdrClientContext* cliprdr); + +BOOL wlf_cliprdr_handle_event(wfClipboard* clipboard, const UwacClipboardEvent* event); + +#endif /* FREERDP_CLIENT_WAYLAND_CLIPRDR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.c new file mode 100644 index 0000000000000000000000000000000000000000..741d7113bcbbd89a647e01106579e3570eb79908 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.c @@ -0,0 +1,458 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Display Control Channel + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "wlf_disp.h" + +#define TAG CLIENT_TAG("wayland.disp") + +#define RESIZE_MIN_DELAY 200 /* minimum delay in ms between two resizes */ + +struct s_wlfDispContext +{ + wlfContext* wlc; + DispClientContext* disp; + BOOL haveXRandr; + int eventBase, errorBase; + int lastSentWidth, lastSentHeight; + UINT64 lastSentDate; + int targetWidth, targetHeight; + BOOL activated; + BOOL waitingResize; + BOOL fullscreen; + UINT16 lastSentDesktopOrientation; + UINT32 lastSentDesktopScaleFactor; + UINT32 lastSentDeviceScaleFactor; +}; + +static UINT wlf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, + size_t nmonitors); + +static BOOL wlf_disp_settings_changed(wlfDispContext* wlfDisp) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(wlfDisp); + WINPR_ASSERT(wlfDisp->wlc); + + settings = wlfDisp->wlc->common.context.settings; + WINPR_ASSERT(settings); + + if (wlfDisp->lastSentWidth != wlfDisp->targetWidth) + return TRUE; + + if (wlfDisp->lastSentHeight != wlfDisp->targetHeight) + return TRUE; + + if (wlfDisp->lastSentDesktopOrientation != + freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation)) + return TRUE; + + if (wlfDisp->lastSentDesktopScaleFactor != + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor)) + return TRUE; + + if (wlfDisp->lastSentDeviceScaleFactor != + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor)) + return TRUE; + + if (wlfDisp->fullscreen != wlfDisp->wlc->fullscreen) + return TRUE; + + return FALSE; +} + +static BOOL wlf_update_last_sent(wlfDispContext* wlfDisp) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(wlfDisp); + WINPR_ASSERT(wlfDisp->wlc); + + settings = wlfDisp->wlc->common.context.settings; + WINPR_ASSERT(settings); + + wlfDisp->lastSentWidth = wlfDisp->targetWidth; + wlfDisp->lastSentHeight = wlfDisp->targetHeight; + wlfDisp->lastSentDesktopOrientation = + freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation); + wlfDisp->lastSentDesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + wlfDisp->lastSentDeviceScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + wlfDisp->fullscreen = wlfDisp->wlc->fullscreen; + return TRUE; +} + +static BOOL wlf_disp_sendResize(wlfDispContext* wlfDisp) +{ + DISPLAY_CONTROL_MONITOR_LAYOUT layout; + wlfContext* wlc = NULL; + rdpSettings* settings = NULL; + + if (!wlfDisp || !wlfDisp->wlc) + return FALSE; + + wlc = wlfDisp->wlc; + settings = wlc->common.context.settings; + + if (!settings) + return FALSE; + + if (!wlfDisp->activated || !wlfDisp->disp) + return TRUE; + + if (GetTickCount64() - wlfDisp->lastSentDate < RESIZE_MIN_DELAY) + return TRUE; + + wlfDisp->lastSentDate = GetTickCount64(); + + if (!wlf_disp_settings_changed(wlfDisp)) + return TRUE; + + /* TODO: Multimonitor support for wayland + if (wlc->fullscreen && (freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount > 0)) + { + if (wlf_disp_sendLayout(wlfDisp->disp, setings->MonitorDefArray, + freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount) != + CHANNEL_RC_OK) return FALSE; + } + else + */ + { + wlfDisp->waitingResize = TRUE; + layout.Flags = DISPLAY_CONTROL_MONITOR_PRIMARY; + layout.Top = layout.Left = 0; + layout.Width = WINPR_ASSERTING_INT_CAST(uint32_t, wlfDisp->targetWidth); + layout.Height = WINPR_ASSERTING_INT_CAST(uint32_t, wlfDisp->targetHeight); + layout.Orientation = freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation); + layout.DesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + layout.DeviceScaleFactor = freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + layout.PhysicalWidth = WINPR_ASSERTING_INT_CAST(uint32_t, wlfDisp->targetWidth); + layout.PhysicalHeight = WINPR_ASSERTING_INT_CAST(uint32_t, wlfDisp->targetHeight); + + if (IFCALLRESULT(CHANNEL_RC_OK, wlfDisp->disp->SendMonitorLayout, wlfDisp->disp, 1, + &layout) != CHANNEL_RC_OK) + return FALSE; + } + return wlf_update_last_sent(wlfDisp); +} + +static BOOL wlf_disp_set_window_resizable(wlfDispContext* wlfDisp) +{ +#if 0 // TODO +#endif + return TRUE; +} + +static BOOL wlf_disp_check_context(void* context, wlfContext** ppwlc, wlfDispContext** ppwlfDisp, + rdpSettings** ppSettings) +{ + wlfContext* wlc = NULL; + + if (!context) + return FALSE; + + wlc = (wlfContext*)context; + + if (!(wlc->disp)) + return FALSE; + + if (!wlc->common.context.settings) + return FALSE; + + *ppwlc = wlc; + *ppwlfDisp = wlc->disp; + *ppSettings = wlc->common.context.settings; + return TRUE; +} + +static void wlf_disp_OnActivated(void* context, const ActivatedEventArgs* e) +{ + wlfContext* wlc = NULL; + wlfDispContext* wlfDisp = NULL; + rdpSettings* settings = NULL; + + if (!wlf_disp_check_context(context, &wlc, &wlfDisp, &settings)) + return; + + wlfDisp->waitingResize = FALSE; + + if (wlfDisp->activated && !freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + wlf_disp_set_window_resizable(wlfDisp); + + if (e->firstActivation) + return; + + wlf_disp_sendResize(wlfDisp); + } +} + +static void wlf_disp_OnGraphicsReset(void* context, const GraphicsResetEventArgs* e) +{ + wlfContext* wlc = NULL; + wlfDispContext* wlfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(e); + if (!wlf_disp_check_context(context, &wlc, &wlfDisp, &settings)) + return; + + wlfDisp->waitingResize = FALSE; + + if (wlfDisp->activated && !freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + wlf_disp_set_window_resizable(wlfDisp); + wlf_disp_sendResize(wlfDisp); + } +} + +static void wlf_disp_OnTimer(void* context, const TimerEventArgs* e) +{ + wlfContext* wlc = NULL; + wlfDispContext* wlfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(e); + if (!wlf_disp_check_context(context, &wlc, &wlfDisp, &settings)) + return; + + if (!wlfDisp->activated || freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + return; + + wlf_disp_sendResize(wlfDisp); +} + +wlfDispContext* wlf_disp_new(wlfContext* wlc) +{ + wlfDispContext* ret = NULL; + wPubSub* pubSub = NULL; + rdpSettings* settings = NULL; + + if (!wlc || !wlc->common.context.settings || !wlc->common.context.pubSub) + return NULL; + + settings = wlc->common.context.settings; + pubSub = wlc->common.context.pubSub; + ret = calloc(1, sizeof(wlfDispContext)); + + if (!ret) + return NULL; + + ret->wlc = wlc; + ret->lastSentWidth = ret->targetWidth = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + ret->lastSentHeight = ret->targetHeight = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + PubSub_SubscribeActivated(pubSub, wlf_disp_OnActivated); + PubSub_SubscribeGraphicsReset(pubSub, wlf_disp_OnGraphicsReset); + PubSub_SubscribeTimer(pubSub, wlf_disp_OnTimer); + return ret; +} + +void wlf_disp_free(wlfDispContext* disp) +{ + if (!disp) + return; + + if (disp->wlc) + { + wPubSub* pubSub = disp->wlc->common.context.pubSub; + PubSub_UnsubscribeActivated(pubSub, wlf_disp_OnActivated); + PubSub_UnsubscribeGraphicsReset(pubSub, wlf_disp_OnGraphicsReset); + PubSub_UnsubscribeTimer(pubSub, wlf_disp_OnTimer); + } + + free(disp); +} + +UINT wlf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, size_t nmonitors) +{ + UINT ret = CHANNEL_RC_OK; + DISPLAY_CONTROL_MONITOR_LAYOUT* layouts = NULL; + wlfDispContext* wlfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(disp); + WINPR_ASSERT(monitors); + WINPR_ASSERT(nmonitors > 0); + WINPR_ASSERT(nmonitors <= UINT32_MAX); + + wlfDisp = (wlfDispContext*)disp->custom; + WINPR_ASSERT(wlfDisp); + WINPR_ASSERT(wlfDisp->wlc); + + settings = wlfDisp->wlc->common.context.settings; + WINPR_ASSERT(settings); + + layouts = calloc(nmonitors, sizeof(DISPLAY_CONTROL_MONITOR_LAYOUT)); + + if (!layouts) + return CHANNEL_RC_NO_MEMORY; + + for (size_t i = 0; i < nmonitors; i++) + { + const rdpMonitor* monitor = &monitors[i]; + DISPLAY_CONTROL_MONITOR_LAYOUT* layout = &layouts[i]; + + layout->Flags = (monitor->is_primary ? DISPLAY_CONTROL_MONITOR_PRIMARY : 0); + layout->Left = monitor->x; + layout->Top = monitor->y; + layout->Width = WINPR_ASSERTING_INT_CAST(UINT32, monitor->width); + layout->Height = WINPR_ASSERTING_INT_CAST(UINT32, monitor->height); + layout->Orientation = ORIENTATION_LANDSCAPE; + layout->PhysicalWidth = monitor->attributes.physicalWidth; + layout->PhysicalHeight = monitor->attributes.physicalHeight; + + switch (monitor->attributes.orientation) + { + case 90: + layout->Orientation = ORIENTATION_PORTRAIT; + break; + + case 180: + layout->Orientation = ORIENTATION_LANDSCAPE_FLIPPED; + break; + + case 270: + layout->Orientation = ORIENTATION_PORTRAIT_FLIPPED; + break; + + case 0: + default: + /* MS-RDPEDISP - 2.2.2.2.1: + * Orientation (4 bytes): A 32-bit unsigned integer that specifies the + * orientation of the monitor in degrees. Valid values are 0, 90, 180 + * or 270 + * + * So we default to ORIENTATION_LANDSCAPE + */ + layout->Orientation = ORIENTATION_LANDSCAPE; + break; + } + + layout->DesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + layout->DeviceScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + } + + ret = IFCALLRESULT(CHANNEL_RC_OK, disp->SendMonitorLayout, disp, (UINT32)nmonitors, layouts); + free(layouts); + return ret; +} + +BOOL wlf_disp_handle_configure(wlfDispContext* disp, int32_t width, int32_t height) +{ + if (!disp) + return FALSE; + + disp->targetWidth = width; + disp->targetHeight = height; + return wlf_disp_sendResize(disp); +} + +static UINT wlf_DisplayControlCaps(DispClientContext* disp, UINT32 maxNumMonitors, + UINT32 maxMonitorAreaFactorA, UINT32 maxMonitorAreaFactorB) +{ + /* we're called only if dynamic resolution update is activated */ + wlfDispContext* wlfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(disp); + + wlfDisp = (wlfDispContext*)disp->custom; + WINPR_ASSERT(wlfDisp); + WINPR_ASSERT(wlfDisp->wlc); + + settings = wlfDisp->wlc->common.context.settings; + WINPR_ASSERT(settings); + + WLog_DBG(TAG, + "DisplayControlCapsPdu: MaxNumMonitors: %" PRIu32 " MaxMonitorAreaFactorA: %" PRIu32 + " MaxMonitorAreaFactorB: %" PRIu32 "", + maxNumMonitors, maxMonitorAreaFactorA, maxMonitorAreaFactorB); + wlfDisp->activated = TRUE; + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + return CHANNEL_RC_OK; + + WLog_DBG(TAG, "DisplayControlCapsPdu: setting the window as resizable"); + return wlf_disp_set_window_resizable(wlfDisp) ? CHANNEL_RC_OK : CHANNEL_RC_NO_MEMORY; +} + +BOOL wlf_disp_init(wlfDispContext* wlfDisp, DispClientContext* disp) +{ + rdpSettings* settings = NULL; + + if (!wlfDisp || !wlfDisp->wlc || !disp) + return FALSE; + + settings = wlfDisp->wlc->common.context.settings; + + if (!settings) + return FALSE; + + wlfDisp->disp = disp; + disp->custom = (void*)wlfDisp; + + if (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) + { + disp->DisplayControlCaps = wlf_DisplayControlCaps; + } + + return TRUE; +} + +BOOL wlf_disp_uninit(wlfDispContext* wlfDisp, DispClientContext* disp) +{ + if (!wlfDisp || !disp) + return FALSE; + + wlfDisp->disp = NULL; + return TRUE; +} + +int wlf_list_monitors(wlfContext* wlc) +{ + uint32_t nmonitors = UwacDisplayGetNbOutputs(wlc->display); + + for (uint32_t i = 0; i < nmonitors; i++) + { + const UwacOutput* monitor = + UwacDisplayGetOutput(wlc->display, WINPR_ASSERTING_INT_CAST(int, i)); + UwacSize resolution; + UwacPosition pos; + + if (!monitor) + continue; + UwacOutputGetPosition(monitor, &pos); + UwacOutputGetResolution(monitor, &resolution); + + printf(" %s [%u] %dx%d\t+%d+%d\n", (i == 0) ? "*" : " ", i, resolution.width, + resolution.height, pos.x, pos.y); + } + + return 0; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.h new file mode 100644 index 0000000000000000000000000000000000000000..36fa27c7b21b59b572c870a7c9c4a05196cc9ae5 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_disp.h @@ -0,0 +1,38 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Display Control Channel + * + * Copyright 2018 Armin Novak + * Copyright 2018 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FREERDP_CLIENT_WAYLAND_DISP_H +#define FREERDP_CLIENT_WAYLAND_DISP_H + +#include +#include + +#include "wlfreerdp.h" + +FREERDP_API BOOL wlf_disp_init(wlfDispContext* xfDisp, DispClientContext* disp); +FREERDP_API BOOL wlf_disp_uninit(wlfDispContext* xfDisp, DispClientContext* disp); + +wlfDispContext* wlf_disp_new(wlfContext* wlc); +void wlf_disp_free(wlfDispContext* disp); +BOOL wlf_disp_handle_configure(wlfDispContext* disp, int32_t width, int32_t height); +void wlf_disp_resized(wlfDispContext* disp); + +int wlf_list_monitors(wlfContext* wlc); + +#endif /* FREERDP_CLIENT_WAYLAND_DISP_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.c new file mode 100644 index 0000000000000000000000000000000000000000..b56d0a9a9fb89de96155491b42e2edbf7e21723d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.c @@ -0,0 +1,455 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Input + * + * Copyright 2014 Manuel Bachmann + * Copyright 2015 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include + +#include +#include + +#include +#include +#if defined(CHANNEL_RDPEI_CLIENT) +#include +#endif +#include + +#include "wlfreerdp.h" +#include "wlf_input.h" + +static BOOL scale_signed_coordinates(rdpContext* context, int32_t* x, int32_t* y, + BOOL fromLocalToRDP) +{ + BOOL rc = 0; + UINT32 ux = 0; + UINT32 uy = 0; + WINPR_ASSERT(context); + WINPR_ASSERT(x); + WINPR_ASSERT(y); + WINPR_ASSERT(*x >= 0); + WINPR_ASSERT(*y >= 0); + + ux = (UINT32)*x; + uy = (UINT32)*y; + rc = wlf_scale_coordinates(context, &ux, &uy, fromLocalToRDP); + WINPR_ASSERT(ux < INT32_MAX); + WINPR_ASSERT(uy < INT32_MAX); + *x = (int32_t)ux; + *y = (int32_t)uy; + return rc; +} + +BOOL wlf_handle_pointer_enter(freerdp* instance, const UwacPointerEnterLeaveEvent* ev) +{ + uint32_t x = 0; + uint32_t y = 0; + rdpClientContext* cctx = NULL; + + if (!instance || !ev) + return FALSE; + + x = ev->x; + y = ev->y; + + if (!wlf_scale_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + cctx = (rdpClientContext*)instance->context; + return freerdp_client_send_button_event(cctx, FALSE, PTR_FLAGS_MOVE, + WINPR_ASSERTING_INT_CAST(int, x), + WINPR_ASSERTING_INT_CAST(int, y)); +} + +BOOL wlf_handle_pointer_motion(freerdp* instance, const UwacPointerMotionEvent* ev) +{ + rdpClientContext* cctx = NULL; + + if (!instance || !ev) + return FALSE; + + cctx = (rdpClientContext*)instance->context; + WINPR_ASSERT(cctx); + + uint32_t x = ev->x; + uint32_t y = ev->y; + + if (!wlf_scale_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + return freerdp_client_send_button_event(cctx, FALSE, PTR_FLAGS_MOVE, + WINPR_ASSERTING_INT_CAST(int32_t, x), + WINPR_ASSERTING_INT_CAST(int32_t, y)); +} + +BOOL wlf_handle_pointer_buttons(freerdp* instance, const UwacPointerButtonEvent* ev) +{ + rdpClientContext* cctx = NULL; + UINT16 flags = 0; + UINT16 xflags = 0; + + if (!instance || !ev) + return FALSE; + + cctx = (rdpClientContext*)instance->context; + WINPR_ASSERT(cctx); + + uint32_t x = ev->x; + uint32_t y = ev->y; + + if (!wlf_scale_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + if (ev->state == WL_POINTER_BUTTON_STATE_PRESSED) + { + flags |= PTR_FLAGS_DOWN; + xflags |= PTR_XFLAGS_DOWN; + } + + switch (ev->button) + { + case BTN_LEFT: + flags |= PTR_FLAGS_BUTTON1; + break; + + case BTN_RIGHT: + flags |= PTR_FLAGS_BUTTON2; + break; + + case BTN_MIDDLE: + flags |= PTR_FLAGS_BUTTON3; + break; + + case BTN_SIDE: + xflags |= PTR_XFLAGS_BUTTON1; + break; + + case BTN_EXTRA: + xflags |= PTR_XFLAGS_BUTTON2; + break; + + default: + return TRUE; + } + + const INT32 cx = WINPR_ASSERTING_INT_CAST(int32_t, x); + const INT32 cy = WINPR_ASSERTING_INT_CAST(int32_t, y); + + if ((flags & ~PTR_FLAGS_DOWN) != 0) + return freerdp_client_send_button_event(cctx, FALSE, flags, cx, cy); + + if ((xflags & ~PTR_XFLAGS_DOWN) != 0) + return freerdp_client_send_extended_button_event(cctx, FALSE, xflags, cx, cy); + + return FALSE; +} + +BOOL wlf_handle_pointer_axis(freerdp* instance, const UwacPointerAxisEvent* ev) +{ + wlfContext* context = NULL; + if (!instance || !instance->context || !ev) + return FALSE; + + context = (wlfContext*)instance->context; + return ArrayList_Append(context->events, ev); +} + +BOOL wlf_handle_pointer_axis_discrete(freerdp* instance, const UwacPointerAxisEvent* ev) +{ + wlfContext* context = NULL; + if (!instance || !instance->context || !ev) + return FALSE; + + context = (wlfContext*)instance->context; + return ArrayList_Append(context->events, ev); +} + +static BOOL wlf_handle_wheel(freerdp* instance, uint32_t x, uint32_t y, uint32_t axis, + int32_t value) +{ + rdpClientContext* cctx = NULL; + UINT16 flags = 0; + int32_t direction = 0; + uint32_t avalue = (uint32_t)abs(value); + + WINPR_ASSERT(instance); + + cctx = (rdpClientContext*)instance->context; + WINPR_ASSERT(cctx); + + if (!wlf_scale_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + direction = value; + switch (axis) + { + case WL_POINTER_AXIS_VERTICAL_SCROLL: + flags |= PTR_FLAGS_WHEEL; + if (direction > 0) + flags |= PTR_FLAGS_WHEEL_NEGATIVE; + break; + + case WL_POINTER_AXIS_HORIZONTAL_SCROLL: + flags |= PTR_FLAGS_HWHEEL; + if (direction < 0) + flags |= PTR_FLAGS_WHEEL_NEGATIVE; + break; + + default: + return FALSE; + } + + /* Wheel rotation steps: + * + * positive: 0 ... 0xFF -> slow ... fast + * negative: 0 ... 0xFF -> fast ... slow + */ + + while (avalue > 0) + { + const UINT16 cval = (avalue > 0xFF) ? 0xFF : (UINT16)avalue; + UINT16 cflags = flags | cval; + /* Convert negative values to 9bit twos complement */ + if (flags & PTR_FLAGS_WHEEL_NEGATIVE) + cflags = (flags & 0xFF00) | (0x100 - cval); + if (!freerdp_client_send_wheel_event(cctx, cflags)) + return FALSE; + + avalue -= cval; + } + return TRUE; +} + +BOOL wlf_handle_pointer_frame(freerdp* instance, const UwacPointerFrameEvent* ev) +{ + BOOL success = TRUE; + BOOL handle = FALSE; + wlfContext* context = NULL; + enum wl_pointer_axis_source source = WL_POINTER_AXIS_SOURCE_CONTINUOUS; + + if (!instance || !ev || !instance->context) + return FALSE; + + context = (wlfContext*)instance->context; + + for (size_t x = 0; x < ArrayList_Count(context->events); x++) + { + UwacEvent* cev = ArrayList_GetItem(context->events, x); + if (!cev) + continue; + if (cev->type == UWAC_EVENT_POINTER_SOURCE) + { + handle = TRUE; + source = cev->mouse_source.axis_source; + } + } + + /* We need source events to determine how to interpret the data */ + if (handle) + { + for (size_t x = 0; x < ArrayList_Count(context->events); x++) + { + UwacEvent* cev = ArrayList_GetItem(context->events, x); + if (!cev) + continue; + + switch (source) + { + /* If we have a mouse wheel, just use discrete data */ + case WL_POINTER_AXIS_SOURCE_WHEEL: +#if defined(WL_POINTER_AXIS_SOURCE_WHEEL_TILT_SINCE_VERSION) + case WL_POINTER_AXIS_SOURCE_WHEEL_TILT: +#endif + if (cev->type == UWAC_EVENT_POINTER_AXIS_DISCRETE) + { + /* Get the number of steps, multiply by default step width of 120 */ + int32_t val = cev->mouse_axis.value * 0x78; + /* No wheel event received, success! */ + if (!wlf_handle_wheel(instance, cev->mouse_axis.x, cev->mouse_axis.y, + cev->mouse_axis.axis, val)) + success = FALSE; + } + break; + /* If we have a touch pad we get actual data, scale */ + case WL_POINTER_AXIS_SOURCE_FINGER: + case WL_POINTER_AXIS_SOURCE_CONTINUOUS: + if (cev->type == UWAC_EVENT_POINTER_AXIS) + { + double dval = wl_fixed_to_double(cev->mouse_axis.value); + int32_t val = (int32_t)(dval * 0x78 / 10.0); + if (!wlf_handle_wheel(instance, cev->mouse_axis.x, cev->mouse_axis.y, + cev->mouse_axis.axis, val)) + success = FALSE; + } + break; + default: + break; + } + } + } + ArrayList_Clear(context->events); + return success; +} + +BOOL wlf_handle_pointer_source(freerdp* instance, const UwacPointerSourceEvent* ev) +{ + wlfContext* context = NULL; + if (!instance || !instance->context || !ev) + return FALSE; + + context = (wlfContext*)instance->context; + return ArrayList_Append(context->events, ev); +} + +BOOL wlf_handle_key(freerdp* instance, const UwacKeyEvent* ev) +{ + if (!instance || !ev) + return FALSE; + + WINPR_ASSERT(instance->context); + wlfContext* ctx = (wlfContext*)instance->context; + if (freerdp_settings_get_bool(instance->context->settings, FreeRDP_GrabKeyboard) && + ev->raw_key == KEY_RIGHTCTRL) + wlf_handle_ungrab_key(instance, ev); + + rdpInput* input = instance->context->input; + + const DWORD vc = GetVirtualKeyCodeFromKeycode(ev->raw_key, WINPR_KEYCODE_TYPE_EVDEV); + const DWORD sc = GetVirtualScanCodeFromVirtualKeyCode(vc, WINPR_KBD_TYPE_IBM_ENHANCED); + const DWORD rdp_scancode = freerdp_keyboard_remap_key(ctx->remap_table, sc); + + if (rdp_scancode == RDP_SCANCODE_UNKNOWN) + return TRUE; + + return freerdp_input_send_keyboard_event_ex(input, ev->pressed, ev->repeated, rdp_scancode); +} + +BOOL wlf_handle_ungrab_key(freerdp* instance, const UwacKeyEvent* ev) +{ + wlfContext* context = NULL; + if (!instance || !instance->context || !ev) + return FALSE; + + context = (wlfContext*)instance->context; + + return UwacSeatInhibitShortcuts(context->seat, false) == UWAC_SUCCESS; +} + +BOOL wlf_keyboard_enter(freerdp* instance, const UwacKeyboardEnterLeaveEvent* ev) +{ + if (!instance || !ev) + return FALSE; + + ((wlfContext*)instance->context)->focusing = TRUE; + return TRUE; +} + +BOOL wlf_keyboard_modifiers(freerdp* instance, const UwacKeyboardModifiersEvent* ev) +{ + rdpInput* input = NULL; + UINT16 syncFlags = 0; + wlfContext* wlf = NULL; + + if (!instance || !ev) + return FALSE; + + wlf = (wlfContext*)instance->context; + WINPR_ASSERT(wlf); + + input = instance->context->input; + WINPR_ASSERT(input); + + syncFlags = 0; + + if (ev->modifiers & UWAC_MOD_CAPS_MASK) + syncFlags |= KBD_SYNC_CAPS_LOCK; + if (ev->modifiers & UWAC_MOD_NUM_MASK) + syncFlags |= KBD_SYNC_NUM_LOCK; + + if (!wlf->focusing) + return TRUE; + + ((wlfContext*)instance->context)->focusing = FALSE; + + return freerdp_input_send_focus_in_event(input, syncFlags) && + freerdp_client_send_button_event(&wlf->common, FALSE, PTR_FLAGS_MOVE, 0, 0); +} + +BOOL wlf_handle_touch_up(freerdp* instance, const UwacTouchUp* ev) +{ + int32_t x = 0; + int32_t y = 0; + + WINPR_ASSERT(instance); + WINPR_ASSERT(ev); + + wlfContext* wlf = (wlfContext*)instance->context; + WINPR_ASSERT(wlf); + + x = ev->x; + y = ev->y; + + if (!scale_signed_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + return freerdp_client_handle_touch(&wlf->common, FREERDP_TOUCH_UP, ev->id, 0, x, y); +} + +BOOL wlf_handle_touch_down(freerdp* instance, const UwacTouchDown* ev) +{ + int32_t x = 0; + int32_t y = 0; + + WINPR_ASSERT(instance); + WINPR_ASSERT(ev); + + wlfContext* wlf = (wlfContext*)instance->context; + WINPR_ASSERT(wlf); + + x = ev->x; + y = ev->y; + + if (!scale_signed_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + return freerdp_client_handle_touch(&wlf->common, FREERDP_TOUCH_DOWN, ev->id, 0, x, y); +} + +BOOL wlf_handle_touch_motion(freerdp* instance, const UwacTouchMotion* ev) +{ + int32_t x = 0; + int32_t y = 0; + + WINPR_ASSERT(instance); + WINPR_ASSERT(ev); + + wlfContext* wlf = (wlfContext*)instance->context; + WINPR_ASSERT(wlf); + + x = ev->x; + y = ev->y; + + if (!scale_signed_coordinates(instance->context, &x, &y, TRUE)) + return FALSE; + + return freerdp_client_handle_touch(&wlf->common, FREERDP_TOUCH_MOTION, 0, + WINPR_ASSERTING_INT_CAST(uint32_t, ev->id), x, y); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.h new file mode 100644 index 0000000000000000000000000000000000000000..0d4f5efa25581930cc2b90f7539c99f52e08c22f --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_input.h @@ -0,0 +1,45 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Input + * + * Copyright 2014 Manuel Bachmann + * Copyright 2015 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WAYLAND_INPUT_H +#define FREERDP_CLIENT_WAYLAND_INPUT_H + +#include +#include +#include +#include + +BOOL wlf_handle_pointer_enter(freerdp* instance, const UwacPointerEnterLeaveEvent* ev); +BOOL wlf_handle_pointer_motion(freerdp* instance, const UwacPointerMotionEvent* ev); +BOOL wlf_handle_pointer_buttons(freerdp* instance, const UwacPointerButtonEvent* ev); +BOOL wlf_handle_pointer_axis(freerdp* instance, const UwacPointerAxisEvent* ev); +BOOL wlf_handle_pointer_axis_discrete(freerdp* instance, const UwacPointerAxisEvent* ev); +BOOL wlf_handle_pointer_frame(freerdp* instance, const UwacPointerFrameEvent* ev); +BOOL wlf_handle_pointer_source(freerdp* instance, const UwacPointerSourceEvent* ev); +BOOL wlf_handle_touch_up(freerdp* instance, const UwacTouchUp* ev); +BOOL wlf_handle_touch_down(freerdp* instance, const UwacTouchDown* ev); +BOOL wlf_handle_touch_motion(freerdp* instance, const UwacTouchMotion* ev); + +BOOL wlf_handle_key(freerdp* instance, const UwacKeyEvent* ev); +BOOL wlf_handle_ungrab_key(freerdp* instance, const UwacKeyEvent* ev); +BOOL wlf_keyboard_enter(freerdp* instance, const UwacKeyboardEnterLeaveEvent* ev); +BOOL wlf_keyboard_modifiers(freerdp* instance, const UwacKeyboardModifiersEvent* ev); + +#endif /* FREERDP_CLIENT_WAYLAND_INPUT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.c new file mode 100644 index 0000000000000000000000000000000000000000..eebc4ba198276ab6dc1b96d39218bb94cc9dbbaa --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.c @@ -0,0 +1,167 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Mouse Pointer + * + * Copyright 2019 Armin Novak + * Copyright 2019 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "wlf_pointer.h" +#include "wlfreerdp.h" + +#define TAG CLIENT_TAG("wayland.pointer") + +typedef struct +{ + rdpPointer pointer; + size_t size; + void* data; +} wlfPointer; + +static BOOL wlf_Pointer_New(rdpContext* context, rdpPointer* pointer) +{ + wlfPointer* ptr = (wlfPointer*)pointer; + + if (!ptr) + return FALSE; + + ptr->size = 4ULL * pointer->width * pointer->height; + ptr->data = winpr_aligned_malloc(ptr->size, 16); + + if (!ptr->data) + return FALSE; + + if (!freerdp_image_copy_from_pointer_data( + ptr->data, PIXEL_FORMAT_BGRA32, 0, 0, 0, pointer->width, pointer->height, + pointer->xorMaskData, pointer->lengthXorMask, pointer->andMaskData, + pointer->lengthAndMask, pointer->xorBpp, &context->gdi->palette)) + { + winpr_aligned_free(ptr->data); + return FALSE; + } + + return TRUE; +} + +static void wlf_Pointer_Free(rdpContext* context, rdpPointer* pointer) +{ + wlfPointer* ptr = (wlfPointer*)pointer; + WINPR_UNUSED(context); + + if (ptr) + winpr_aligned_free(ptr->data); +} + +static BOOL wlf_Pointer_Set(rdpContext* context, rdpPointer* pointer) +{ + wlfContext* wlf = (wlfContext*)context; + wlfPointer* ptr = (wlfPointer*)pointer; + void* data = NULL; + UINT32 w = 0; + UINT32 h = 0; + UINT32 x = 0; + UINT32 y = 0; + size_t size = 0; + UwacReturnCode rc = UWAC_ERROR_INTERNAL; + BOOL res = FALSE; + RECTANGLE_16 area; + + if (!wlf || !wlf->seat) + return FALSE; + + x = pointer->xPos; + y = pointer->yPos; + w = pointer->width; + h = pointer->height; + + if (!wlf_scale_coordinates(context, &x, &y, FALSE) || + !wlf_scale_coordinates(context, &w, &h, FALSE)) + return FALSE; + + size = 4ULL * w * h; + data = malloc(size); + + if (!data) + return FALSE; + + area.top = 0; + area.left = 0; + area.right = (UINT16)pointer->width; + area.bottom = (UINT16)pointer->height; + + if (!wlf_copy_image(ptr->data, 4ULL * pointer->width, pointer->width, pointer->height, data, + 4ULL * w, w, h, &area, + freerdp_settings_get_bool(context->settings, FreeRDP_SmartSizing))) + goto fail; + + rc = UwacSeatSetMouseCursor(wlf->seat, data, size, w, h, x, y); + + if (rc == UWAC_SUCCESS) + res = TRUE; + +fail: + free(data); + return res; +} + +static BOOL wlf_Pointer_SetNull(rdpContext* context) +{ + wlfContext* wlf = (wlfContext*)context; + + if (!wlf || !wlf->seat) + return FALSE; + + if (UwacSeatSetMouseCursor(wlf->seat, NULL, 0, 0, 0, 0, 0) != UWAC_SUCCESS) + return FALSE; + + return TRUE; +} + +static BOOL wlf_Pointer_SetDefault(rdpContext* context) +{ + wlfContext* wlf = (wlfContext*)context; + + if (!wlf || !wlf->seat) + return FALSE; + + if (UwacSeatSetMouseCursor(wlf->seat, NULL, 1, 0, 0, 0, 0) != UWAC_SUCCESS) + return FALSE; + + return TRUE; +} + +static BOOL wlf_Pointer_SetPosition(rdpContext* context, UINT32 x, UINT32 y) +{ + // TODO + WLog_WARN(TAG, "not implemented"); + return TRUE; +} + +BOOL wlf_register_pointer(rdpGraphics* graphics) +{ + rdpPointer pointer = { 0 }; + + pointer.size = sizeof(wlfPointer); + pointer.New = wlf_Pointer_New; + pointer.Free = wlf_Pointer_Free; + pointer.Set = wlf_Pointer_Set; + pointer.SetNull = wlf_Pointer_SetNull; + pointer.SetDefault = wlf_Pointer_SetDefault; + pointer.SetPosition = wlf_Pointer_SetPosition; + graphics_register_pointer(graphics, &pointer); + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.h new file mode 100644 index 0000000000000000000000000000000000000000..8ae82e1d5778d57862db5f5698ded0cc642754ae --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlf_pointer.h @@ -0,0 +1,28 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Mouse Pointer + * + * Copyright 2019 Armin Novak + * Copyright 2019 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WAYLAND_POINTER_H +#define FREERDP_CLIENT_WAYLAND_POINTER_H + +#include + +BOOL wlf_register_pointer(rdpGraphics* graphics); + +#endif /* FREERDP_CLIENT_WAYLAND_POINTER_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.1.in b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.1.in new file mode 100644 index 0000000000000000000000000000000000000000..ee4041289d97d1e345ed32ee77e0cf304a0d74f8 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.1.in @@ -0,0 +1,38 @@ +.de URL +\\$2 \(laURL: \\$1 \(ra\\$3 +.. +.if \n[.g] .mso www.tmac +.TH @MANPAGE_NAME@ 1 2017-01-12 "@FREERDP_VERSION_FULL@" "FreeRDP" +.SH NAME +@MANPAGE_NAME@ \- FreeRDP wayland client +.SH SYNOPSIS +.B @MANPAGE_NAME@ +[file] +[\fIdefault_client_options\fP] +[\fB/v\fP:[:port]] +[\fB/version\fP] +[\fB/help\fP] +.SH DESCRIPTION +.B @MANPAGE_NAME@ +is a wayland Remote Desktop Protocol (RDP) client which is part of the FreeRDP project. A RDP server is built-in to many editions of Windows.. Alternative servers included ogon, gnome-remote-desktop, xrdp and VRDP (VirtualBox). +.SH OPTIONS +The wayland client also supports a lot of the \fIdefault client options\fP which are not described here. For details on those see the xfreerdp(1) man page. +.IP \fB/v:\fP\fI[:port]\fP +The server hostname or IP, and optionally the port, to connect to. +.IP /version +Print the version and exit. +.IP /help +Print the help and exit. +.SH EXIT STATUS +.TP +.B 0 +Successful program execution. +.TP +.B not 0 +On failure. + +.SH SEE ALSO +xfreerdp(1) wlog(7) + +.SH AUTHOR +FreeRDP diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.c b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..15d71f258816aae96b152aaee002517dacc08b43 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.c @@ -0,0 +1,815 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Client + * + * Copyright 2014 Manuel Bachmann + * Copyright 2016 Thincast Technologies GmbH + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include "wlfreerdp.h" +#include "wlf_input.h" +#include "wlf_cliprdr.h" +#include "wlf_disp.h" +#include "wlf_channels.h" +#include "wlf_pointer.h" + +#define TAG CLIENT_TAG("wayland") + +static BOOL wl_update_buffer(wlfContext* context_w, INT32 ix, INT32 iy, INT32 iw, INT32 ih) +{ + BOOL res = FALSE; + rdpGdi* gdi = NULL; + char* data = NULL; + UwacSize geometry = { 0 }; + size_t stride = 0; + UwacReturnCode rc = UWAC_ERROR_INTERNAL; + RECTANGLE_16 area = { 0 }; + + if (!context_w) + return FALSE; + + if ((ix < 0) || (iy < 0) || (iw < 0) || (ih < 0)) + return FALSE; + + EnterCriticalSection(&context_w->critical); + UINT32 x = WINPR_ASSERTING_INT_CAST(UINT16, ix); + UINT32 y = WINPR_ASSERTING_INT_CAST(UINT16, iy); + UINT32 w = WINPR_ASSERTING_INT_CAST(UINT16, iw); + UINT32 h = WINPR_ASSERTING_INT_CAST(UINT16, ih); + rc = UwacWindowGetDrawingBufferGeometry(context_w->window, &geometry, &stride); + data = UwacWindowGetDrawingBuffer(context_w->window); + + if (!data || (rc != UWAC_SUCCESS)) + goto fail; + + gdi = context_w->common.context.gdi; + + if (!gdi) + goto fail; + + /* Ignore output if the surface size does not match. */ + if (((INT64)x > geometry.width) || ((INT64)y > geometry.height)) + { + res = TRUE; + goto fail; + } + + area.left = WINPR_ASSERTING_INT_CAST(UINT16, x); + area.top = WINPR_ASSERTING_INT_CAST(UINT16, y); + area.right = WINPR_ASSERTING_INT_CAST(UINT16, x + w); + area.bottom = WINPR_ASSERTING_INT_CAST(UINT16, y + h); + + if (!wlf_copy_image( + gdi->primary_buffer, gdi->stride, WINPR_ASSERTING_INT_CAST(size_t, gdi->width), + WINPR_ASSERTING_INT_CAST(size_t, gdi->height), data, stride, + WINPR_ASSERTING_INT_CAST(size_t, geometry.width), + WINPR_ASSERTING_INT_CAST(size_t, geometry.height), &area, + freerdp_settings_get_bool(context_w->common.context.settings, FreeRDP_SmartSizing))) + goto fail; + + if (!wlf_scale_coordinates(&context_w->common.context, &x, &y, FALSE)) + goto fail; + + if (!wlf_scale_coordinates(&context_w->common.context, &w, &h, FALSE)) + goto fail; + + if (UwacWindowAddDamage(context_w->window, x, y, w, h) != UWAC_SUCCESS) + goto fail; + + if (UwacWindowSubmitBuffer(context_w->window, false) != UWAC_SUCCESS) + goto fail; + + res = TRUE; +fail: + LeaveCriticalSection(&context_w->critical); + return res; +} + +static BOOL wl_end_paint(rdpContext* context) +{ + rdpGdi* gdi = NULL; + wlfContext* context_w = NULL; + INT32 x = 0; + INT32 y = 0; + INT32 w = 0; + INT32 h = 0; + + if (!context || !context->gdi || !context->gdi->primary) + return FALSE; + + gdi = context->gdi; + + if (gdi->primary->hdc->hwnd->invalid->null) + return TRUE; + + x = gdi->primary->hdc->hwnd->invalid->x; + y = gdi->primary->hdc->hwnd->invalid->y; + w = gdi->primary->hdc->hwnd->invalid->w; + h = gdi->primary->hdc->hwnd->invalid->h; + context_w = (wlfContext*)context; + if (!wl_update_buffer(context_w, x, y, w, h)) + { + return FALSE; + } + + gdi->primary->hdc->hwnd->invalid->null = TRUE; + gdi->primary->hdc->hwnd->ninvalid = 0; + return TRUE; +} + +static BOOL wl_refresh_display(wlfContext* context) +{ + rdpGdi* gdi = NULL; + + if (!context || !context->common.context.gdi) + return FALSE; + + gdi = context->common.context.gdi; + return wl_update_buffer(context, 0, 0, gdi->width, gdi->height); +} + +static BOOL wl_resize_display(rdpContext* context) +{ + wlfContext* wlc = (wlfContext*)context; + rdpGdi* gdi = context->gdi; + rdpSettings* settings = context->settings; + + if (!gdi_resize(gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))) + return FALSE; + + return wl_refresh_display(wlc); +} + +static BOOL wl_pre_connect(freerdp* instance) +{ + rdpSettings* settings = NULL; + wlfContext* context = NULL; + const UwacOutput* output = NULL; + UwacSize resolution; + + if (!instance) + return FALSE; + + context = (wlfContext*)instance->context; + WINPR_ASSERT(context); + + settings = instance->context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_set_bool(settings, FreeRDP_CertificateCallbackPreferPEM, TRUE)) + return FALSE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_UNIX)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_NATIVE_WAYLAND)) + return FALSE; + PubSub_SubscribeChannelConnected(instance->context->pubSub, wlf_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(instance->context->pubSub, + wlf_OnChannelDisconnectedEventHandler); + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + // Use the resolution of the first display output + output = UwacDisplayGetOutput(context->display, 0); + + if ((output != NULL) && (UwacOutputGetResolution(output, &resolution) == UWAC_SUCCESS)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, + (UINT32)resolution.width)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, + (UINT32)resolution.height)) + return FALSE; + } + else + { + WLog_WARN(TAG, "Failed to get output resolution! Check your display settings"); + } + } + + return TRUE; +} + +static BOOL wl_post_connect(freerdp* instance) +{ + if (!instance || !instance->context) + return FALSE; + + wlfContext* context = (wlfContext*)instance->context; + WINPR_ASSERT(context); + + rdpSettings* settings = instance->context->settings; + WINPR_ASSERT(settings); + + const char* title = "FreeRDP"; + const char* wtitle = freerdp_settings_get_string(settings, FreeRDP_WindowTitle); + if (wtitle) + title = wtitle; + + const char* app_id = "wlfreerdp"; + const char* wmclass = freerdp_settings_get_string(settings, FreeRDP_WmClass); + if (wmclass) + app_id = wmclass; + + if (!gdi_init(instance, PIXEL_FORMAT_BGRA32)) + return FALSE; + + rdpGdi* gdi = instance->context->gdi; + + if (!gdi || (gdi->width < 0) || (gdi->height < 0)) + return FALSE; + + if (!wlf_register_pointer(instance->context->graphics)) + return FALSE; + + UINT32 w = (UINT32)gdi->width; + UINT32 h = (UINT32)gdi->height; + + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) && !context->fullscreen) + { + const UINT32 sw = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth); + if (sw > 0) + w = sw; + + const UINT32 sh = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight); + if (sh > 0) + h = sh; + } + + context->window = UwacCreateWindowShm(context->display, w, h, WL_SHM_FORMAT_XRGB8888); + + if (!context->window) + return FALSE; + + UwacWindowSetFullscreenState( + context->window, NULL, + freerdp_settings_get_bool(instance->context->settings, FreeRDP_Fullscreen)); + UwacWindowSetTitle(context->window, title); + UwacWindowSetAppId(context->window, app_id); + UwacWindowSetOpaqueRegion(context->window, 0, 0, w, h); + instance->context->update->EndPaint = wl_end_paint; + instance->context->update->DesktopResize = wl_resize_display; + const char* KeyboardRemappingList = + freerdp_settings_get_string(instance->context->settings, FreeRDP_KeyboardRemappingList); + + context->remap_table = freerdp_keyboard_remap_string_to_list(KeyboardRemappingList); + if (!context->remap_table) + return FALSE; + + if (!(context->disp = wlf_disp_new(context))) + return FALSE; + + context->clipboard = wlf_clipboard_new(context); + + if (!context->clipboard) + return FALSE; + + return wl_refresh_display(context); +} + +static void wl_post_disconnect(freerdp* instance) +{ + if (!instance) + return; + + if (!instance->context) + return; + + wlfContext* context = (wlfContext*)instance->context; + gdi_free(instance); + wlf_clipboard_free(context->clipboard); + wlf_disp_free(context->disp); + + if (context->window) + UwacDestroyWindow(&context->window); + freerdp_keyboard_remap_free(context->remap_table); + context->remap_table = NULL; +} + +static BOOL handle_uwac_events(freerdp* instance, UwacDisplay* display) +{ + UwacEvent event; + wlfContext* context = NULL; + + if (UwacDisplayDispatch(display, 1) < 0) + return FALSE; + + context = (wlfContext*)instance->context; + + while (UwacHasEvent(display)) + { + if (UwacNextEvent(display, &event) != UWAC_SUCCESS) + return FALSE; + + /*printf("UWAC event type %d\n", event.type);*/ + switch (event.type) + { + case UWAC_EVENT_NEW_SEAT: + context->seat = event.seat_new.seat; + break; + + case UWAC_EVENT_REMOVED_SEAT: + context->seat = NULL; + break; + + case UWAC_EVENT_FRAME_DONE: + { + EnterCriticalSection(&context->critical); + UwacReturnCode r = UwacWindowSubmitBuffer(context->window, false); + LeaveCriticalSection(&context->critical); + if (r != UWAC_SUCCESS) + return FALSE; + } + break; + + case UWAC_EVENT_POINTER_ENTER: + if (!wlf_handle_pointer_enter(instance, &event.mouse_enter_leave)) + return FALSE; + + break; + + case UWAC_EVENT_POINTER_MOTION: + if (!wlf_handle_pointer_motion(instance, &event.mouse_motion)) + return FALSE; + + break; + + case UWAC_EVENT_POINTER_BUTTONS: + if (!wlf_handle_pointer_buttons(instance, &event.mouse_button)) + return FALSE; + + break; + + case UWAC_EVENT_POINTER_AXIS: + if (!wlf_handle_pointer_axis(instance, &event.mouse_axis)) + return FALSE; + break; + + case UWAC_EVENT_POINTER_AXIS_DISCRETE: + if (!wlf_handle_pointer_axis_discrete(instance, &event.mouse_axis)) + return FALSE; + break; + + case UWAC_EVENT_POINTER_FRAME: + if (!wlf_handle_pointer_frame(instance, &event.mouse_frame)) + return FALSE; + break; + case UWAC_EVENT_POINTER_SOURCE: + if (!wlf_handle_pointer_source(instance, &event.mouse_source)) + return FALSE; + break; + + case UWAC_EVENT_KEY: + if (!wlf_handle_key(instance, &event.key)) + return FALSE; + + break; + + case UWAC_EVENT_TOUCH_UP: + if (!wlf_handle_touch_up(instance, &event.touchUp)) + return FALSE; + + break; + + case UWAC_EVENT_TOUCH_DOWN: + if (!wlf_handle_touch_down(instance, &event.touchDown)) + return FALSE; + + break; + + case UWAC_EVENT_TOUCH_MOTION: + if (!wlf_handle_touch_motion(instance, &event.touchMotion)) + return FALSE; + + break; + + case UWAC_EVENT_KEYBOARD_ENTER: + if (freerdp_settings_get_bool(instance->context->settings, FreeRDP_GrabKeyboard)) + UwacSeatInhibitShortcuts(event.keyboard_enter_leave.seat, true); + + if (!wlf_keyboard_enter(instance, &event.keyboard_enter_leave)) + return FALSE; + + break; + + case UWAC_EVENT_KEYBOARD_MODIFIERS: + if (!wlf_keyboard_modifiers(instance, &event.keyboard_modifiers)) + return FALSE; + + break; + + case UWAC_EVENT_CONFIGURE: + if (!wlf_disp_handle_configure(context->disp, event.configure.width, + event.configure.height)) + return FALSE; + + if (!wl_refresh_display(context)) + return FALSE; + + break; + + case UWAC_EVENT_CLIPBOARD_AVAILABLE: + case UWAC_EVENT_CLIPBOARD_OFFER: + case UWAC_EVENT_CLIPBOARD_SELECT: + if (!wlf_cliprdr_handle_event(context->clipboard, &event.clipboard)) + return FALSE; + + break; + + case UWAC_EVENT_CLOSE: + context->closed = TRUE; + + break; + + default: + break; + } + } + + return TRUE; +} + +static BOOL handle_window_events(freerdp* instance) +{ + if (!instance) + return FALSE; + + return TRUE; +} + +static int wlfreerdp_run(freerdp* instance) +{ + wlfContext* context = NULL; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD status = WAIT_ABANDONED; + HANDLE timer = NULL; + LARGE_INTEGER due = { 0 }; + + TimerEventArgs timerEvent; + EventArgsInit(&timerEvent, "xfreerdp"); + + if (!instance) + return -1; + + context = (wlfContext*)instance->context; + + if (!context) + return -1; + + if (!freerdp_connect(instance)) + { + WLog_Print(context->log, WLOG_ERROR, "Failed to connect"); + return -1; + } + + timer = CreateWaitableTimerA(NULL, FALSE, "mainloop-periodic-timer"); + + if (!timer) + { + WLog_ERR(TAG, "failed to create timer"); + goto disconnect; + } + + due.QuadPart = 0; + + if (!SetWaitableTimer(timer, &due, 20, NULL, NULL, FALSE)) + { + goto disconnect; + } + + while (!freerdp_shall_disconnect_context(instance->context)) + { + DWORD count = 0; + handles[count++] = timer; + handles[count++] = context->displayHandle; + count += freerdp_get_event_handles(instance->context, &handles[count], + ARRAYSIZE(handles) - count); + + if (count <= 2) + { + WLog_Print(context->log, WLOG_ERROR, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(count, handles, FALSE, INFINITE); + + if (WAIT_FAILED == status) + { + WLog_Print(context->log, WLOG_ERROR, "WaitForMultipleObjects failed"); + break; + } + + if (!handle_uwac_events(instance, context->display)) + { + WLog_Print(context->log, WLOG_ERROR, "error handling UWAC events"); + break; + } + + if (context->closed) + { + WLog_Print(context->log, WLOG_INFO, "Closed from Wayland"); + break; + } + + if (freerdp_check_event_handles(instance->context) != TRUE) + { + if (client_auto_reconnect_ex(instance, handle_window_events)) + continue; + else + { + /* + * Indicate an unsuccessful connection attempt if reconnect + * did not succeed and no other error was specified. + */ + if (freerdp_error_info(instance) == 0) + status = 42; + } + + if (freerdp_get_last_error(instance->context) == FREERDP_ERROR_SUCCESS) + WLog_Print(context->log, WLOG_ERROR, "Failed to check FreeRDP file descriptor"); + + break; + } + + if ((status != WAIT_TIMEOUT) && (status == WAIT_OBJECT_0)) + { + timerEvent.now = GetTickCount64(); + PubSub_OnTimer(context->common.context.pubSub, context, &timerEvent); + } + } + +disconnect: + if (timer) + (void)CloseHandle(timer); + freerdp_disconnect(instance); + return WINPR_ASSERTING_INT_CAST(int, status); +} + +static BOOL wlf_client_global_init(void) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + (void)setlocale(LC_ALL, ""); + + if (freerdp_handle_signals() != 0) + return FALSE; + + return TRUE; +} + +static void wlf_client_global_uninit(void) +{ +} + +static int wlf_logon_error_info(freerdp* instance, UINT32 data, UINT32 type) +{ + wlfContext* wlf = NULL; + const char* str_data = freerdp_get_logon_error_info_data(data); + const char* str_type = freerdp_get_logon_error_info_type(type); + + if (!instance || !instance->context) + return -1; + + wlf = (wlfContext*)instance->context; + WLog_Print(wlf->log, WLOG_INFO, "Logon Error Info %s [%s]", str_data, str_type); + return 1; +} + +static void wlf_client_free(freerdp* instance, rdpContext* context) +{ + wlfContext* wlf = (wlfContext*)instance->context; + + if (!context) + return; + + if (wlf->display) + UwacCloseDisplay(&wlf->display); + + if (wlf->displayHandle) + (void)CloseHandle(wlf->displayHandle); + ArrayList_Free(wlf->events); + DeleteCriticalSection(&wlf->critical); +} + +static void* uwac_event_clone(const void* val) +{ + UwacEvent* copy = NULL; + const UwacEvent* ev = (const UwacEvent*)val; + + copy = calloc(1, sizeof(UwacEvent)); + if (!copy) + return NULL; + *copy = *ev; + return copy; +} + +static BOOL wlf_client_new(freerdp* instance, rdpContext* context) +{ + wObject* obj = NULL; + UwacReturnCode status = UWAC_ERROR_INTERNAL; + wlfContext* wfl = (wlfContext*)context; + + if (!instance || !context) + return FALSE; + + instance->PreConnect = wl_pre_connect; + instance->PostConnect = wl_post_connect; + instance->PostDisconnect = wl_post_disconnect; + instance->LogonErrorInfo = wlf_logon_error_info; + wfl->log = WLog_Get(TAG); + wfl->display = UwacOpenDisplay(NULL, &status); + + if (!wfl->display || (status != UWAC_SUCCESS) || !wfl->log) + return FALSE; + + wfl->displayHandle = CreateFileDescriptorEvent(NULL, FALSE, FALSE, + UwacDisplayGetFd(wfl->display), WINPR_FD_READ); + + if (!wfl->displayHandle) + return FALSE; + + wfl->events = ArrayList_New(FALSE); + if (!wfl->events) + return FALSE; + + obj = ArrayList_Object(wfl->events); + obj->fnObjectNew = uwac_event_clone; + obj->fnObjectFree = free; + + InitializeCriticalSection(&wfl->critical); + + return TRUE; +} + +static int wfl_client_start(rdpContext* context) +{ + WINPR_UNUSED(context); + return 0; +} + +static int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + WINPR_ASSERT(pEntryPoints); + ZeroMemory(pEntryPoints, sizeof(RDP_CLIENT_ENTRY_POINTS)); + pEntryPoints->Version = RDP_CLIENT_INTERFACE_VERSION; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->GlobalInit = wlf_client_global_init; + pEntryPoints->GlobalUninit = wlf_client_global_uninit; + pEntryPoints->ContextSize = sizeof(wlfContext); + pEntryPoints->ClientNew = wlf_client_new; + pEntryPoints->ClientFree = wlf_client_free; + pEntryPoints->ClientStart = wfl_client_start; + pEntryPoints->ClientStop = freerdp_client_common_stop; + return 0; +} + +int main(int argc, char* argv[]) +{ + int rc = -1; + int status = 0; + RDP_CLIENT_ENTRY_POINTS clientEntryPoints; + rdpContext* context = NULL; + rdpSettings* settings = NULL; + wlfContext* wlc = NULL; + + freerdp_client_warn_deprecated(argc, argv); + + RdpClientEntry(&clientEntryPoints); + context = freerdp_client_context_new(&clientEntryPoints); + if (!context) + goto fail; + wlc = (wlfContext*)context; + settings = context->settings; + + status = freerdp_client_settings_parse_command_line(settings, argc, argv, FALSE); + if (status) + { + rc = freerdp_client_settings_command_line_status_print(settings, status, argc, argv); + + if (freerdp_settings_get_bool(settings, FreeRDP_ListMonitors)) + wlf_list_monitors(wlc); + + goto fail; + } + + if (freerdp_client_start(context) != 0) + goto fail; + + rc = wlfreerdp_run(context->instance); + + if (freerdp_client_stop(context) != 0) + rc = -1; + +fail: + freerdp_client_context_free(context); + return rc; +} + +BOOL wlf_copy_image(const void* src, size_t srcStride, size_t srcWidth, size_t srcHeight, void* dst, + size_t dstStride, size_t dstWidth, size_t dstHeight, const RECTANGLE_16* area, + BOOL scale) +{ + BOOL rc = FALSE; + + if (!src || !dst || !area) + return FALSE; + + if (scale) + { + WINPR_ASSERT(dstStride <= UINT32_MAX); + WINPR_ASSERT(dstWidth <= UINT32_MAX); + WINPR_ASSERT(dstHeight <= UINT32_MAX); + WINPR_ASSERT(srcStride <= UINT32_MAX); + WINPR_ASSERT(srcWidth <= UINT32_MAX); + WINPR_ASSERT(srcHeight <= UINT32_MAX); + return freerdp_image_scale(dst, PIXEL_FORMAT_BGRA32, (UINT32)dstStride, 0, 0, + (UINT32)dstWidth, (UINT32)dstHeight, src, PIXEL_FORMAT_BGRA32, + (UINT32)srcStride, 0, 0, (UINT32)srcWidth, (UINT32)srcHeight); + } + else + { + const size_t baseSrcOffset = 1ULL * area->top * srcStride + 4ULL * area->left; + const size_t baseDstOffset = 1ULL * area->top * dstStride + 4ULL * area->left; + const size_t width = MIN((size_t)area->right - area->left, dstWidth - area->left); + const size_t height = MIN((size_t)area->bottom - area->top, dstHeight - area->top); + const BYTE* psrc = (const BYTE*)src; + BYTE* pdst = (BYTE*)dst; + + for (size_t i = 0; i < height; i++) + { + const size_t srcOffset = i * srcStride + baseSrcOffset; + const size_t dstOffset = i * dstStride + baseDstOffset; + memcpy(&pdst[dstOffset], &psrc[srcOffset], width * 4); + } + + rc = TRUE; + } + + return rc; +} + +BOOL wlf_scale_coordinates(rdpContext* context, UINT32* px, UINT32* py, BOOL fromLocalToRDP) +{ + wlfContext* wlf = (wlfContext*)context; + UwacSize geometry = { 0 }; + + if (!context || !px || !py || !context->gdi) + return FALSE; + + if (!freerdp_settings_get_bool(context->settings, FreeRDP_SmartSizing)) + return TRUE; + + rdpGdi* gdi = context->gdi; + + if (UwacWindowGetDrawingBufferGeometry(wlf->window, &geometry, NULL) != UWAC_SUCCESS) + return FALSE; + + const double sx = 1.0 * geometry.width / (double)gdi->width; + const double sy = 1.0 * geometry.height / (double)gdi->height; + + if (!fromLocalToRDP) + { + *px *= (UINT32)lround(sx); + *py *= (UINT32)lround(sy); + } + else + { + *px /= (UINT32)lround(sx); + *py /= (UINT32)lround(sy); + } + + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.h b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..b4724341853d2a3aa8f98d8ee6e34991e4dbdece --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Wayland/wlfreerdp.h @@ -0,0 +1,61 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Wayland Client + * + * Copyright 2014 Manuel Bachmann + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WAYLAND_FREERDP_H +#define FREERDP_CLIENT_WAYLAND_FREERDP_H + +#include +#include +#include +#include +#include +#include +#include + +typedef struct wlf_clipboard wfClipboard; +typedef struct s_wlfDispContext wlfDispContext; + +typedef struct +{ + rdpClientContext common; + + UwacDisplay* display; + HANDLE displayHandle; + UwacWindow* window; + UwacSeat* seat; + + BOOL fullscreen; + BOOL closed; + BOOL focusing; + + /* Channels */ + wfClipboard* clipboard; + wlfDispContext* disp; + wLog* log; + CRITICAL_SECTION critical; + wArrayList* events; + FREERDP_REMAP_TABLE* remap_table; +} wlfContext; + +BOOL wlf_scale_coordinates(rdpContext* context, UINT32* px, UINT32* py, BOOL fromLocalToRDP); +BOOL wlf_copy_image(const void* src, size_t srcStride, size_t srcWidth, size_t srcHeight, void* dst, + size_t dstStride, size_t dstWidth, size_t dstHeight, const RECTANGLE_16* area, + BOOL scale); + +#endif /* FREERDP_CLIENT_WAYLAND_FREERDP_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/Windows/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..37f0bab3420a3cdae351353e08eeba505d2c8b75 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/CMakeLists.txt @@ -0,0 +1,87 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Windows cmake build script +# +# Copyright 2012 Marc-Andre Moreau +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set(MODULE_NAME "wfreerdp-client") +set(MODULE_PREFIX "FREERDP_CLIENT_WINDOWS_CONTROL") + +set(${MODULE_PREFIX}_SRCS + wf_gdi.c + wf_gdi.h + wf_event.c + wf_event.h + wf_channels.c + wf_channels.h + wf_graphics.c + wf_graphics.h + wf_cliprdr.c + wf_cliprdr.h + wf_rail.c + wf_rail.h + wf_client.c + wf_client.h + wf_floatbar.c + wf_floatbar.h + wf_defaults.h + wf_defaults.c + resource/wfreerdp.rc + resource/resource.h +) + +option(WITH_WINDOWS_CERT_STORE + "Build ${MODULE_NAME} with additional certificate validation against windows certificate store" ON +) +if(WITH_WINDOWS_CERT_STORE) + add_compile_definitions("WITH_WINDOWS_CERT_STORE") +endif() + +option(WITH_WIN_CONSOLE "Build ${MODULE_NAME} with console support" OFF) +if(WITH_WIN_CONSOLE) + add_compile_definitions("WITH_WIN_CONSOLE") + set(WIN32_GUI_FLAG "TRUE") +else() + set(WIN32_GUI_FLAG "WIN32") +endif() + +option(WITH_PROGRESS_BAR "Build ${MODULE_NAME} with connect progress bar (Windows 7+ or 2008 R2+)" ON) +if(WITH_PROGRESS_BAR) + add_compile_definitions("WITH_PROGRESS_BAR") +endif() + +if(CLIENT_INTERFACE_SHARED) + addtargetwithresourcefile(${MODULE_NAME} "SHARED" "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) +else() + addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" ${MODULE_PREFIX}_SRCS) +endif() +target_include_directories(${MODULE_NAME} INTERFACE $) + +list(APPEND PUB_LIBS freerdp-client) +list(APPEND PUB_LIBS winpr freerdp) + +list(APPEND PRIV_LIBS msimg32.lib credui.lib) + +if(MINGW) + list(APPEND PRIV_LIBS ntdll.lib) # only required with MINGW +endif() +target_link_libraries(${MODULE_NAME} PUBLIC ${PUB_LIBS}) +target_link_libraries(${MODULE_NAME} PRIVATE ${PRIV_LIBS}) + +if(WITH_CLIENT_INTERFACE) + install(TARGETS ${MODULE_NAME} DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) +endif() +add_subdirectory(cli) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Client/Windows") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/ModuleOptions.cmake b/local-test-freerdp-full-01/afc-freerdp/client/Windows/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ec9bf511b93c4a3136021c923cfcadbd3aa4fff4 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_CLIENT_NAME "wfreerdp") +set(FREERDP_CLIENT_PLATFORM "Windows") +set(FREERDP_CLIENT_VENDOR "FreeRDP") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..69c99efefa950b45bdaf11089a392eaabb9e57a9 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.c @@ -0,0 +1,86 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include "wf_channels.h" + +#include "wf_rail.h" +#include "wf_cliprdr.h" + +#include +#include + +#include +#define TAG CLIENT_TAG("windows") + +void wf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e) +{ + wfContext* wfc = (wfContext*)context; + rdpSettings* settings; + + WINPR_ASSERT(wfc); + WINPR_ASSERT(e); + + settings = wfc->common.context.settings; + WINPR_ASSERT(settings); + + if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + wf_rail_init(wfc, (RailClientContext*)e->pInterface); + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + wf_cliprdr_init(wfc, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + wfc->disp = (DispClientContext*)e->pInterface; + } + else + freerdp_client_OnChannelConnectedEventHandler(context, e); +} + +void wf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e) +{ + wfContext* wfc = (wfContext*)context; + rdpSettings* settings; + + WINPR_ASSERT(wfc); + WINPR_ASSERT(e); + + settings = wfc->common.context.settings; + WINPR_ASSERT(settings); + + if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + wf_rail_uninit(wfc, (RailClientContext*)e->pInterface); + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + wf_cliprdr_uninit(wfc, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + wfc->disp = NULL; + } + else + freerdp_client_OnChannelDisconnectedEventHandler(context, e); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.h new file mode 100644 index 0000000000000000000000000000000000000000..8676310625c359e3ced8e9a84519e0d4ff1bc9d5 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_channels.h @@ -0,0 +1,36 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_CHANNELS_H +#define FREERDP_CLIENT_WIN_CHANNELS_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "wf_client.h" + +void wf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e); +void wf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e); + +#endif /* FREERDP_CLIENT_WIN_CHANNELS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.c new file mode 100644 index 0000000000000000000000000000000000000000..fc6d68f7a8012af31f0f14a9774439d68aab4601 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.c @@ -0,0 +1,1490 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Client + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WITH_PROGRESS_BAR +#include +#endif + +#ifdef WITH_WINDOWS_CERT_STORE +#include +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "wf_gdi.h" +#include "wf_rail.h" +#include "wf_channels.h" +#include "wf_graphics.h" + +#include "resource/resource.h" + +#define TAG CLIENT_TAG("windows") + +#define WM_FREERDP_SHOWWINDOW (WM_USER + 100) + +static BOOL wf_has_console(void) +{ +#ifdef WITH_WIN_CONSOLE + int file = _fileno(stdin); + int tty = _isatty(file); +#else + int file = -1; + int tty = 0; +#endif + + WLog_INFO(TAG, "Detected stdin=%d -> %s mode", file, tty ? "console" : "gui"); + return tty; +} + +static BOOL wf_end_paint(rdpContext* context) +{ + rdpGdi* gdi; + int ninvalid; + RECT updateRect; + HGDI_RGN cinvalid; + REGION16 invalidRegion; + RECTANGLE_16 invalidRect; + const RECTANGLE_16* extents; + wfContext* wfc = (wfContext*)context; + gdi = context->gdi; + ninvalid = gdi->primary->hdc->hwnd->ninvalid; + cinvalid = gdi->primary->hdc->hwnd->cinvalid; + + if (ninvalid < 1) + return TRUE; + + region16_init(&invalidRegion); + + for (int i = 0; i < ninvalid; i++) + { + invalidRect.left = cinvalid[i].x; + invalidRect.top = cinvalid[i].y; + invalidRect.right = cinvalid[i].x + cinvalid[i].w; + invalidRect.bottom = cinvalid[i].y + cinvalid[i].h; + region16_union_rect(&invalidRegion, &invalidRegion, &invalidRect); + } + + if (!region16_is_empty(&invalidRegion)) + { + extents = region16_extents(&invalidRegion); + updateRect.left = extents->left; + updateRect.top = extents->top; + updateRect.right = extents->right; + updateRect.bottom = extents->bottom; + + wf_scale_rect(wfc, &updateRect); + + InvalidateRect(wfc->hwnd, &updateRect, FALSE); + + if (wfc->rail) + wf_rail_invalidate_region(wfc, &invalidRegion); + } + + region16_uninit(&invalidRegion); + + if (!wfc->is_shown) + { + wfc->is_shown = TRUE; + +#ifdef WITH_PROGRESS_BAR + if (wfc->taskBarList) + { + wfc->taskBarList->lpVtbl->SetProgressState(wfc->taskBarList, wfc->hwnd, + TBPF_NOPROGRESS); + } +#endif + + PostMessage(wfc->hwnd, WM_FREERDP_SHOWWINDOW, 0, 0); + WLog_INFO(TAG, "Window is shown!"); + } + return TRUE; +} + +static BOOL wf_begin_paint(rdpContext* context) +{ + HGDI_DC hdc; + + if (!context || !context->gdi || !context->gdi->primary || !context->gdi->primary->hdc) + return FALSE; + + hdc = context->gdi->primary->hdc; + + if (!hdc || !hdc->hwnd || !hdc->hwnd->invalid) + return FALSE; + + hdc->hwnd->invalid->null = TRUE; + hdc->hwnd->ninvalid = 0; + return TRUE; +} + +static BOOL wf_desktop_resize(rdpContext* context) +{ + BOOL same; + RECT rect; + rdpSettings* settings; + wfContext* wfc = (wfContext*)context; + + if (!context || !context->settings) + return FALSE; + + settings = context->settings; + + if (wfc->primary) + { + same = (wfc->primary == wfc->drawing) ? TRUE : FALSE; + wf_image_free(wfc->primary); + wfc->primary = + wf_image_new(wfc, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + context->gdi->dstFormat, NULL); + } + + if (!gdi_resize_ex(context->gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), 0, + context->gdi->dstFormat, wfc->primary->pdata, NULL)) + return FALSE; + + if (same) + wfc->drawing = wfc->primary; + + if (wfc->fullscreen != TRUE) + { + if (wfc->hwnd && !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + SetWindowPos(wfc->hwnd, HWND_TOP, -1, -1, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) + wfc->diff.x, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) + wfc->diff.y, + SWP_NOMOVE); + } + else + { + wf_update_offset(wfc); + GetWindowRect(wfc->hwnd, &rect); + InvalidateRect(wfc->hwnd, &rect, TRUE); + } + + return TRUE; +} + +static BOOL wf_pre_connect(freerdp* instance) +{ + UINT32 rc; + wfContext* wfc; + UINT32 desktopWidth; + UINT32 desktopHeight; + rdpContext* context; + rdpSettings* settings; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + context = instance->context; + wfc = (wfContext*)instance->context; + settings = context->settings; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_WINDOWS)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_WINDOWS_NT)) + return FALSE; + wfc->fullscreen = freerdp_settings_get_bool(settings, FreeRDP_Fullscreen); + wfc->fullscreen_toggle = freerdp_settings_get_bool(settings, FreeRDP_ToggleFullscreen); + desktopWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + desktopHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (wfc->percentscreen > 0) + { + desktopWidth = (GetSystemMetrics(SM_CXSCREEN) * wfc->percentscreen) / 100; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, desktopWidth)) + return FALSE; + desktopHeight = (GetSystemMetrics(SM_CYSCREEN) * wfc->percentscreen) / 100; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, desktopHeight)) + return FALSE; + } + + if (wfc->fullscreen) + { + if (freerdp_settings_get_bool(settings, FreeRDP_UseMultimon)) + { + desktopWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN); + desktopHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN); + } + else + { + desktopWidth = GetSystemMetrics(SM_CXSCREEN); + desktopHeight = GetSystemMetrics(SM_CYSCREEN); + } + } + + /* FIXME: desktopWidth has a limitation that it should be divisible by 4, + * otherwise the screen will crash when connecting to an XP desktop.*/ + desktopWidth = (desktopWidth + 3) & (~3); + + if (desktopWidth != freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, desktopWidth)) + return FALSE; + } + + if (desktopHeight != freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, desktopHeight)) + return FALSE; + } + + rc = freerdp_keyboard_init(freerdp_settings_get_uint32(settings, FreeRDP_KeyboardLayout)); + if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardLayout, rc)) + return FALSE; + PubSub_SubscribeChannelConnected(instance->context->pubSub, wf_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(instance->context->pubSub, + wf_OnChannelDisconnectedEventHandler); + return TRUE; +} + +static void wf_append_item_to_system_menu(HMENU hMenu, UINT fMask, UINT wID, const wchar_t* text, + wfContext* wfc) +{ + MENUITEMINFO item_info = { 0 }; + item_info.fMask = fMask; + item_info.cbSize = sizeof(MENUITEMINFO); + item_info.wID = wID; + item_info.fType = MFT_STRING; + item_info.dwTypeData = _wcsdup(text); + item_info.cch = (UINT)_wcslen(text); + if (wfc) + item_info.dwItemData = (ULONG_PTR)wfc; + InsertMenuItem(hMenu, wfc->systemMenuInsertPosition++, TRUE, &item_info); +} + +static void wf_add_system_menu(wfContext* wfc) +{ + HMENU hMenu; + + if (wfc->fullscreen && !wfc->fullscreen_toggle) + { + return; + } + + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_DynamicResolutionUpdate)) + { + return; + } + + hMenu = GetSystemMenu(wfc->hwnd, FALSE); + + wf_append_item_to_system_menu(hMenu, + MIIM_CHECKMARKS | MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_DATA, + SYSCOMMAND_ID_SMARTSIZING, L"Smart sizing", wfc); + + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_SmartSizing)) + { + CheckMenuItem(hMenu, SYSCOMMAND_ID_SMARTSIZING, MF_CHECKED); + } + + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_RemoteAssistanceMode)) + wf_append_item_to_system_menu(hMenu, MIIM_FTYPE | MIIM_ID | MIIM_STRING, + SYSCOMMAND_ID_REQUEST_CONTROL, L"Request control", wfc); +} + +static WCHAR* wf_window_get_title(rdpSettings* settings) +{ + BOOL port; + WCHAR* windowTitle = NULL; + size_t size; + WCHAR prefix[] = L"FreeRDP:"; + + if (!settings) + return NULL; + + const char* name = freerdp_settings_get_string(settings, FreeRDP_ServerHostname); + + if (freerdp_settings_get_string(settings, FreeRDP_WindowTitle)) + return ConvertUtf8ToWCharAlloc(freerdp_settings_get_string(settings, FreeRDP_WindowTitle), + NULL); + + port = (freerdp_settings_get_uint32(settings, FreeRDP_ServerPort) != 3389); + size = strlen(name) + 16 + wcslen(prefix); + windowTitle = calloc(size, sizeof(WCHAR)); + + if (!windowTitle) + return NULL; + + if (!port) + _snwprintf_s(windowTitle, size, _TRUNCATE, L"%s %S", prefix, name); + else + _snwprintf_s(windowTitle, size, _TRUNCATE, L"%s %S:%u", prefix, name, + freerdp_settings_get_uint32(settings, FreeRDP_ServerPort)); + + return windowTitle; +} + +static BOOL wf_post_connect(freerdp* instance) +{ + rdpGdi* gdi; + DWORD dwStyle; + rdpCache* cache; + wfContext* wfc; + rdpContext* context; + rdpSettings* settings; + EmbedWindowEventArgs e; + const UINT32 format = PIXEL_FORMAT_BGRX32; + + WINPR_ASSERT(instance); + + context = instance->context; + WINPR_ASSERT(context); + + settings = context->settings; + WINPR_ASSERT(settings); + + wfc = (wfContext*)instance->context; + WINPR_ASSERT(wfc); + + wfc->primary = + wf_image_new(wfc, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), format, NULL); + + if (!gdi_init_ex(instance, format, 0, wfc->primary->pdata, NULL)) + return FALSE; + + cache = instance->context->cache; + WINPR_ASSERT(cache); + + gdi = instance->context->gdi; + + if (!freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)) + { + wf_gdi_register_update_callbacks(context->update); + } + + wfc->window_title = wf_window_get_title(settings); + + if (!wfc->window_title) + return FALSE; + + if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_Decorations, FALSE)) + return FALSE; + } + + if (wfc->fullscreen) + dwStyle = WS_POPUP; + else if (!freerdp_settings_get_bool(settings, FreeRDP_Decorations)) + dwStyle = WS_CHILD | WS_BORDER; + else + dwStyle = + WS_CAPTION | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX | WS_MAXIMIZEBOX; + + if (!wfc->hwnd) + { + wfc->hwnd = CreateWindowEx(0, wfc->wndClassName, wfc->window_title, dwStyle, 0, 0, 0, 0, + wfc->hWndParent, NULL, wfc->hInstance, NULL); + SetWindowLongPtr(wfc->hwnd, GWLP_USERDATA, (LONG_PTR)wfc); + } + + wf_resize_window(wfc); + wf_add_system_menu(wfc); + BitBlt(wfc->primary->hdc, 0, 0, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), NULL, 0, 0, BLACKNESS); + wfc->drawing = wfc->primary; + EventArgsInit(&e, "wfreerdp"); + e.embed = FALSE; + e.handle = (void*)wfc->hwnd; + PubSub_OnEmbedWindow(context->pubSub, context, &e); +#ifdef WITH_PROGRESS_BAR + if (wfc->taskBarList) + { + ShowWindow(wfc->hwnd, SW_SHOWMINIMIZED); + wfc->taskBarList->lpVtbl->SetProgressState(wfc->taskBarList, wfc->hwnd, TBPF_INDETERMINATE); + } +#endif + UpdateWindow(wfc->hwnd); + context->update->BeginPaint = wf_begin_paint; + context->update->DesktopResize = wf_desktop_resize; + context->update->EndPaint = wf_end_paint; + wf_register_pointer(context->graphics); + + wfc->floatbar = wf_floatbar_new(wfc, wfc->hInstance, + freerdp_settings_get_uint32(settings, FreeRDP_Floatbar)); + return TRUE; +} + +static void wf_post_disconnect(freerdp* instance) +{ + wfContext* wfc; + + if (!instance || !instance->context) + return; + + wfc = (wfContext*)instance->context; + free(wfc->window_title); +} + +static CREDUI_INFOW wfUiInfo = { sizeof(CREDUI_INFOW), NULL, L"Enter your credentials", + L"Remote Desktop Security", NULL }; + +static BOOL wf_authenticate_ex(freerdp* instance, char** username, char** password, char** domain, + rdp_auth_reason reason) +{ + wfContext* wfc; + BOOL fSave; + DWORD status; + DWORD dwFlags; + WCHAR UserNameW[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 }; + WCHAR UserW[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 }; + WCHAR DomainW[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = { 0 }; + WCHAR PasswordW[CREDUI_MAX_PASSWORD_LENGTH + 1] = { 0 }; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + wfc = (wfContext*)instance->context; + WINPR_ASSERT(wfc); + + WINPR_ASSERT(username); + WINPR_ASSERT(domain); + WINPR_ASSERT(password); + + const WCHAR auth[] = L"Target credentials requested"; + const WCHAR authPin[] = L"PIN requested"; + const WCHAR gwAuth[] = L"Gateway credentials requested"; + const WCHAR* titleW = auth; + + fSave = FALSE; + dwFlags = CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_EXCLUDE_CERTIFICATES | + CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS; + switch (reason) + { + case AUTH_NLA: + break; + case AUTH_TLS: + case AUTH_RDP: + if ((*username) && (*password)) + return TRUE; + break; + case AUTH_SMARTCARD_PIN: + dwFlags &= ~CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS; + dwFlags |= CREDUI_FLAGS_PASSWORD_ONLY_OK | CREDUI_FLAGS_KEEP_USERNAME; + titleW = authPin; + if (*password) + return TRUE; + if (!(*username)) + *username = _strdup("PIN"); + break; + case GW_AUTH_HTTP: + case GW_AUTH_RDG: + case GW_AUTH_RPC: + titleW = gwAuth; + break; + default: + return FALSE; + } + + if (*username) + { + (void)ConvertUtf8ToWChar(*username, UserNameW, ARRAYSIZE(UserNameW)); + (void)ConvertUtf8ToWChar(*username, UserW, ARRAYSIZE(UserW)); + } + + if (*password) + (void)ConvertUtf8ToWChar(*password, PasswordW, ARRAYSIZE(PasswordW)); + + if (*domain) + (void)ConvertUtf8ToWChar(*domain, DomainW, ARRAYSIZE(DomainW)); + + if (_wcsnlen(PasswordW, ARRAYSIZE(PasswordW)) == 0) + { + if (!wfc->isConsole && + freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_CredentialsFromStdin)) + WLog_ERR(TAG, "Flag for stdin read present but stdin is redirected; using GUI"); + if (wfc->isConsole && + freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_CredentialsFromStdin)) + status = CredUICmdLinePromptForCredentialsW(titleW, NULL, 0, UserNameW, + ARRAYSIZE(UserNameW), PasswordW, + ARRAYSIZE(PasswordW), &fSave, dwFlags); + else + status = CredUIPromptForCredentialsW(&wfUiInfo, titleW, NULL, 0, UserNameW, + ARRAYSIZE(UserNameW), PasswordW, + ARRAYSIZE(PasswordW), &fSave, dwFlags); + if (status != NO_ERROR) + { + WLog_ERR(TAG, "CredUIPromptForCredentials unexpected status: 0x%08lX", status); + return FALSE; + } + + if ((dwFlags & CREDUI_FLAGS_KEEP_USERNAME) == 0) + { + status = CredUIParseUserNameW(UserNameW, UserW, ARRAYSIZE(UserW), DomainW, + ARRAYSIZE(DomainW)); + if (status != NO_ERROR) + { + CHAR User[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 }; + CHAR UserName[CREDUI_MAX_USERNAME_LENGTH + 1] = { 0 }; + CHAR Domain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = { 0 }; + + (void)ConvertWCharNToUtf8(UserNameW, ARRAYSIZE(UserNameW), UserName, + ARRAYSIZE(UserName)); + (void)ConvertWCharNToUtf8(UserW, ARRAYSIZE(UserW), User, ARRAYSIZE(User)); + (void)ConvertWCharNToUtf8(DomainW, ARRAYSIZE(DomainW), Domain, ARRAYSIZE(Domain)); + WLog_ERR(TAG, "Failed to parse UserName: %s into User: %s Domain: %s", UserName, + User, Domain); + return FALSE; + } + } + } + + *username = ConvertWCharNToUtf8Alloc(UserW, ARRAYSIZE(UserW), NULL); + if (!(*username)) + { + WLog_ERR(TAG, "ConvertWCharNToUtf8Alloc failed", status); + return FALSE; + } + + if (_wcsnlen(DomainW, ARRAYSIZE(DomainW)) > 0) + *domain = ConvertWCharNToUtf8Alloc(DomainW, ARRAYSIZE(DomainW), NULL); + else + *domain = _strdup("\0"); + + if (!(*domain)) + { + free(*username); + WLog_ERR(TAG, "strdup failed", status); + return FALSE; + } + + *password = ConvertWCharNToUtf8Alloc(PasswordW, ARRAYSIZE(PasswordW), NULL); + if (!(*password)) + { + free(*username); + free(*domain); + return FALSE; + } + + return TRUE; +} + +static WCHAR* wf_format_text(const WCHAR* fmt, ...) +{ + int rc; + size_t size = 0; + WCHAR* buffer = NULL; + + do + { + WCHAR* tmp; + va_list ap; + va_start(ap, fmt); + rc = _vsnwprintf(buffer, size, fmt, ap); + va_end(ap); + if (rc <= 0) + goto fail; + + if ((size_t)rc < size) + return buffer; + + size = (size_t)rc + 1; + tmp = realloc(buffer, size * sizeof(WCHAR)); + if (!tmp) + goto fail; + + buffer = tmp; + } while (TRUE); + +fail: + free(buffer); + return NULL; +} + +#ifdef WITH_WINDOWS_CERT_STORE +/* https://stackoverflow.com/questions/1231178/load-an-pem-encoded-x-509-certificate-into-windows-cryptoapi/3803333#3803333 + */ +/* https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/Win7Samples/security/cryptoapi/peertrust/cpp/peertrust.cpp + */ +/* https://stackoverflow.com/questions/7340504/whats-the-correct-way-to-verify-an-ssl-certificate-in-win32 + */ + +static void wf_report_error(char* wszMessage, DWORD dwErrCode) +{ + LPSTR pwszMsgBuf = NULL; + + if (NULL != wszMessage && 0 != *wszMessage) + { + WLog_ERR(TAG, "%s", wszMessage); + } + + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, // Location of message + // definition ignored + dwErrCode, // Message identifier for + // the requested message + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Language identifier for + // the requested message + (LPSTR)&pwszMsgBuf, // Buffer that receives + // the formatted message + 0, // Size of output buffer + // not needed as allocate + // buffer flag is set + NULL // Array of insert values + ); + + if (NULL != pwszMsgBuf) + { + WLog_ERR(TAG, "Error: 0x%08x (%d) %s", dwErrCode, dwErrCode, pwszMsgBuf); + LocalFree(pwszMsgBuf); + } + else + { + WLog_ERR(TAG, "Error: 0x%08x (%d)", dwErrCode, dwErrCode); + } +} + +static DWORD wf_is_x509_certificate_trusted(const char* common_name, const char* subject, + const char* issuer, const char* fingerprint) +{ + HRESULT hr = CRYPT_E_NOT_FOUND; + + DWORD dwChainFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; + PCCERT_CONTEXT pCert = NULL; + HCERTCHAINENGINE hChainEngine = NULL; + PCCERT_CHAIN_CONTEXT pChainContext = NULL; + + CERT_ENHKEY_USAGE EnhkeyUsage = { 0 }; + CERT_USAGE_MATCH CertUsage = { 0 }; + CERT_CHAIN_PARA ChainPara = { 0 }; + CERT_CHAIN_POLICY_PARA ChainPolicy = { 0 }; + CERT_CHAIN_POLICY_STATUS PolicyStatus = { 0 }; + CERT_CHAIN_ENGINE_CONFIG EngineConfig = { 0 }; + + DWORD derPubKeyLen = strlen(fingerprint); + char* derPubKey = calloc(derPubKeyLen, sizeof(char)); + if (NULL == derPubKey) + { + WLog_ERR(TAG, "Could not allocate derPubKey"); + goto CleanUp; + } + + /* + * Convert from PEM format to DER format - removes header and footer and decodes from base64 + */ + if (!CryptStringToBinaryA(fingerprint, 0, CRYPT_STRING_BASE64HEADER, derPubKey, &derPubKeyLen, + NULL, NULL)) + { + WLog_ERR(TAG, "CryptStringToBinary failed. Err: %d", GetLastError()); + goto CleanUp; + } + + //--------------------------------------------------------- + // Initialize data structures for chain building. + + EnhkeyUsage.cUsageIdentifier = 0; + EnhkeyUsage.rgpszUsageIdentifier = NULL; + + CertUsage.dwType = USAGE_MATCH_TYPE_AND; + CertUsage.Usage = EnhkeyUsage; + + ChainPara.cbSize = sizeof(ChainPara); + ChainPara.RequestedUsage = CertUsage; + + ChainPolicy.cbSize = sizeof(ChainPolicy); + + PolicyStatus.cbSize = sizeof(PolicyStatus); + + EngineConfig.cbSize = sizeof(EngineConfig); + EngineConfig.dwUrlRetrievalTimeout = 0; + + pCert = CertCreateCertificateContext(X509_ASN_ENCODING, derPubKey, derPubKeyLen); + if (NULL == pCert) + { + WLog_ERR(TAG, "FAILED: Certificate could not be parsed."); + goto CleanUp; + } + + dwChainFlags |= CERT_CHAIN_ENABLE_PEER_TRUST; + + // When this flag is set, end entity certificates in the + // Trusted People store are trusted without doing any chain building + // This optimizes the chain building process. + + //--------------------------------------------------------- + // Create chain engine. + + if (!CertCreateCertificateChainEngine(&EngineConfig, &hChainEngine)) + { + hr = HRESULT_FROM_WIN32(GetLastError()); + goto CleanUp; + } + + //------------------------------------------------------------------- + // Build a chain using CertGetCertificateChain + + if (!CertGetCertificateChain(hChainEngine, // use the default chain engine + pCert, // pointer to the end certificate + NULL, // use the default time + NULL, // search no additional stores + &ChainPara, // use AND logic and enhanced key usage + // as indicated in the ChainPara + // data structure + dwChainFlags, + NULL, // currently reserved + &pChainContext)) // return a pointer to the chain created + { + hr = HRESULT_FROM_WIN32(GetLastError()); + goto CleanUp; + } + + //--------------------------------------------------------------- + // Verify that the chain complies with policy + + if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_BASE, // use the base policy + pChainContext, // pointer to the chain + &ChainPolicy, + &PolicyStatus)) // return a pointer to the policy status + { + hr = HRESULT_FROM_WIN32(GetLastError()); + goto CleanUp; + } + + if (PolicyStatus.dwError != S_OK) + { + wf_report_error("CertVerifyCertificateChainPolicy: Chain Status", PolicyStatus.dwError); + hr = PolicyStatus.dwError; + // Instruction: If the PolicyStatus.dwError is CRYPT_E_NO_REVOCATION_CHECK or + // CRYPT_E_REVOCATION_OFFLINE, it indicates errors in obtaining + // revocation information. These can be ignored since the retrieval of + // revocation information depends on network availability + + if (PolicyStatus.dwError == CRYPT_E_NO_REVOCATION_CHECK || + PolicyStatus.dwError == CRYPT_E_REVOCATION_OFFLINE) + { + hr = S_OK; + } + + goto CleanUp; + } + + WLog_INFO(TAG, "CertVerifyCertificateChainPolicy succeeded for %s (%s) issued by %s", + common_name, subject, issuer); + + hr = S_OK; +CleanUp: + + if (FAILED(hr)) + { + WLog_INFO(TAG, "CertVerifyCertificateChainPolicy failed for %s (%s) issued by %s", + common_name, subject, issuer); + wf_report_error(NULL, hr); + } + + free(derPubKey); + + if (NULL != pChainContext) + { + CertFreeCertificateChain(pChainContext); + } + + if (NULL != hChainEngine) + { + CertFreeCertificateChainEngine(hChainEngine); + } + + if (NULL != pCert) + { + CertFreeCertificateContext(pCert); + } + + return (DWORD)hr; +} +#endif + +static DWORD wf_cli_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port, + const char* common_name, const char* subject, + const char* issuer, const char* fingerprint, DWORD flags) +{ +#ifdef WITH_WINDOWS_CERT_STORE + if (flags & VERIFY_CERT_FLAG_FP_IS_PEM && !(flags & VERIFY_CERT_FLAG_MISMATCH)) + { + if (wf_is_x509_certificate_trusted(common_name, subject, issuer, fingerprint) == S_OK) + { + return 2; + } + } +#endif + + return client_cli_verify_certificate_ex(instance, host, port, common_name, subject, issuer, + fingerprint, flags); +} + +static DWORD wf_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port, + const char* common_name, const char* subject, + const char* issuer, const char* fingerprint, DWORD flags) +{ + WCHAR* buffer; + WCHAR* caption; + int what = IDCANCEL; + +#ifdef WITH_WINDOWS_CERT_STORE + if (flags & VERIFY_CERT_FLAG_FP_IS_PEM && !(flags & VERIFY_CERT_FLAG_MISMATCH)) + { + if (wf_is_x509_certificate_trusted(common_name, subject, issuer, fingerprint) == S_OK) + { + return 2; + } + } +#endif + + buffer = wf_format_text( + L"Certificate details:\n" + L"\tCommonName: %S\n" + L"\tSubject: %S\n" + L"\tIssuer: %S\n" + L"\tThumbprint: %S\n" + L"\tHostMismatch: %S\n" + L"\n" + L"The above X.509 certificate could not be verified, possibly because you do not have " + L"the CA certificate in your certificate store, or the certificate has expired. " + L"Please look at the OpenSSL documentation on how to add a private CA to the store.\n" + L"\n" + L"YES\tAccept permanently\n" + L"NO\tAccept for this session only\n" + L"CANCEL\tAbort connection\n", + common_name, subject, issuer, fingerprint, + flags & VERIFY_CERT_FLAG_MISMATCH ? "Yes" : "No"); + caption = wf_format_text(L"Verify certificate for %S:%hu", host, port); + + WINPR_UNUSED(instance); + + if (!buffer || !caption) + goto fail; + + what = MessageBoxW(NULL, buffer, caption, MB_YESNOCANCEL); +fail: + free(buffer); + free(caption); + + /* return 1 to accept and store a certificate, 2 to accept + * a certificate only for this session, 0 otherwise */ + switch (what) + { + case IDYES: + return 1; + case IDNO: + return 2; + default: + return 0; + } +} + +static DWORD wf_verify_changed_certificate_ex(freerdp* instance, const char* host, UINT16 port, + const char* common_name, const char* subject, + const char* issuer, const char* new_fingerprint, + const char* old_subject, const char* old_issuer, + const char* old_fingerprint, DWORD flags) +{ + WCHAR* buffer; + WCHAR* caption; + int what = IDCANCEL; + + buffer = wf_format_text( + L"New Certificate details:\n" + L"\tCommonName: %S\n" + L"\tSubject: %S\n" + L"\tIssuer: %S\n" + L"\tThumbprint: %S\n" + L"\tHostMismatch: %S\n" + L"\n" + L"Old Certificate details:\n" + L"\tSubject: %S\n" + L"\tIssuer: %S\n" + L"\tThumbprint: %S" + L"The above X.509 certificate could not be verified, possibly because you do not have " + L"the CA certificate in your certificate store, or the certificate has expired. " + L"Please look at the OpenSSL documentation on how to add a private CA to the store.\n" + L"\n" + L"YES\tAccept permanently\n" + L"NO\tAccept for this session only\n" + L"CANCEL\tAbort connection\n", + common_name, subject, issuer, new_fingerprint, + flags & VERIFY_CERT_FLAG_MISMATCH ? "Yes" : "No", old_subject, old_issuer, old_fingerprint); + caption = wf_format_text(L"Verify certificate change for %S:%hu", host, port); + + WINPR_UNUSED(instance); + if (!buffer || !caption) + goto fail; + + what = MessageBoxW(NULL, buffer, caption, MB_YESNOCANCEL); +fail: + free(buffer); + free(caption); + + /* return 1 to accept and store a certificate, 2 to accept + * a certificate only for this session, 0 otherwise */ + switch (what) + { + case IDYES: + return 1; + case IDNO: + return 2; + default: + return 0; + } +} + +static BOOL wf_present_gateway_message(freerdp* instance, UINT32 type, BOOL isDisplayMandatory, + BOOL isConsentMandatory, size_t length, const WCHAR* message) +{ + if (!isDisplayMandatory && !isConsentMandatory) + return TRUE; + + /* special handling for consent messages (show modal dialog) */ + if (type == GATEWAY_MESSAGE_CONSENT && isConsentMandatory) + { + int mbRes; + WCHAR* msg; + + msg = wf_format_text(L"%.*s\n\nI understand and agree to the terms of this policy", length, + message); + mbRes = MessageBoxW(NULL, msg, L"Consent Message", MB_YESNO); + free(msg); + + if (mbRes != IDYES) + return FALSE; + } + else + return client_cli_present_gateway_message(instance, type, isDisplayMandatory, + isConsentMandatory, length, message); + + return TRUE; +} + +static DWORD WINAPI wf_client_thread(LPVOID lpParam) +{ + MSG msg = { 0 }; + int width = 0; + int height = 0; + BOOL msg_ret = FALSE; + int quit_msg = 0; + DWORD error = 0; + + freerdp* instance = (freerdp*)lpParam; + WINPR_ASSERT(instance); + + if (!freerdp_connect(instance)) + goto end; + + rdpContext* context = instance->context; + WINPR_ASSERT(context); + + wfContext* wfc = (wfContext*)instance->context; + WINPR_ASSERT(wfc); + + rdpChannels* channels = context->channels; + WINPR_ASSERT(channels); + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + while (!freerdp_shall_disconnect_context(instance->context)) + { + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD nCount = 0; + + if (freerdp_focus_required(instance)) + { + wf_event_focus_in(wfc); + wf_event_focus_in(wfc); + } + + { + DWORD tmp = freerdp_get_event_handles(context, &handles[nCount], 64 - nCount); + + if (tmp == 0) + { + WLog_ERR(TAG, "freerdp_get_event_handles failed"); + break; + } + + nCount += tmp; + } + + DWORD status = MsgWaitForMultipleObjectsEx(nCount, handles, 5 * 1000, QS_ALLINPUT, + MWMO_ALERTABLE | MWMO_INPUTAVAILABLE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "wfreerdp_run: WaitForMultipleObjects failed: 0x%08lX", GetLastError()); + break; + } + + { + if (!freerdp_check_event_handles(context)) + { + if (client_auto_reconnect(instance)) + continue; + + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + break; + } + } + + if (freerdp_shall_disconnect_context(instance->context)) + break; + + quit_msg = FALSE; + + while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) + { + msg_ret = GetMessage(&msg, NULL, 0, 0); + + if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow)) + { + if ((msg.message == WM_SETFOCUS) && (msg.lParam == 1)) + { + PostMessage(wfc->hwnd, WM_SETFOCUS, 0, 0); + } + else if ((msg.message == WM_KILLFOCUS) && (msg.lParam == 1)) + { + PostMessage(wfc->hwnd, WM_KILLFOCUS, 0, 0); + } + } + + switch (msg.message) + { + case WM_SIZE: + { + width = LOWORD(msg.lParam); + height = HIWORD(msg.lParam); + SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, width, height, SWP_FRAMECHANGED); + break; + } + case WM_FREERDP_SHOWWINDOW: + { + ShowWindow(wfc->hwnd, SW_NORMAL); + break; + } + default: + break; + } + + if ((msg_ret == 0) || (msg_ret == -1)) + { + quit_msg = TRUE; + break; + } + + TranslateMessage(&msg); + DispatchMessage(&msg); + } + + if (quit_msg) + break; + } + + /* cleanup */ + freerdp_disconnect(instance); + +end: + error = freerdp_get_last_error(instance->context); + WLog_DBG(TAG, "Main thread exited with %" PRIu32, error); + ExitThread(error); + return error; +} + +static DWORD WINAPI wf_keyboard_thread(LPVOID lpParam) +{ + MSG msg; + BOOL status; + wfContext* wfc; + HHOOK hook_handle; + wfc = (wfContext*)lpParam; + WINPR_ASSERT(NULL != wfc); + hook_handle = SetWindowsHookEx(WH_KEYBOARD_LL, wf_ll_kbd_proc, wfc->hInstance, 0); + + if (hook_handle) + { + while ((status = GetMessage(&msg, NULL, 0, 0)) != 0) + { + if (status == -1) + { + WLog_ERR(TAG, "keyboard thread error getting message"); + break; + } + else + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + UnhookWindowsHookEx(hook_handle); + } + else + { + WLog_ERR(TAG, "failed to install keyboard hook"); + } + + WLog_DBG(TAG, "Keyboard thread exited."); + ExitThread(0); + return 0; +} + +int freerdp_client_set_window_size(wfContext* wfc, int width, int height) +{ + WLog_DBG(TAG, "freerdp_client_set_window_size %d, %d", width, height); + + if ((width != wfc->client_width) || (height != wfc->client_height)) + { + PostThreadMessage(wfc->mainThreadId, WM_SIZE, SIZE_RESTORED, + ((UINT)height << 16) | (UINT)width); + } + + return 0; +} + +void wf_size_scrollbars(wfContext* wfc, UINT32 client_width, UINT32 client_height) +{ + const rdpSettings* settings; + WINPR_ASSERT(wfc); + + settings = wfc->common.context.settings; + WINPR_ASSERT(settings); + + if (wfc->disablewindowtracking) + return; + + // prevent infinite message loop + wfc->disablewindowtracking = TRUE; + + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) + { + wfc->xCurrentScroll = 0; + wfc->yCurrentScroll = 0; + + if (wfc->xScrollVisible || wfc->yScrollVisible) + { + if (ShowScrollBar(wfc->hwnd, SB_BOTH, FALSE)) + { + wfc->xScrollVisible = FALSE; + wfc->yScrollVisible = FALSE; + } + } + } + else + { + SCROLLINFO si; + BOOL horiz = wfc->xScrollVisible; + BOOL vert = wfc->yScrollVisible; + + if (!horiz && client_width < freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)) + { + horiz = TRUE; + } + else if (horiz && + client_width >= + freerdp_settings_get_uint32( + settings, FreeRDP_DesktopWidth) /* - GetSystemMetrics(SM_CXVSCROLL)*/) + { + horiz = FALSE; + } + + if (!vert && client_height < freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)) + { + vert = TRUE; + } + else if (vert && + client_height >= + freerdp_settings_get_uint32( + settings, FreeRDP_DesktopHeight) /* - GetSystemMetrics(SM_CYHSCROLL)*/) + { + vert = FALSE; + } + + if (horiz == vert && (horiz != wfc->xScrollVisible && vert != wfc->yScrollVisible)) + { + if (ShowScrollBar(wfc->hwnd, SB_BOTH, horiz)) + { + wfc->xScrollVisible = horiz; + wfc->yScrollVisible = vert; + } + } + + if (horiz != wfc->xScrollVisible) + { + if (ShowScrollBar(wfc->hwnd, SB_HORZ, horiz)) + { + wfc->xScrollVisible = horiz; + } + } + + if (vert != wfc->yScrollVisible) + { + if (ShowScrollBar(wfc->hwnd, SB_VERT, vert)) + { + wfc->yScrollVisible = vert; + } + } + + if (horiz) + { + // The horizontal scrolling range is defined by + // (bitmap_width) - (client_width). The current horizontal + // scroll value remains within the horizontal scrolling range. + wfc->xMaxScroll = + MAX(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) - client_width, 0); + wfc->xCurrentScroll = MIN(wfc->xCurrentScroll, wfc->xMaxScroll); + si.cbSize = sizeof(si); + si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS; + si.nMin = wfc->xMinScroll; + si.nMax = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + si.nPage = client_width; + si.nPos = wfc->xCurrentScroll; + SetScrollInfo(wfc->hwnd, SB_HORZ, &si, TRUE); + } + + if (vert) + { + // The vertical scrolling range is defined by + // (bitmap_height) - (client_height). The current vertical + // scroll value remains within the vertical scrolling range. + wfc->yMaxScroll = MAX( + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) - client_height, 0); + wfc->yCurrentScroll = MIN(wfc->yCurrentScroll, wfc->yMaxScroll); + si.cbSize = sizeof(si); + si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS; + si.nMin = wfc->yMinScroll; + si.nMax = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + si.nPage = client_height; + si.nPos = wfc->yCurrentScroll; + SetScrollInfo(wfc->hwnd, SB_VERT, &si, TRUE); + } + } + + wfc->disablewindowtracking = FALSE; + wf_update_canvas_diff(wfc); +} + +static BOOL wfreerdp_client_global_init(void) +{ + WSADATA wsaData; + + WSAStartup(0x101, &wsaData); + + freerdp_register_addin_provider(freerdp_channels_load_static_addin_entry, 0); + + return TRUE; +} + +static void wfreerdp_client_global_uninit(void) +{ + WSACleanup(); +} + +static BOOL wfreerdp_client_new(freerdp* instance, rdpContext* context) +{ + wfContext* wfc = (wfContext*)context; + if (!wfc) + return FALSE; + + // AttachConsole and stdin do not work well. + // Use GUI input dialogs instead of command line ones. + wfc->isConsole = wf_has_console(); + + if (!(wfreerdp_client_global_init())) + return FALSE; + + WINPR_ASSERT(instance); + instance->PreConnect = wf_pre_connect; + instance->PostConnect = wf_post_connect; + instance->PostDisconnect = wf_post_disconnect; + instance->AuthenticateEx = wf_authenticate_ex; + +#ifdef WITH_WINDOWS_CERT_STORE + if (!freerdp_settings_set_bool(context->settings, FreeRDP_CertificateCallbackPreferPEM, TRUE)) + return FALSE; +#endif + + if (!wfc->isConsole) + { + instance->VerifyCertificateEx = wf_verify_certificate_ex; + instance->VerifyChangedCertificateEx = wf_verify_changed_certificate_ex; + instance->PresentGatewayMessage = wf_present_gateway_message; + } + +#ifdef WITH_PROGRESS_BAR + CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); + CoCreateInstance(&CLSID_TaskbarList, NULL, CLSCTX_ALL, &IID_ITaskbarList3, + (void**)&wfc->taskBarList); +#endif + + return TRUE; +} + +static void wfreerdp_client_free(freerdp* instance, rdpContext* context) +{ + WINPR_UNUSED(instance); + if (!context) + return; + +#ifdef WITH_PROGRESS_BAR + CoUninitialize(); +#endif +} + +static int wfreerdp_client_start(rdpContext* context) +{ + wfContext* wfc = (wfContext*)context; + + WINPR_ASSERT(context); + WINPR_ASSERT(context->settings); + + freerdp* instance = context->instance; + WINPR_ASSERT(instance); + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + HINSTANCE hInstance = GetModuleHandle(NULL); + HWND hWndParent = (HWND)freerdp_settings_get_uint64(settings, FreeRDP_ParentWindowId); + if (!freerdp_settings_set_bool(settings, FreeRDP_EmbeddedWindow, (hWndParent) ? TRUE : FALSE)) + return -1; + + wfc->hWndParent = hWndParent; + + if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow)) + { + typedef UINT(WINAPI * GetDpiForWindow_t)(HWND hwnd); + typedef BOOL(WINAPI * SetProcessDPIAware_t)(void); + + HMODULE module = GetModuleHandle(_T("User32")); + if (module) + { + GetDpiForWindow_t pGetDpiForWindow = + GetProcAddressAs(module, "GetDpiForWindow", GetDpiForWindow_t); + SetProcessDPIAware_t pSetProcessDPIAware = + GetProcAddressAs(module, "SetProcessDPIAware", SetProcessDPIAware_t); + if (pGetDpiForWindow && pSetProcessDPIAware) + { + const UINT dpiAwareness = pGetDpiForWindow(hWndParent); + if (dpiAwareness != USER_DEFAULT_SCREEN_DPI) + pSetProcessDPIAware(); + } + FreeLibrary(module); + } + } + + /* initial windows system item position where we will insert new menu item + * after default 5 items (restore, move, size, minimize, maximize) + * gets incremented each time wf_append_item_to_system_menu is called + * or maybe could use GetMenuItemCount() to get initial item count ? */ + wfc->systemMenuInsertPosition = 6; + + wfc->hInstance = hInstance; + wfc->cursor = LoadCursor(NULL, IDC_ARROW); + wfc->icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1)); + wfc->wndClassName = _tcsdup(_T("FreeRDP")); + wfc->wndClass.cbSize = sizeof(WNDCLASSEX); + wfc->wndClass.style = CS_HREDRAW | CS_VREDRAW; + wfc->wndClass.lpfnWndProc = wf_event_proc; + wfc->wndClass.cbClsExtra = 0; + wfc->wndClass.cbWndExtra = 0; + wfc->wndClass.hCursor = NULL; + wfc->wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); + wfc->wndClass.lpszMenuName = NULL; + wfc->wndClass.lpszClassName = wfc->wndClassName; + wfc->wndClass.hInstance = hInstance; + wfc->wndClass.hIcon = wfc->icon; + wfc->wndClass.hIconSm = wfc->icon; + RegisterClassEx(&(wfc->wndClass)); + wfc->keyboardThread = + CreateThread(NULL, 0, wf_keyboard_thread, (void*)wfc, 0, &wfc->keyboardThreadId); + + if (!wfc->keyboardThread) + return -1; + + wfc->common.thread = + CreateThread(NULL, 0, wf_client_thread, (void*)instance, 0, &wfc->mainThreadId); + + if (!wfc->common.thread) + return -1; + + return 0; +} + +static int wfreerdp_client_stop(rdpContext* context) +{ + int rc; + wfContext* wfc = (wfContext*)context; + + WINPR_ASSERT(wfc); + PostThreadMessage(wfc->mainThreadId, WM_QUIT, 0, 0); + rc = freerdp_client_common_stop(context); + wfc->mainThreadId = 0; + + if (wfc->keyboardThread) + { + PostThreadMessage(wfc->keyboardThreadId, WM_QUIT, 0, 0); + (void)WaitForSingleObject(wfc->keyboardThread, INFINITE); + (void)CloseHandle(wfc->keyboardThread); + wfc->keyboardThread = NULL; + wfc->keyboardThreadId = 0; + } + + return 0; +} + +int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + pEntryPoints->Version = 1; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->GlobalInit = wfreerdp_client_global_init; + pEntryPoints->GlobalUninit = wfreerdp_client_global_uninit; + pEntryPoints->ContextSize = sizeof(wfContext); + pEntryPoints->ClientNew = wfreerdp_client_new; + pEntryPoints->ClientFree = wfreerdp_client_free; + pEntryPoints->ClientStart = wfreerdp_client_start; + pEntryPoints->ClientStop = wfreerdp_client_stop; + return 0; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.h new file mode 100644 index 0000000000000000000000000000000000000000..85261765a91583485d7ff5aae1d88c3fe2d05e06 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_client.h @@ -0,0 +1,158 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Client + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_INTERFACE_H +#define FREERDP_CLIENT_WIN_INTERFACE_H + +#include + +#include + +#ifdef WITH_PROGRESS_BAR +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "wf_channels.h" +#include "wf_floatbar.h" +#include "wf_event.h" +#include "wf_cliprdr.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +// System menu constants +#define SYSCOMMAND_ID_SMARTSIZING 1000 +#define SYSCOMMAND_ID_REQUEST_CONTROL 1001 + + typedef struct + { + rdpBitmap _bitmap; + HDC hdc; + HBITMAP bitmap; + HBITMAP org_bitmap; + BYTE* pdata; + } wfBitmap; + + typedef struct + { + rdpPointer pointer; + HCURSOR cursor; + } wfPointer; + + struct wf_context + { + rdpClientContext common; + + int offset_x; + int offset_y; + int fullscreen_toggle; + int fullscreen; + int percentscreen; + WCHAR* window_title; + int client_x; + int client_y; + int client_width; + int client_height; + + HANDLE keyboardThread; + + HICON icon; + HWND hWndParent; + HINSTANCE hInstance; + WNDCLASSEX wndClass; + LPCTSTR wndClassName; + HCURSOR hDefaultCursor; + + UINT systemMenuInsertPosition; + + HWND hwnd; + BOOL is_shown; + ITaskbarList3* taskBarList; + POINT diff; + + wfBitmap* primary; + wfBitmap* drawing; + HCURSOR cursor; + HBRUSH brush; + HBRUSH org_brush; + RECT update_rect; + RECT scale_update_rect; + + DWORD mainThreadId; + DWORD keyboardThreadId; + + rdpFile* connectionRdpFile; + + BOOL disablewindowtracking; + + BOOL updating_scrollbars; + BOOL xScrollVisible; + int xMinScroll; + int xCurrentScroll; + int xMaxScroll; + + BOOL yScrollVisible; + int yMinScroll; + int yCurrentScroll; + int yMaxScroll; + + void* clipboard; + CliprdrClientContext* cliprdr; + + wfFloatBar* floatbar; + + RailClientContext* rail; + wHashTable* railWindows; + BOOL isConsole; + + DispClientContext* disp; + UINT64 lastSentDate; + BOOL wasMaximized; + }; + + /** + * Client Interface + */ + + FREERDP_API int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints); + FREERDP_API int freerdp_client_set_window_size(wfContext* wfc, int width, int height); + FREERDP_API void wf_size_scrollbars(wfContext* wfc, UINT32 client_width, UINT32 client_height); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_CLIENT_WIN_INTERFACE_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.c new file mode 100644 index 0000000000000000000000000000000000000000..beddce8f934d86b8980788a3741f68ff5bf101b7 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.c @@ -0,0 +1,2549 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Clipboard Redirection + * + * Copyright 2012 Jason Champion + * Copyright 2014 Marc-Andre Moreau + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define CINTERFACE +#define COBJMACROS + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include + +#include "wf_cliprdr.h" + +#define TAG CLIENT_TAG("windows") + +#ifdef WITH_DEBUG_CLIPRDR +#define DEBUG_CLIPRDR(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_CLIPRDR(...) \ + do \ + { \ + } while (0) +#endif + +typedef BOOL(WINAPI* fnAddClipboardFormatListener)(HWND hwnd); +typedef BOOL(WINAPI* fnRemoveClipboardFormatListener)(HWND hwnd); +typedef BOOL(WINAPI* fnGetUpdatedClipboardFormats)(PUINT lpuiFormats, UINT cFormats, + PUINT pcFormatsOut); + +typedef struct +{ + UINT32 remote_format_id; + UINT32 local_format_id; + WCHAR* name; +} formatMapping; + +typedef struct +{ + IEnumFORMATETC iEnumFORMATETC; + + LONG m_lRefCount; + LONG m_nIndex; + LONG m_nNumFormats; + FORMATETC* m_pFormatEtc; +} CliprdrEnumFORMATETC; + +typedef struct +{ + IStream iStream; + + LONG m_lRefCount; + ULONG m_lIndex; + ULARGE_INTEGER m_lSize; + ULARGE_INTEGER m_lOffset; + FILEDESCRIPTORW m_Dsc; + void* m_pData; +} CliprdrStream; + +typedef struct +{ + IDataObject iDataObject; + + LONG m_lRefCount; + FORMATETC* m_pFormatEtc; + STGMEDIUM* m_pStgMedium; + ULONG m_nNumFormats; + ULONG m_nStreams; + IStream** m_pStream; + void* m_pData; +} CliprdrDataObject; + +typedef struct +{ + wfContext* wfc; + rdpChannels* channels; + CliprdrClientContext* context; + + BOOL sync; + UINT32 capabilities; + + size_t map_size; + size_t map_capacity; + formatMapping* format_mappings; + + UINT32 requestedFormatId; + + HWND hwnd; + HANDLE hmem; + HANDLE thread; + HANDLE response_data_event; + + LPDATAOBJECT data_obj; + ULONG req_fsize; + char* req_fdata; + HANDLE req_fevent; + + size_t nFiles; + size_t file_array_size; + WCHAR** file_names; + FILEDESCRIPTORW** fileDescriptor; + + BOOL legacyApi; + HMODULE hUser32; + HWND hWndNextViewer; + fnAddClipboardFormatListener AddClipboardFormatListener; + fnRemoveClipboardFormatListener RemoveClipboardFormatListener; + fnGetUpdatedClipboardFormats GetUpdatedClipboardFormats; +} wfClipboard; + +#define WM_CLIPRDR_MESSAGE (WM_USER + 156) +#define OLE_SETCLIPBOARD 1 + +static BOOL wf_create_file_obj(wfClipboard* cliprdrrdr, IDataObject** ppDataObject); +static void wf_destroy_file_obj(IDataObject* instance); +static UINT32 get_remote_format_id(wfClipboard* clipboard, UINT32 local_format); +static UINT cliprdr_send_data_request(wfClipboard* clipboard, UINT32 format); +static UINT cliprdr_send_lock(wfClipboard* clipboard); +static UINT cliprdr_send_unlock(wfClipboard* clipboard); +static UINT cliprdr_send_request_filecontents(wfClipboard* clipboard, const void* streamid, + ULONG index, UINT32 flag, UINT64 position, + ULONG request); + +static void CliprdrDataObject_Delete(CliprdrDataObject* instance); + +static CliprdrEnumFORMATETC* CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC* pFormatEtc); +static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC* instance); + +static void CliprdrStream_Delete(CliprdrStream* instance); + +static BOOL try_open_clipboard(HWND hwnd) +{ + for (size_t x = 0; x < 10; x++) + { + if (OpenClipboard(hwnd)) + return TRUE; + Sleep(10); + } + return FALSE; +} + +/** + * IStream + */ + +static HRESULT STDMETHODCALLTYPE CliprdrStream_QueryInterface(IStream* This, REFIID riid, + void** ppvObject) +{ + if (IsEqualIID(riid, &IID_IStream) || IsEqualIID(riid, &IID_IUnknown)) + { + IStream_AddRef(This); + *ppvObject = This; + return S_OK; + } + else + { + *ppvObject = 0; + return E_NOINTERFACE; + } +} + +static ULONG STDMETHODCALLTYPE CliprdrStream_AddRef(IStream* This) +{ + CliprdrStream* instance = (CliprdrStream*)This; + + if (!instance) + return 0; + + return InterlockedIncrement(&instance->m_lRefCount); +} + +static ULONG STDMETHODCALLTYPE CliprdrStream_Release(IStream* This) +{ + LONG count; + CliprdrStream* instance = (CliprdrStream*)This; + + if (!instance) + return 0; + + count = InterlockedDecrement(&instance->m_lRefCount); + + if (count == 0) + { + CliprdrStream_Delete(instance); + return 0; + } + else + { + return count; + } +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream* This, void* pv, ULONG cb, + ULONG* pcbRead) +{ + int ret; + CliprdrStream* instance = (CliprdrStream*)This; + wfClipboard* clipboard; + + if (!pv || !pcbRead || !instance) + return E_INVALIDARG; + + clipboard = (wfClipboard*)instance->m_pData; + *pcbRead = 0; + + if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart) + return S_FALSE; + + ret = cliprdr_send_request_filecontents(clipboard, (void*)This, instance->m_lIndex, + FILECONTENTS_RANGE, instance->m_lOffset.QuadPart, cb); + + if (ret < 0) + return E_FAIL; + + if (clipboard->req_fdata) + { + CopyMemory(pv, clipboard->req_fdata, clipboard->req_fsize); + free(clipboard->req_fdata); + } + + *pcbRead = clipboard->req_fsize; + instance->m_lOffset.QuadPart += clipboard->req_fsize; + + if (clipboard->req_fsize < cb) + return S_FALSE; + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream* This, const void* pv, ULONG cb, + ULONG* pcbWritten) +{ + (void)This; + (void)pv; + (void)cb; + (void)pcbWritten; + return STG_E_ACCESSDENIED; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Seek(IStream* This, LARGE_INTEGER dlibMove, + DWORD dwOrigin, ULARGE_INTEGER* plibNewPosition) +{ + ULONGLONG newoffset; + CliprdrStream* instance = (CliprdrStream*)This; + + if (!instance) + return E_INVALIDARG; + + newoffset = instance->m_lOffset.QuadPart; + + switch (dwOrigin) + { + case STREAM_SEEK_SET: + newoffset = dlibMove.QuadPart; + break; + + case STREAM_SEEK_CUR: + newoffset += dlibMove.QuadPart; + break; + + case STREAM_SEEK_END: + newoffset = instance->m_lSize.QuadPart + dlibMove.QuadPart; + break; + + default: + return E_INVALIDARG; + } + + if (newoffset < 0 || newoffset >= instance->m_lSize.QuadPart) + return E_FAIL; + + instance->m_lOffset.QuadPart = newoffset; + + if (plibNewPosition) + plibNewPosition->QuadPart = instance->m_lOffset.QuadPart; + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_SetSize(IStream* This, ULARGE_INTEGER libNewSize) +{ + (void)This; + (void)libNewSize; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_CopyTo(IStream* This, IStream* pstm, + ULARGE_INTEGER cb, ULARGE_INTEGER* pcbRead, + ULARGE_INTEGER* pcbWritten) +{ + (void)This; + (void)pstm; + (void)cb; + (void)pcbRead; + (void)pcbWritten; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Commit(IStream* This, DWORD grfCommitFlags) +{ + (void)This; + (void)grfCommitFlags; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Revert(IStream* This) +{ + (void)This; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_LockRegion(IStream* This, ULARGE_INTEGER libOffset, + ULARGE_INTEGER cb, DWORD dwLockType) +{ + (void)This; + (void)libOffset; + (void)cb; + (void)dwLockType; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_UnlockRegion(IStream* This, ULARGE_INTEGER libOffset, + ULARGE_INTEGER cb, DWORD dwLockType) +{ + (void)This; + (void)libOffset; + (void)cb; + (void)dwLockType; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Stat(IStream* This, STATSTG* pstatstg, + DWORD grfStatFlag) +{ + CliprdrStream* instance = (CliprdrStream*)This; + + if (!instance) + return E_INVALIDARG; + + if (pstatstg == NULL) + return STG_E_INVALIDPOINTER; + + ZeroMemory(pstatstg, sizeof(STATSTG)); + + switch (grfStatFlag) + { + case STATFLAG_DEFAULT: + return STG_E_INSUFFICIENTMEMORY; + + case STATFLAG_NONAME: + pstatstg->cbSize.QuadPart = instance->m_lSize.QuadPart; + pstatstg->grfLocksSupported = LOCK_EXCLUSIVE; + pstatstg->grfMode = GENERIC_READ; + pstatstg->grfStateBits = 0; + pstatstg->type = STGTY_STREAM; + break; + + case STATFLAG_NOOPEN: + return STG_E_INVALIDFLAG; + + default: + return STG_E_INVALIDFLAG; + } + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream* This, IStream** ppstm) +{ + (void)This; + (void)ppstm; + return E_NOTIMPL; +} + +static CliprdrStream* CliprdrStream_New(ULONG index, void* pData, const FILEDESCRIPTORW* dsc) +{ + IStream* iStream; + BOOL success = FALSE; + BOOL isDir = FALSE; + CliprdrStream* instance; + wfClipboard* clipboard = (wfClipboard*)pData; + instance = (CliprdrStream*)calloc(1, sizeof(CliprdrStream)); + + if (instance) + { + instance->m_Dsc = *dsc; + iStream = &instance->iStream; + iStream->lpVtbl = (IStreamVtbl*)calloc(1, sizeof(IStreamVtbl)); + + if (iStream->lpVtbl) + { + iStream->lpVtbl->QueryInterface = CliprdrStream_QueryInterface; + iStream->lpVtbl->AddRef = CliprdrStream_AddRef; + iStream->lpVtbl->Release = CliprdrStream_Release; + iStream->lpVtbl->Read = CliprdrStream_Read; + iStream->lpVtbl->Write = CliprdrStream_Write; + iStream->lpVtbl->Seek = CliprdrStream_Seek; + iStream->lpVtbl->SetSize = CliprdrStream_SetSize; + iStream->lpVtbl->CopyTo = CliprdrStream_CopyTo; + iStream->lpVtbl->Commit = CliprdrStream_Commit; + iStream->lpVtbl->Revert = CliprdrStream_Revert; + iStream->lpVtbl->LockRegion = CliprdrStream_LockRegion; + iStream->lpVtbl->UnlockRegion = CliprdrStream_UnlockRegion; + iStream->lpVtbl->Stat = CliprdrStream_Stat; + iStream->lpVtbl->Clone = CliprdrStream_Clone; + instance->m_lRefCount = 1; + instance->m_lIndex = index; + instance->m_pData = pData; + instance->m_lOffset.QuadPart = 0; + + if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES) + { + if (instance->m_Dsc.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + isDir = TRUE; + } + + if (((instance->m_Dsc.dwFlags & FD_FILESIZE) == 0) && !isDir) + { + /* get content size of this stream */ + if (cliprdr_send_request_filecontents(clipboard, (void*)instance, + instance->m_lIndex, FILECONTENTS_SIZE, 0, + 8) == CHANNEL_RC_OK) + { + success = TRUE; + } + + instance->m_lSize.QuadPart = *((LONGLONG*)clipboard->req_fdata); + free(clipboard->req_fdata); + } + else + { + instance->m_lSize.QuadPart = + ((UINT64)instance->m_Dsc.nFileSizeHigh << 32) | instance->m_Dsc.nFileSizeLow; + success = TRUE; + } + } + } + + if (!success) + { + CliprdrStream_Delete(instance); + instance = NULL; + } + + return instance; +} + +void CliprdrStream_Delete(CliprdrStream* instance) +{ + if (instance) + { + free(instance->iStream.lpVtbl); + free(instance); + } +} + +/** + * IDataObject + */ + +static LONG cliprdr_lookup_format(CliprdrDataObject* instance, FORMATETC* pFormatEtc) +{ + if (!instance || !pFormatEtc) + return -1; + + for (ULONG i = 0; i < instance->m_nNumFormats; i++) + { + if ((pFormatEtc->tymed & instance->m_pFormatEtc[i].tymed) && + pFormatEtc->cfFormat == instance->m_pFormatEtc[i].cfFormat && + pFormatEtc->dwAspect & instance->m_pFormatEtc[i].dwAspect) + { + return (LONG)i; + } + } + + return -1; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_QueryInterface(IDataObject* This, REFIID riid, + void** ppvObject) +{ + (void)This; + + if (!ppvObject) + return E_INVALIDARG; + + if (IsEqualIID(riid, &IID_IDataObject) || IsEqualIID(riid, &IID_IUnknown)) + { + IDataObject_AddRef(This); + *ppvObject = This; + return S_OK; + } + else + { + *ppvObject = 0; + return E_NOINTERFACE; + } +} + +static ULONG STDMETHODCALLTYPE CliprdrDataObject_AddRef(IDataObject* This) +{ + CliprdrDataObject* instance = (CliprdrDataObject*)This; + + if (!instance) + return E_INVALIDARG; + + return InterlockedIncrement(&instance->m_lRefCount); +} + +static ULONG STDMETHODCALLTYPE CliprdrDataObject_Release(IDataObject* This) +{ + LONG count; + CliprdrDataObject* instance = (CliprdrDataObject*)This; + + if (!instance) + return E_INVALIDARG; + + count = InterlockedDecrement(&instance->m_lRefCount); + + if (count == 0) + { + CliprdrDataObject_Delete(instance); + return 0; + } + else + return count; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject* This, FORMATETC* pFormatEtc, + STGMEDIUM* pMedium) +{ + LONG idx; + CliprdrDataObject* instance = (CliprdrDataObject*)This; + wfClipboard* clipboard; + + if (!pFormatEtc || !pMedium || !instance) + return E_INVALIDARG; + + clipboard = (wfClipboard*)instance->m_pData; + + if (!clipboard) + return E_INVALIDARG; + + if ((idx = cliprdr_lookup_format(instance, pFormatEtc)) == -1) + return DV_E_FORMATETC; + + pMedium->tymed = instance->m_pFormatEtc[idx].tymed; + pMedium->pUnkForRelease = 0; + + if (instance->m_pFormatEtc[idx].cfFormat == RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW)) + { + FILEGROUPDESCRIPTOR* dsc; + DWORD remote = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat); + + if (cliprdr_send_data_request(clipboard, remote) != 0) + return E_UNEXPECTED; + + pMedium->u.hGlobal = clipboard->hmem; + /* points to a FILEGROUPDESCRIPTOR structure */ + /* GlobalLock returns a pointer to the first byte of the memory block, + * in which is a FILEGROUPDESCRIPTOR structure, whose first UINT member + * is the number of FILEDESCRIPTOR's */ + dsc = (FILEGROUPDESCRIPTOR*)GlobalLock(clipboard->hmem); + instance->m_nStreams = dsc->cItems; + GlobalUnlock(clipboard->hmem); + + if (instance->m_nStreams > 0) + { + if (!instance->m_pStream) + { + instance->m_pStream = (LPSTREAM*)calloc(instance->m_nStreams, sizeof(LPSTREAM)); + + if (instance->m_pStream) + { + for (ULONG i = 0; i < instance->m_nStreams; i++) + { + instance->m_pStream[i] = + (IStream*)CliprdrStream_New(i, clipboard, &dsc->fgd[i]); + + if (!instance->m_pStream[i]) + return E_OUTOFMEMORY; + } + } + } + } + + if (!instance->m_pStream) + { + if (clipboard->hmem) + { + GlobalFree(clipboard->hmem); + clipboard->hmem = NULL; + } + + pMedium->u.hGlobal = NULL; + return E_OUTOFMEMORY; + } + } + else if (instance->m_pFormatEtc[idx].cfFormat == RegisterClipboardFormat(CFSTR_FILECONTENTS)) + { + if ((pFormatEtc->lindex >= 0) && ((ULONG)pFormatEtc->lindex < instance->m_nStreams)) + { + pMedium->u.pstm = instance->m_pStream[pFormatEtc->lindex]; + IDataObject_AddRef(instance->m_pStream[pFormatEtc->lindex]); + } + else + return E_INVALIDARG; + } + else + return E_UNEXPECTED; + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetDataHere(IDataObject* This, + FORMATETC* pformatetc, + STGMEDIUM* pmedium) +{ + (void)This; + (void)pformatetc; + (void)pmedium; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_QueryGetData(IDataObject* This, + FORMATETC* pformatetc) +{ + CliprdrDataObject* instance = (CliprdrDataObject*)This; + + if (!pformatetc) + return E_INVALIDARG; + + if (cliprdr_lookup_format(instance, pformatetc) == -1) + return DV_E_FORMATETC; + + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetCanonicalFormatEtc(IDataObject* This, + FORMATETC* pformatectIn, + FORMATETC* pformatetcOut) +{ + (void)This; + (void)pformatectIn; + + if (!pformatetcOut) + return E_INVALIDARG; + + pformatetcOut->ptd = NULL; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_SetData(IDataObject* This, FORMATETC* pformatetc, + STGMEDIUM* pmedium, BOOL fRelease) +{ + (void)This; + (void)pformatetc; + (void)pmedium; + (void)fRelease; + return E_NOTIMPL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_EnumFormatEtc(IDataObject* This, + DWORD dwDirection, + IEnumFORMATETC** ppenumFormatEtc) +{ + CliprdrDataObject* instance = (CliprdrDataObject*)This; + + if (!instance || !ppenumFormatEtc) + return E_INVALIDARG; + + if (dwDirection == DATADIR_GET) + { + *ppenumFormatEtc = (IEnumFORMATETC*)CliprdrEnumFORMATETC_New(instance->m_nNumFormats, + instance->m_pFormatEtc); + return (*ppenumFormatEtc) ? S_OK : E_OUTOFMEMORY; + } + else + { + return E_NOTIMPL; + } +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_DAdvise(IDataObject* This, FORMATETC* pformatetc, + DWORD advf, IAdviseSink* pAdvSink, + DWORD* pdwConnection) +{ + (void)This; + (void)pformatetc; + (void)advf; + (void)pAdvSink; + (void)pdwConnection; + return OLE_E_ADVISENOTSUPPORTED; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_DUnadvise(IDataObject* This, DWORD dwConnection) +{ + (void)This; + (void)dwConnection; + return OLE_E_ADVISENOTSUPPORTED; +} + +static HRESULT STDMETHODCALLTYPE CliprdrDataObject_EnumDAdvise(IDataObject* This, + IEnumSTATDATA** ppenumAdvise) +{ + (void)This; + (void)ppenumAdvise; + return OLE_E_ADVISENOTSUPPORTED; +} + +static CliprdrDataObject* CliprdrDataObject_New(FORMATETC* fmtetc, STGMEDIUM* stgmed, ULONG count, + void* data) +{ + CliprdrDataObject* instance; + IDataObject* iDataObject; + instance = (CliprdrDataObject*)calloc(1, sizeof(CliprdrDataObject)); + + if (!instance) + goto error; + + iDataObject = &instance->iDataObject; + iDataObject->lpVtbl = (IDataObjectVtbl*)calloc(1, sizeof(IDataObjectVtbl)); + + if (!iDataObject->lpVtbl) + goto error; + + iDataObject->lpVtbl->QueryInterface = CliprdrDataObject_QueryInterface; + iDataObject->lpVtbl->AddRef = CliprdrDataObject_AddRef; + iDataObject->lpVtbl->Release = CliprdrDataObject_Release; + iDataObject->lpVtbl->GetData = CliprdrDataObject_GetData; + iDataObject->lpVtbl->GetDataHere = CliprdrDataObject_GetDataHere; + iDataObject->lpVtbl->QueryGetData = CliprdrDataObject_QueryGetData; + iDataObject->lpVtbl->GetCanonicalFormatEtc = CliprdrDataObject_GetCanonicalFormatEtc; + iDataObject->lpVtbl->SetData = CliprdrDataObject_SetData; + iDataObject->lpVtbl->EnumFormatEtc = CliprdrDataObject_EnumFormatEtc; + iDataObject->lpVtbl->DAdvise = CliprdrDataObject_DAdvise; + iDataObject->lpVtbl->DUnadvise = CliprdrDataObject_DUnadvise; + iDataObject->lpVtbl->EnumDAdvise = CliprdrDataObject_EnumDAdvise; + instance->m_lRefCount = 1; + instance->m_nNumFormats = count; + instance->m_pData = data; + instance->m_nStreams = 0; + instance->m_pStream = NULL; + + if (count > 0) + { + instance->m_pFormatEtc = (FORMATETC*)calloc(count, sizeof(FORMATETC)); + + if (!instance->m_pFormatEtc) + goto error; + + instance->m_pStgMedium = (STGMEDIUM*)calloc(count, sizeof(STGMEDIUM)); + + if (!instance->m_pStgMedium) + goto error; + + for (ULONG i = 0; i < count; i++) + { + instance->m_pFormatEtc[i] = fmtetc[i]; + instance->m_pStgMedium[i] = stgmed[i]; + } + } + + return instance; +error: + CliprdrDataObject_Delete(instance); + return NULL; +} + +void CliprdrDataObject_Delete(CliprdrDataObject* instance) +{ + if (instance) + { + free(instance->iDataObject.lpVtbl); + free(instance->m_pFormatEtc); + free(instance->m_pStgMedium); + + if (instance->m_pStream) + { + for (ULONG i = 0; i < instance->m_nStreams; i++) + CliprdrStream_Release(instance->m_pStream[i]); + + free(instance->m_pStream); + } + + free(instance); + } +} + +static BOOL wf_create_file_obj(wfClipboard* clipboard, IDataObject** ppDataObject) +{ + FORMATETC fmtetc[2] = { 0 }; + STGMEDIUM stgmeds[2] = { 0 }; + + if (!ppDataObject) + return FALSE; + + fmtetc[0].cfFormat = RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW); + fmtetc[0].dwAspect = DVASPECT_CONTENT; + + fmtetc[0].tymed = TYMED_HGLOBAL; + stgmeds[0].tymed = TYMED_HGLOBAL; + + fmtetc[1].cfFormat = RegisterClipboardFormat(CFSTR_FILECONTENTS); + fmtetc[1].dwAspect = DVASPECT_CONTENT; + + fmtetc[1].tymed = TYMED_ISTREAM; + stgmeds[1].tymed = TYMED_ISTREAM; + + *ppDataObject = (IDataObject*)CliprdrDataObject_New(fmtetc, stgmeds, 2, clipboard); + return (*ppDataObject) ? TRUE : FALSE; +} + +static void wf_destroy_file_obj(IDataObject* instance) +{ + if (instance) + IDataObject_Release(instance); +} + +/** + * IEnumFORMATETC + */ + +static void cliprdr_format_deep_copy(FORMATETC* dest, FORMATETC* source) +{ + *dest = *source; + + if (source->ptd) + { + dest->ptd = (DVTARGETDEVICE*)CoTaskMemAlloc(sizeof(DVTARGETDEVICE)); + + if (dest->ptd) + *(dest->ptd) = *(source->ptd); + } +} + +static HRESULT STDMETHODCALLTYPE CliprdrEnumFORMATETC_QueryInterface(IEnumFORMATETC* This, + REFIID riid, void** ppvObject) +{ + (void)This; + + if (IsEqualIID(riid, &IID_IEnumFORMATETC) || IsEqualIID(riid, &IID_IUnknown)) + { + IEnumFORMATETC_AddRef(This); + *ppvObject = This; + return S_OK; + } + else + { + *ppvObject = 0; + return E_NOINTERFACE; + } +} + +static ULONG STDMETHODCALLTYPE CliprdrEnumFORMATETC_AddRef(IEnumFORMATETC* This) +{ + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance) + return 0; + + return InterlockedIncrement(&instance->m_lRefCount); +} + +static ULONG STDMETHODCALLTYPE CliprdrEnumFORMATETC_Release(IEnumFORMATETC* This) +{ + LONG count; + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance) + return 0; + + count = InterlockedDecrement(&instance->m_lRefCount); + + if (count == 0) + { + CliprdrEnumFORMATETC_Delete(instance); + return 0; + } + else + { + return count; + } +} + +static HRESULT STDMETHODCALLTYPE CliprdrEnumFORMATETC_Next(IEnumFORMATETC* This, ULONG celt, + FORMATETC* rgelt, ULONG* pceltFetched) +{ + ULONG copied = 0; + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance || !celt || !rgelt) + return E_INVALIDARG; + + while ((instance->m_nIndex < instance->m_nNumFormats) && (copied < celt)) + { + cliprdr_format_deep_copy(&rgelt[copied++], &instance->m_pFormatEtc[instance->m_nIndex++]); + } + + if (pceltFetched != 0) + *pceltFetched = copied; + + return (copied == celt) ? S_OK : E_FAIL; +} + +static HRESULT STDMETHODCALLTYPE CliprdrEnumFORMATETC_Skip(IEnumFORMATETC* This, ULONG celt) +{ + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance) + return E_INVALIDARG; + + if (instance->m_nIndex + (LONG)celt > instance->m_nNumFormats) + return E_FAIL; + + instance->m_nIndex += celt; + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrEnumFORMATETC_Reset(IEnumFORMATETC* This) +{ + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance) + return E_INVALIDARG; + + instance->m_nIndex = 0; + return S_OK; +} + +static HRESULT STDMETHODCALLTYPE CliprdrEnumFORMATETC_Clone(IEnumFORMATETC* This, + IEnumFORMATETC** ppEnum) +{ + CliprdrEnumFORMATETC* instance = (CliprdrEnumFORMATETC*)This; + + if (!instance || !ppEnum) + return E_INVALIDARG; + + *ppEnum = + (IEnumFORMATETC*)CliprdrEnumFORMATETC_New(instance->m_nNumFormats, instance->m_pFormatEtc); + + if (!*ppEnum) + return E_OUTOFMEMORY; + + ((CliprdrEnumFORMATETC*)*ppEnum)->m_nIndex = instance->m_nIndex; + return S_OK; +} + +CliprdrEnumFORMATETC* CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC* pFormatEtc) +{ + CliprdrEnumFORMATETC* instance; + IEnumFORMATETC* iEnumFORMATETC; + + if ((nFormats != 0) && !pFormatEtc) + return NULL; + + instance = (CliprdrEnumFORMATETC*)calloc(1, sizeof(CliprdrEnumFORMATETC)); + + if (!instance) + goto error; + + iEnumFORMATETC = &instance->iEnumFORMATETC; + iEnumFORMATETC->lpVtbl = (IEnumFORMATETCVtbl*)calloc(1, sizeof(IEnumFORMATETCVtbl)); + + if (!iEnumFORMATETC->lpVtbl) + goto error; + + iEnumFORMATETC->lpVtbl->QueryInterface = CliprdrEnumFORMATETC_QueryInterface; + iEnumFORMATETC->lpVtbl->AddRef = CliprdrEnumFORMATETC_AddRef; + iEnumFORMATETC->lpVtbl->Release = CliprdrEnumFORMATETC_Release; + iEnumFORMATETC->lpVtbl->Next = CliprdrEnumFORMATETC_Next; + iEnumFORMATETC->lpVtbl->Skip = CliprdrEnumFORMATETC_Skip; + iEnumFORMATETC->lpVtbl->Reset = CliprdrEnumFORMATETC_Reset; + iEnumFORMATETC->lpVtbl->Clone = CliprdrEnumFORMATETC_Clone; + instance->m_lRefCount = 1; + instance->m_nIndex = 0; + instance->m_nNumFormats = nFormats; + + if (nFormats > 0) + { + instance->m_pFormatEtc = (FORMATETC*)calloc(nFormats, sizeof(FORMATETC)); + + if (!instance->m_pFormatEtc) + goto error; + + for (ULONG i = 0; i < nFormats; i++) + cliprdr_format_deep_copy(&instance->m_pFormatEtc[i], &pFormatEtc[i]); + } + + return instance; +error: + CliprdrEnumFORMATETC_Delete(instance); + return NULL; +} + +void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC* instance) +{ + if (instance) + { + free(instance->iEnumFORMATETC.lpVtbl); + + if (instance->m_pFormatEtc) + { + for (LONG i = 0; i < instance->m_nNumFormats; i++) + { + if (instance->m_pFormatEtc[i].ptd) + CoTaskMemFree(instance->m_pFormatEtc[i].ptd); + } + + free(instance->m_pFormatEtc); + } + + free(instance); + } +} + +/***********************************************************************************/ + +static UINT32 get_local_format_id_by_name(wfClipboard* clipboard, const TCHAR* format_name) +{ + formatMapping* map; + WCHAR* unicode_name; +#if !defined(UNICODE) + size_t size; +#endif + + if (!clipboard || !format_name) + return 0; + +#if defined(UNICODE) + unicode_name = _wcsdup(format_name); +#else + size = _tcslen(format_name); + unicode_name = calloc(size + 1, sizeof(WCHAR)); + + if (!unicode_name) + return 0; + + MultiByteToWideChar(CP_OEMCP, 0, format_name, strlen(format_name), unicode_name, size); +#endif + + if (!unicode_name) + return 0; + + for (size_t i = 0; i < clipboard->map_size; i++) + { + map = &clipboard->format_mappings[i]; + + if (map->name) + { + if (wcscmp(map->name, unicode_name) == 0) + { + free(unicode_name); + return map->local_format_id; + } + } + } + + free(unicode_name); + return 0; +} + +static INLINE BOOL file_transferring(wfClipboard* clipboard) +{ + return get_local_format_id_by_name(clipboard, CFSTR_FILEDESCRIPTORW) ? TRUE : FALSE; +} + +static UINT32 get_remote_format_id(wfClipboard* clipboard, UINT32 local_format) +{ + formatMapping* map; + + if (!clipboard) + return 0; + + for (UINT32 i = 0; i < clipboard->map_size; i++) + { + map = &clipboard->format_mappings[i]; + + if (map->local_format_id == local_format) + return map->remote_format_id; + } + + return local_format; +} + +static void map_ensure_capacity(wfClipboard* clipboard) +{ + if (!clipboard) + return; + + if (clipboard->map_size >= clipboard->map_capacity) + { + size_t new_size; + formatMapping* new_map; + new_size = clipboard->map_capacity * 2; + new_map = + (formatMapping*)realloc(clipboard->format_mappings, sizeof(formatMapping) * new_size); + + if (!new_map) + return; + + clipboard->format_mappings = new_map; + clipboard->map_capacity = new_size; + } +} + +static BOOL clear_format_map(wfClipboard* clipboard) +{ + formatMapping* map; + + if (!clipboard) + return FALSE; + + if (clipboard->format_mappings) + { + for (size_t i = 0; i < clipboard->map_capacity; i++) + { + map = &clipboard->format_mappings[i]; + map->remote_format_id = 0; + map->local_format_id = 0; + free(map->name); + map->name = NULL; + } + } + + clipboard->map_size = 0; + return TRUE; +} + +static UINT cliprdr_send_tempdir(wfClipboard* clipboard) +{ + CLIPRDR_TEMP_DIRECTORY tempDirectory; + + if (!clipboard) + return -1; + + if (GetEnvironmentVariableA("TEMP", tempDirectory.szTempDir, sizeof(tempDirectory.szTempDir)) == + 0) + return -1; + + return clipboard->context->TempDirectory(clipboard->context, &tempDirectory); +} + +static BOOL cliprdr_GetUpdatedClipboardFormats(wfClipboard* clipboard, PUINT lpuiFormats, + UINT cFormats, PUINT pcFormatsOut) +{ + UINT index = 0; + UINT format = 0; + BOOL clipboardOpen = FALSE; + + if (!clipboard->legacyApi) + return clipboard->GetUpdatedClipboardFormats(lpuiFormats, cFormats, pcFormatsOut); + + clipboardOpen = try_open_clipboard(clipboard->hwnd); + + if (!clipboardOpen) + { + *pcFormatsOut = 0; + return TRUE; /* Other app holding clipboard */ + } + + while (index < cFormats) + { + format = EnumClipboardFormats(format); + + if (!format) + break; + + lpuiFormats[index] = format; + index++; + } + + *pcFormatsOut = index; + CloseClipboard(); + return TRUE; +} + +static UINT cliprdr_send_format_list(wfClipboard* clipboard) +{ + UINT rc; + int count = 0; + UINT32 numFormats = 0; + UINT32 formatId = 0; + char formatName[1024]; + CLIPRDR_FORMAT* formats = NULL; + CLIPRDR_FORMAT_LIST formatList = { 0 }; + + if (!clipboard) + return ERROR_INTERNAL_ERROR; + + /* Ignore if other app is holding clipboard */ + if (try_open_clipboard(clipboard->hwnd)) + { + count = CountClipboardFormats(); + numFormats = (UINT32)count; + formats = (CLIPRDR_FORMAT*)calloc(numFormats, sizeof(CLIPRDR_FORMAT)); + + if (!formats) + { + CloseClipboard(); + return CHANNEL_RC_NO_MEMORY; + } + + { + UINT32 index = 0; + + if (IsClipboardFormatAvailable(CF_HDROP)) + { + formats[index++].formatId = RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW); + formats[index++].formatId = RegisterClipboardFormat(CFSTR_FILECONTENTS); + } + else + { + while ((formatId = EnumClipboardFormats(formatId)) != 0) + formats[index++].formatId = formatId; + } + + numFormats = index; + } + + if (!CloseClipboard()) + { + free(formats); + return ERROR_INTERNAL_ERROR; + } + + for (UINT index = 0; index < numFormats; index++) + { + if (GetClipboardFormatNameA(formats[index].formatId, formatName, sizeof(formatName))) + { + formats[index].formatName = _strdup(formatName); + } + } + } + + formatList.numFormats = numFormats; + formatList.formats = formats; + formatList.common.msgType = CB_FORMAT_LIST; + rc = clipboard->context->ClientFormatList(clipboard->context, &formatList); + + for (UINT index = 0; index < numFormats; index++) + free(formats[index].formatName); + + free(formats); + return rc; +} + +static UINT cliprdr_send_data_request(wfClipboard* clipboard, UINT32 formatId) +{ + UINT rc; + UINT32 remoteFormatId; + CLIPRDR_FORMAT_DATA_REQUEST formatDataRequest; + + if (!clipboard || !clipboard->context || !clipboard->context->ClientFormatDataRequest) + return ERROR_INTERNAL_ERROR; + + remoteFormatId = get_remote_format_id(clipboard, formatId); + + formatDataRequest.requestedFormatId = remoteFormatId; + clipboard->requestedFormatId = formatId; + rc = clipboard->context->ClientFormatDataRequest(clipboard->context, &formatDataRequest); + + if (WaitForSingleObject(clipboard->response_data_event, INFINITE) != WAIT_OBJECT_0) + rc = ERROR_INTERNAL_ERROR; + else if (!ResetEvent(clipboard->response_data_event)) + rc = ERROR_INTERNAL_ERROR; + + return rc; +} + +UINT cliprdr_send_request_filecontents(wfClipboard* clipboard, const void* streamid, ULONG index, + UINT32 flag, UINT64 position, ULONG nreq) +{ + UINT rc; + CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest; + + if (!clipboard || !clipboard->context || !clipboard->context->ClientFileContentsRequest) + return ERROR_INTERNAL_ERROR; + + fileContentsRequest.streamId = (UINT32)(ULONG_PTR)streamid; + fileContentsRequest.listIndex = index; + fileContentsRequest.dwFlags = flag; + fileContentsRequest.nPositionLow = position & 0xFFFFFFFF; + fileContentsRequest.nPositionHigh = (position >> 32) & 0xFFFFFFFF; + fileContentsRequest.cbRequested = nreq; + fileContentsRequest.clipDataId = 0; + fileContentsRequest.common.msgFlags = 0; + rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest); + + if (WaitForSingleObject(clipboard->req_fevent, INFINITE) != WAIT_OBJECT_0) + rc = ERROR_INTERNAL_ERROR; + else if (!ResetEvent(clipboard->req_fevent)) + rc = ERROR_INTERNAL_ERROR; + + return rc; +} + +static UINT cliprdr_send_response_filecontents(wfClipboard* clipboard, UINT32 streamId, UINT32 size, + BYTE* data) +{ + CLIPRDR_FILE_CONTENTS_RESPONSE fileContentsResponse; + + if (!clipboard || !clipboard->context || !clipboard->context->ClientFileContentsResponse) + return ERROR_INTERNAL_ERROR; + + fileContentsResponse.streamId = streamId; + fileContentsResponse.cbRequested = size; + fileContentsResponse.requestedData = data; + fileContentsResponse.common.msgFlags = CB_RESPONSE_OK; + return clipboard->context->ClientFileContentsResponse(clipboard->context, + &fileContentsResponse); +} + +static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) +{ + static wfClipboard* clipboard = NULL; + + switch (Msg) + { + case WM_CREATE: + DEBUG_CLIPRDR("info: WM_CREATE"); + clipboard = (wfClipboard*)((CREATESTRUCT*)lParam)->lpCreateParams; + clipboard->hwnd = hWnd; + + if (!clipboard->legacyApi) + clipboard->AddClipboardFormatListener(hWnd); + else + clipboard->hWndNextViewer = SetClipboardViewer(hWnd); + + break; + + case WM_CLOSE: + DEBUG_CLIPRDR("info: WM_CLOSE"); + + if (!clipboard->legacyApi) + clipboard->RemoveClipboardFormatListener(hWnd); + + break; + + case WM_DESTROY: + if (clipboard->legacyApi) + ChangeClipboardChain(hWnd, clipboard->hWndNextViewer); + + break; + + case WM_CLIPBOARDUPDATE: + DEBUG_CLIPRDR("info: WM_CLIPBOARDUPDATE"); + + if (clipboard->sync) + { + if ((GetClipboardOwner() != clipboard->hwnd) && + (S_FALSE == OleIsCurrentClipboard(clipboard->data_obj))) + { + if (clipboard->hmem) + { + GlobalFree(clipboard->hmem); + clipboard->hmem = NULL; + } + + cliprdr_send_format_list(clipboard); + } + } + + break; + + case WM_RENDERALLFORMATS: + DEBUG_CLIPRDR("info: WM_RENDERALLFORMATS"); + + /* discard all contexts in clipboard */ + if (!try_open_clipboard(clipboard->hwnd)) + { + DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError()); + break; + } + + EmptyClipboard(); + CloseClipboard(); + break; + + case WM_RENDERFORMAT: + DEBUG_CLIPRDR("info: WM_RENDERFORMAT"); + + if (cliprdr_send_data_request(clipboard, (UINT32)wParam) != 0) + { + DEBUG_CLIPRDR("error: cliprdr_send_data_request failed."); + break; + } + + if (!SetClipboardData((UINT)wParam, clipboard->hmem)) + { + DEBUG_CLIPRDR("SetClipboardData failed with 0x%x", GetLastError()); + + if (clipboard->hmem) + { + GlobalFree(clipboard->hmem); + clipboard->hmem = NULL; + } + } + + /* Note: GlobalFree() is not needed when success */ + break; + + case WM_DRAWCLIPBOARD: + if (clipboard->legacyApi) + { + if ((GetClipboardOwner() != clipboard->hwnd) && + (S_FALSE == OleIsCurrentClipboard(clipboard->data_obj))) + { + cliprdr_send_format_list(clipboard); + } + + SendMessage(clipboard->hWndNextViewer, Msg, wParam, lParam); + } + + break; + + case WM_CHANGECBCHAIN: + if (clipboard->legacyApi) + { + HWND hWndCurrViewer = (HWND)wParam; + HWND hWndNextViewer = (HWND)lParam; + + if (hWndCurrViewer == clipboard->hWndNextViewer) + clipboard->hWndNextViewer = hWndNextViewer; + else if (clipboard->hWndNextViewer) + SendMessage(clipboard->hWndNextViewer, Msg, wParam, lParam); + } + + break; + + case WM_CLIPRDR_MESSAGE: + DEBUG_CLIPRDR("info: WM_CLIPRDR_MESSAGE"); + + switch (wParam) + { + case OLE_SETCLIPBOARD: + DEBUG_CLIPRDR("info: OLE_SETCLIPBOARD"); + + if (wf_create_file_obj(clipboard, &clipboard->data_obj)) + { + if (OleSetClipboard(clipboard->data_obj) != S_OK) + { + wf_destroy_file_obj(clipboard->data_obj); + clipboard->data_obj = NULL; + } + } + + break; + + default: + break; + } + + break; + + case WM_DESTROYCLIPBOARD: + case WM_ASKCBFORMATNAME: + case WM_HSCROLLCLIPBOARD: + case WM_PAINTCLIPBOARD: + case WM_SIZECLIPBOARD: + case WM_VSCROLLCLIPBOARD: + default: + return DefWindowProc(hWnd, Msg, wParam, lParam); + } + + return 0; +} + +static int create_cliprdr_window(wfClipboard* clipboard) +{ + WNDCLASSEX wnd_cls = { 0 }; + + wnd_cls.cbSize = sizeof(WNDCLASSEX); + wnd_cls.style = CS_OWNDC; + wnd_cls.lpfnWndProc = cliprdr_proc; + wnd_cls.cbClsExtra = 0; + wnd_cls.cbWndExtra = 0; + wnd_cls.hIcon = NULL; + wnd_cls.hCursor = NULL; + wnd_cls.hbrBackground = NULL; + wnd_cls.lpszMenuName = NULL; + wnd_cls.lpszClassName = _T("ClipboardHiddenMessageProcessor"); + wnd_cls.hInstance = GetModuleHandle(NULL); + wnd_cls.hIconSm = NULL; + RegisterClassEx(&wnd_cls); + clipboard->hwnd = + CreateWindowEx(WS_EX_LEFT, _T("ClipboardHiddenMessageProcessor"), _T("rdpclip"), 0, 0, 0, 0, + 0, HWND_MESSAGE, NULL, GetModuleHandle(NULL), clipboard); + + if (!clipboard->hwnd) + { + DEBUG_CLIPRDR("error: CreateWindowEx failed with %x.", GetLastError()); + return -1; + } + + return 0; +} + +static DWORD WINAPI cliprdr_thread_func(LPVOID arg) +{ + int ret; + MSG msg; + BOOL mcode; + wfClipboard* clipboard = (wfClipboard*)arg; + OleInitialize(0); + + if ((ret = create_cliprdr_window(clipboard)) != 0) + { + OleUninitialize(); + DEBUG_CLIPRDR("error: create clipboard window failed."); + return 0; + } + + while ((mcode = GetMessage(&msg, 0, 0, 0)) != 0) + { + if (mcode == -1) + { + DEBUG_CLIPRDR("error: clipboard thread GetMessage failed."); + break; + } + else + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + OleUninitialize(); + return 0; +} + +static void clear_file_array(wfClipboard* clipboard) +{ + if (!clipboard) + return; + + /* clear file_names array */ + if (clipboard->file_names) + { + for (size_t i = 0; i < clipboard->nFiles; i++) + { + free(clipboard->file_names[i]); + clipboard->file_names[i] = NULL; + } + + free(clipboard->file_names); + clipboard->file_names = NULL; + } + + /* clear fileDescriptor array */ + if (clipboard->fileDescriptor) + { + for (size_t i = 0; i < clipboard->nFiles; i++) + { + free(clipboard->fileDescriptor[i]); + clipboard->fileDescriptor[i] = NULL; + } + + free(clipboard->fileDescriptor); + clipboard->fileDescriptor = NULL; + } + + clipboard->file_array_size = 0; + clipboard->nFiles = 0; +} + +static BOOL wf_cliprdr_get_file_contents(WCHAR* file_name, BYTE* buffer, LONG positionLow, + LONG positionHigh, DWORD nRequested, DWORD* puSize) +{ + BOOL res = FALSE; + HANDLE hFile; + DWORD nGet, rc; + + if (!file_name || !buffer || !puSize) + { + WLog_ERR(TAG, "get file contents Invalid Arguments."); + return FALSE; + } + + hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + rc = SetFilePointer(hFile, positionLow, &positionHigh, FILE_BEGIN); + + if (rc == INVALID_SET_FILE_POINTER) + goto error; + + if (!ReadFile(hFile, buffer, nRequested, &nGet, NULL)) + { + DEBUG_CLIPRDR("ReadFile failed with 0x%08lX.", GetLastError()); + goto error; + } + + res = TRUE; +error: + + if (!CloseHandle(hFile)) + res = FALSE; + + if (res) + *puSize = nGet; + + return res; +} + +/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */ +static FILEDESCRIPTORW* wf_cliprdr_get_file_descriptor(WCHAR* file_name, size_t pathLen) +{ + HANDLE hFile; + FILEDESCRIPTORW* fd; + fd = (FILEDESCRIPTORW*)calloc(1, sizeof(FILEDESCRIPTORW)); + + if (!fd) + return NULL; + + hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); + + if (hFile == INVALID_HANDLE_VALUE) + { + free(fd); + return NULL; + } + + fd->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI; + fd->dwFileAttributes = GetFileAttributes(file_name); + + if (!GetFileTime(hFile, NULL, NULL, &fd->ftLastWriteTime)) + { + fd->dwFlags &= ~FD_WRITESTIME; + } + + fd->nFileSizeLow = GetFileSize(hFile, &fd->nFileSizeHigh); + wcscpy_s(fd->cFileName, sizeof(fd->cFileName) / 2, file_name + pathLen); + (void)CloseHandle(hFile); + return fd; +} + +static BOOL wf_cliprdr_array_ensure_capacity(wfClipboard* clipboard) +{ + if (!clipboard) + return FALSE; + + if (clipboard->nFiles == clipboard->file_array_size) + { + size_t new_size; + FILEDESCRIPTORW** new_fd; + WCHAR** new_name; + new_size = (clipboard->file_array_size + 1) * 2; + new_fd = (FILEDESCRIPTORW**)realloc(clipboard->fileDescriptor, + new_size * sizeof(FILEDESCRIPTORW*)); + + if (new_fd) + clipboard->fileDescriptor = new_fd; + + new_name = (WCHAR**)realloc(clipboard->file_names, new_size * sizeof(WCHAR*)); + + if (new_name) + clipboard->file_names = new_name; + + if (!new_fd || !new_name) + return FALSE; + + clipboard->file_array_size = new_size; + } + + return TRUE; +} + +static BOOL wf_cliprdr_add_to_file_arrays(wfClipboard* clipboard, WCHAR* full_file_name, + size_t pathLen) +{ + if (!wf_cliprdr_array_ensure_capacity(clipboard)) + return FALSE; + + /* add to name array */ + clipboard->file_names[clipboard->nFiles] = (LPWSTR)malloc(MAX_PATH * 2); + + if (!clipboard->file_names[clipboard->nFiles]) + return FALSE; + + wcscpy_s(clipboard->file_names[clipboard->nFiles], MAX_PATH, full_file_name); + /* add to descriptor array */ + clipboard->fileDescriptor[clipboard->nFiles] = + wf_cliprdr_get_file_descriptor(full_file_name, pathLen); + + if (!clipboard->fileDescriptor[clipboard->nFiles]) + { + free(clipboard->file_names[clipboard->nFiles]); + return FALSE; + } + + clipboard->nFiles++; + return TRUE; +} + +static BOOL wf_cliprdr_traverse_directory(wfClipboard* clipboard, WCHAR* Dir, size_t pathLen) +{ + HANDLE hFind; + WCHAR DirSpec[MAX_PATH]; + WIN32_FIND_DATA FindFileData; + + if (!clipboard || !Dir) + return FALSE; + + StringCchCopy(DirSpec, MAX_PATH, Dir); + StringCchCat(DirSpec, MAX_PATH, TEXT("\\*")); + hFind = FindFirstFile(DirSpec, &FindFileData); + + if (hFind == INVALID_HANDLE_VALUE) + { + DEBUG_CLIPRDR("FindFirstFile failed with 0x%x.", GetLastError()); + return FALSE; + } + + while (FindNextFile(hFind, &FindFileData)) + { + if ((((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) && + (wcscmp(FindFileData.cFileName, _T(".")) == 0)) || + (wcscmp(FindFileData.cFileName, _T("..")) == 0)) + { + continue; + } + + if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) + { + WCHAR DirAdd[MAX_PATH]; + StringCchCopy(DirAdd, MAX_PATH, Dir); + StringCchCat(DirAdd, MAX_PATH, _T("\\")); + StringCchCat(DirAdd, MAX_PATH, FindFileData.cFileName); + + if (!wf_cliprdr_add_to_file_arrays(clipboard, DirAdd, pathLen)) + return FALSE; + + if (!wf_cliprdr_traverse_directory(clipboard, DirAdd, pathLen)) + return FALSE; + } + else + { + WCHAR fileName[MAX_PATH]; + StringCchCopy(fileName, MAX_PATH, Dir); + StringCchCat(fileName, MAX_PATH, _T("\\")); + StringCchCat(fileName, MAX_PATH, FindFileData.cFileName); + + if (!wf_cliprdr_add_to_file_arrays(clipboard, fileName, pathLen)) + return FALSE; + } + } + + FindClose(hFind); + return TRUE; +} + +static UINT wf_cliprdr_send_client_capabilities(wfClipboard* clipboard) +{ + CLIPRDR_CAPABILITIES capabilities; + CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet; + + if (!clipboard || !clipboard->context || !clipboard->context->ClientCapabilities) + return ERROR_INTERNAL_ERROR; + + capabilities.cCapabilitiesSets = 1; + capabilities.capabilitySets = (CLIPRDR_CAPABILITY_SET*)&(generalCapabilitySet); + generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL; + generalCapabilitySet.capabilitySetLength = 12; + generalCapabilitySet.version = CB_CAPS_VERSION_2; + generalCapabilitySet.generalFlags = + CB_USE_LONG_FORMAT_NAMES | CB_STREAM_FILECLIP_ENABLED | CB_FILECLIP_NO_FILE_PATHS; + return clipboard->context->ClientCapabilities(clipboard->context, &capabilities); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_cliprdr_monitor_ready(CliprdrClientContext* context, + const CLIPRDR_MONITOR_READY* monitorReady) +{ + UINT rc; + wfClipboard* clipboard = (wfClipboard*)context->custom; + + if (!context || !monitorReady) + return ERROR_INTERNAL_ERROR; + + clipboard->sync = TRUE; + rc = wf_cliprdr_send_client_capabilities(clipboard); + + if (rc != CHANNEL_RC_OK) + return rc; + + return cliprdr_send_format_list(clipboard); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_cliprdr_server_capabilities(CliprdrClientContext* context, + const CLIPRDR_CAPABILITIES* capabilities) +{ + CLIPRDR_CAPABILITY_SET* capabilitySet; + wfClipboard* clipboard = (wfClipboard*)context->custom; + + if (!context || !capabilities) + return ERROR_INTERNAL_ERROR; + + for (UINT32 index = 0; index < capabilities->cCapabilitiesSets; index++) + { + capabilitySet = &(capabilities->capabilitySets[index]); + + if ((capabilitySet->capabilitySetType == CB_CAPSTYPE_GENERAL) && + (capabilitySet->capabilitySetLength >= CB_CAPSTYPE_GENERAL_LEN)) + { + CLIPRDR_GENERAL_CAPABILITY_SET* generalCapabilitySet = + (CLIPRDR_GENERAL_CAPABILITY_SET*)capabilitySet; + clipboard->capabilities = generalCapabilitySet->generalFlags; + break; + } + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_cliprdr_server_format_list(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST* formatList) +{ + UINT rc = ERROR_INTERNAL_ERROR; + formatMapping* mapping; + CLIPRDR_FORMAT* format; + wfClipboard* clipboard = (wfClipboard*)context->custom; + + if (!clear_format_map(clipboard)) + return ERROR_INTERNAL_ERROR; + + for (UINT32 i = 0; i < formatList->numFormats; i++) + { + format = &(formatList->formats[i]); + mapping = &(clipboard->format_mappings[i]); + mapping->remote_format_id = format->formatId; + + if (format->formatName) + { + mapping->name = ConvertUtf8ToWCharAlloc(format->formatName, NULL); + + if (mapping->name) + mapping->local_format_id = RegisterClipboardFormatW((LPWSTR)mapping->name); + } + else + { + mapping->name = NULL; + mapping->local_format_id = mapping->remote_format_id; + } + + clipboard->map_size++; + map_ensure_capacity(clipboard); + } + + if (file_transferring(clipboard)) + { + if (PostMessage(clipboard->hwnd, WM_CLIPRDR_MESSAGE, OLE_SETCLIPBOARD, 0)) + rc = CHANNEL_RC_OK; + } + else + { + if (!try_open_clipboard(clipboard->hwnd)) + return CHANNEL_RC_OK; /* Ignore, other app holding clipboard */ + + if (EmptyClipboard()) + { + for (UINT32 i = 0; i < (UINT32)clipboard->map_size; i++) + SetClipboardData(clipboard->format_mappings[i].local_format_id, NULL); + + rc = CHANNEL_RC_OK; + } + + if (!CloseClipboard() && GetLastError()) + return ERROR_INTERNAL_ERROR; + } + + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_format_list_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse) +{ + (void)context; + (void)formatListResponse; + + if (formatListResponse->common.msgFlags != CB_RESPONSE_OK) + WLog_WARN(TAG, "format list update failed"); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_lock_clipboard_data(CliprdrClientContext* context, + const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData) +{ + (void)context; + (void)lockClipboardData; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_unlock_clipboard_data(CliprdrClientContext* context, + const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData) +{ + (void)context; + (void)unlockClipboardData; + return CHANNEL_RC_OK; +} + +static BOOL wf_cliprdr_process_filename(wfClipboard* clipboard, WCHAR* wFileName, size_t str_len) +{ + size_t pathLen; + size_t offset = str_len; + + if (!clipboard || !wFileName) + return FALSE; + + /* find the last '\' in full file name */ + while (offset > 0) + { + if (wFileName[offset] == L'\\') + break; + else + offset--; + } + + pathLen = offset + 1; + + if (!wf_cliprdr_add_to_file_arrays(clipboard, wFileName, pathLen)) + return FALSE; + + if ((clipboard->fileDescriptor[clipboard->nFiles - 1]->dwFileAttributes & + FILE_ATTRIBUTE_DIRECTORY) != 0) + { + /* this is a directory */ + if (!wf_cliprdr_traverse_directory(clipboard, wFileName, pathLen)) + return FALSE; + } + + return TRUE; +} + +static SSIZE_T wf_cliprdr_tryopen(wfClipboard* clipboard, UINT32 requestedFormatId, BYTE** pData) +{ + SSIZE_T rc = -1; + WINPR_ASSERT(clipboard); + WINPR_ASSERT(pData); + + *pData = NULL; + + /* Ignore if other app is holding the clipboard */ + if (!try_open_clipboard(clipboard->hwnd)) + return 0; + + HANDLE hClipdata = GetClipboardData(requestedFormatId); + + if (!hClipdata) + goto fail; + + char* globlemem = (char*)GlobalLock(hClipdata); + const SSIZE_T size = GlobalSize(hClipdata); + if (size <= 0) + goto unlock; + + BYTE* buff = malloc(size); + if (buff == NULL) + goto fail; + CopyMemory(buff, globlemem, size); + *pData = buff; + rc = size; + +unlock: + GlobalUnlock(hClipdata); + +fail: + CloseClipboard(); + + return rc; +} + +static SSIZE_T wf_cliprdr_get_filedescriptor(wfClipboard* clipboard, BYTE** pData) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(pData); + + SSIZE_T rc = -1; + LPDATAOBJECT dataObj = NULL; + FORMATETC format_etc = { 0 }; + STGMEDIUM stg_medium = { 0 }; + + *pData = NULL; + + HRESULT result = OleGetClipboard(&dataObj); + if (FAILED(result)) + return -1; + + /* get DROPFILES struct from OLE */ + format_etc.cfFormat = CF_HDROP; + format_etc.tymed = TYMED_HGLOBAL; + format_etc.dwAspect = 1; + format_etc.lindex = -1; + result = IDataObject_GetData(dataObj, &format_etc, &stg_medium); + + if (FAILED(result)) + { + DEBUG_CLIPRDR("dataObj->GetData failed."); + goto exit; + } + + HGLOBAL hdl = stg_medium.u.hGlobal; + DROPFILES* dropFiles = (DROPFILES*)GlobalLock(hdl); + + if (!dropFiles) + { + ReleaseStgMedium(&stg_medium); + clipboard->nFiles = 0; + goto exit; + } + + clear_file_array(clipboard); + + if (dropFiles->fWide) + { + /* dropFiles contains file names */ + size_t len = 0; + for (WCHAR* wFileName = (WCHAR*)((char*)dropFiles + dropFiles->pFiles); + (len = wcslen(wFileName)) > 0; wFileName += len + 1) + { + wf_cliprdr_process_filename(clipboard, wFileName, wcslen(wFileName)); + } + } + else + { + size_t len = 0; + for (char* p = (char*)((char*)dropFiles + dropFiles->pFiles); (len = strlen(p)) > 0; + p += len + 1, clipboard->nFiles++) + { + const int cchWideChar = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, NULL, 0); + WCHAR* wFileName = (LPWSTR)calloc(cchWideChar, sizeof(WCHAR)); + MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, wFileName, cchWideChar); + wf_cliprdr_process_filename(clipboard, wFileName, cchWideChar); + free(wFileName); + } + } + + GlobalUnlock(hdl); + ReleaseStgMedium(&stg_medium); +exit: +{ + const size_t size = 4ull + clipboard->nFiles * sizeof(FILEDESCRIPTORW); + FILEGROUPDESCRIPTORW* groupDsc = (FILEGROUPDESCRIPTORW*)calloc(size, 1); + + if (groupDsc) + { + groupDsc->cItems = clipboard->nFiles; + + for (size_t i = 0; i < clipboard->nFiles; i++) + { + if (clipboard->fileDescriptor[i]) + groupDsc->fgd[i] = *clipboard->fileDescriptor[i]; + } + + *pData = (BYTE*)groupDsc; + rc = size; + } +} + + IDataObject_Release(dataObj); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_format_data_request(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest) +{ + CLIPRDR_FORMAT_DATA_RESPONSE response = { 0 }; + + if (!context || !formatDataRequest) + return ERROR_INTERNAL_ERROR; + + wfClipboard* clipboard = (wfClipboard*)context->custom; + + if (!clipboard) + return ERROR_INTERNAL_ERROR; + + const UINT32 requestedFormatId = formatDataRequest->requestedFormatId; + + if (requestedFormatId == RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW)) + { + const SSIZE_T res = wf_cliprdr_get_filedescriptor(clipboard, &response.requestedFormatData); + if (res > 0) + response.common.dataLen = (UINT32)res; + } + else + { + const SSIZE_T res = + wf_cliprdr_tryopen(clipboard, requestedFormatId, &response.requestedFormatData); + if (res > 0) + response.common.dataLen = (UINT32)res; + } + + response.common.msgFlags = CB_RESPONSE_OK; + + const UINT rc = clipboard->context->ClientFormatDataResponse(clipboard->context, &response); + free(response.requestedFormatData); + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_format_data_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse) +{ + BYTE* data; + HANDLE hMem; + wfClipboard* clipboard; + + if (!context || !formatDataResponse) + return ERROR_INTERNAL_ERROR; + + clipboard = (wfClipboard*)context->custom; + + if (!clipboard) + return ERROR_INTERNAL_ERROR; + + if (formatDataResponse->common.msgFlags != CB_RESPONSE_OK) + { + clipboard->hmem = NULL; + + if (!SetEvent(clipboard->response_data_event)) + return ERROR_INTERNAL_ERROR; + + return CHANNEL_RC_OK; + } + + hMem = GlobalAlloc(GMEM_MOVEABLE, formatDataResponse->common.dataLen); + + if (!hMem) + return ERROR_INTERNAL_ERROR; + + data = (BYTE*)GlobalLock(hMem); + + if (!data) + { + GlobalFree(hMem); + return ERROR_INTERNAL_ERROR; + } + + CopyMemory(data, formatDataResponse->requestedFormatData, formatDataResponse->common.dataLen); + + if (!GlobalUnlock(hMem) && GetLastError()) + { + GlobalFree(hMem); + return ERROR_INTERNAL_ERROR; + } + + clipboard->hmem = hMem; + + if (!SetEvent(clipboard->response_data_event)) + return ERROR_INTERNAL_ERROR; + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_file_contents_request(CliprdrClientContext* context, + const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) +{ + DWORD uSize = 0; + BYTE* pData = NULL; + HRESULT hRet = S_OK; + FORMATETC vFormatEtc = { 0 }; + LPDATAOBJECT pDataObj = NULL; + STGMEDIUM vStgMedium = { 0 }; + BOOL bIsStreamFile = TRUE; + static LPSTREAM pStreamStc = NULL; + static UINT32 uStreamIdStc = 0; + wfClipboard* clipboard; + UINT rc = ERROR_INTERNAL_ERROR; + UINT sRc; + UINT32 cbRequested; + + if (!context || !fileContentsRequest) + return ERROR_INTERNAL_ERROR; + + clipboard = (wfClipboard*)context->custom; + + if (!clipboard) + return ERROR_INTERNAL_ERROR; + + cbRequested = fileContentsRequest->cbRequested; + if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE) + cbRequested = sizeof(UINT64); + + pData = (BYTE*)calloc(1, cbRequested); + + if (!pData) + goto error; + + hRet = OleGetClipboard(&pDataObj); + + if (FAILED(hRet)) + { + WLog_ERR(TAG, "filecontents: get ole clipboard failed."); + goto error; + } + + vFormatEtc.cfFormat = RegisterClipboardFormat(CFSTR_FILECONTENTS); + vFormatEtc.tymed = TYMED_ISTREAM; + vFormatEtc.dwAspect = 1; + vFormatEtc.lindex = fileContentsRequest->listIndex; + vFormatEtc.ptd = NULL; + + if ((uStreamIdStc != fileContentsRequest->streamId) || !pStreamStc) + { + LPENUMFORMATETC pEnumFormatEtc; + ULONG CeltFetched; + FORMATETC vFormatEtc2; + + if (pStreamStc) + { + IStream_Release(pStreamStc); + pStreamStc = NULL; + } + + bIsStreamFile = FALSE; + hRet = IDataObject_EnumFormatEtc(pDataObj, DATADIR_GET, &pEnumFormatEtc); + + if (hRet == S_OK) + { + do + { + hRet = IEnumFORMATETC_Next(pEnumFormatEtc, 1, &vFormatEtc2, &CeltFetched); + + if (hRet == S_OK) + { + if (vFormatEtc2.cfFormat == RegisterClipboardFormat(CFSTR_FILECONTENTS)) + { + hRet = IDataObject_GetData(pDataObj, &vFormatEtc, &vStgMedium); + + if (hRet == S_OK) + { + pStreamStc = vStgMedium.u.pstm; + uStreamIdStc = fileContentsRequest->streamId; + bIsStreamFile = TRUE; + } + + break; + } + } + } while (hRet == S_OK); + } + } + + if (bIsStreamFile == TRUE) + { + if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE) + { + STATSTG vStatStg = { 0 }; + hRet = IStream_Stat(pStreamStc, &vStatStg, STATFLAG_NONAME); + + if (hRet == S_OK) + { + *((UINT32*)&pData[0]) = vStatStg.cbSize.QuadPart & 0xFFFFFFFF; + *((UINT32*)&pData[4]) = (vStatStg.cbSize.QuadPart >> 32) & 0xFFFFFFFF; + uSize = cbRequested; + } + } + else if (fileContentsRequest->dwFlags == FILECONTENTS_RANGE) + { + LARGE_INTEGER dlibMove; + ULARGE_INTEGER dlibNewPosition; + dlibMove.QuadPart = (INT64)(((UINT64)fileContentsRequest->nPositionHigh << 32) | + fileContentsRequest->nPositionLow); + hRet = IStream_Seek(pStreamStc, dlibMove, STREAM_SEEK_SET, &dlibNewPosition); + + if (SUCCEEDED(hRet)) + hRet = IStream_Read(pStreamStc, pData, cbRequested, (PULONG)&uSize); + } + } + else + { + if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE) + { + if (clipboard->nFiles <= fileContentsRequest->listIndex) + goto error; + *((UINT32*)&pData[0]) = + clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeLow; + *((UINT32*)&pData[4]) = + clipboard->fileDescriptor[fileContentsRequest->listIndex]->nFileSizeHigh; + uSize = cbRequested; + } + else if (fileContentsRequest->dwFlags == FILECONTENTS_RANGE) + { + BOOL bRet; + if (clipboard->nFiles <= fileContentsRequest->listIndex) + goto error; + bRet = wf_cliprdr_get_file_contents( + clipboard->file_names[fileContentsRequest->listIndex], pData, + fileContentsRequest->nPositionLow, fileContentsRequest->nPositionHigh, cbRequested, + &uSize); + + if (bRet == FALSE) + { + WLog_ERR(TAG, "get file contents failed."); + uSize = 0; + goto error; + } + } + } + + rc = CHANNEL_RC_OK; +error: + + if (pDataObj) + IDataObject_Release(pDataObj); + + if (uSize == 0) + { + free(pData); + pData = NULL; + } + + sRc = + cliprdr_send_response_filecontents(clipboard, fileContentsRequest->streamId, uSize, pData); + free(pData); + + if (sRc != CHANNEL_RC_OK) + return sRc; + + return rc; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +wf_cliprdr_server_file_contents_response(CliprdrClientContext* context, + const CLIPRDR_FILE_CONTENTS_RESPONSE* fileContentsResponse) +{ + wfClipboard* clipboard; + + if (!context || !fileContentsResponse) + return ERROR_INTERNAL_ERROR; + + if (fileContentsResponse->common.msgFlags != CB_RESPONSE_OK) + return E_FAIL; + + clipboard = (wfClipboard*)context->custom; + + if (!clipboard) + return ERROR_INTERNAL_ERROR; + + clipboard->req_fsize = fileContentsResponse->cbRequested; + clipboard->req_fdata = (char*)malloc(fileContentsResponse->cbRequested); + + if (!clipboard->req_fdata) + return ERROR_INTERNAL_ERROR; + + CopyMemory(clipboard->req_fdata, fileContentsResponse->requestedData, + fileContentsResponse->cbRequested); + + if (!SetEvent(clipboard->req_fevent)) + { + free(clipboard->req_fdata); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +BOOL wf_cliprdr_init(wfContext* wfc, CliprdrClientContext* cliprdr) +{ + wfClipboard* clipboard; + rdpContext* context = (rdpContext*)wfc; + + if (!context || !cliprdr) + return FALSE; + + wfc->clipboard = (wfClipboard*)calloc(1, sizeof(wfClipboard)); + + if (!wfc->clipboard) + return FALSE; + + clipboard = wfc->clipboard; + clipboard->wfc = wfc; + clipboard->context = cliprdr; + clipboard->channels = context->channels; + clipboard->sync = FALSE; + clipboard->map_capacity = 32; + clipboard->map_size = 0; + clipboard->hUser32 = LoadLibraryA("user32.dll"); + + if (clipboard->hUser32) + { + clipboard->AddClipboardFormatListener = GetProcAddressAs( + clipboard->hUser32, "AddClipboardFormatListener", fnAddClipboardFormatListener); + clipboard->RemoveClipboardFormatListener = GetProcAddressAs( + clipboard->hUser32, "RemoveClipboardFormatListener", fnRemoveClipboardFormatListener); + clipboard->GetUpdatedClipboardFormats = GetProcAddressAs( + clipboard->hUser32, "GetUpdatedClipboardFormats", fnGetUpdatedClipboardFormats); + } + + if (!(clipboard->hUser32 && clipboard->AddClipboardFormatListener && + clipboard->RemoveClipboardFormatListener && clipboard->GetUpdatedClipboardFormats)) + clipboard->legacyApi = TRUE; + + if (!(clipboard->format_mappings = + (formatMapping*)calloc(clipboard->map_capacity, sizeof(formatMapping)))) + goto error; + + if (!(clipboard->response_data_event = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto error; + + if (!(clipboard->req_fevent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto error; + + if (!(clipboard->thread = CreateThread(NULL, 0, cliprdr_thread_func, clipboard, 0, NULL))) + goto error; + + cliprdr->MonitorReady = wf_cliprdr_monitor_ready; + cliprdr->ServerCapabilities = wf_cliprdr_server_capabilities; + cliprdr->ServerFormatList = wf_cliprdr_server_format_list; + cliprdr->ServerFormatListResponse = wf_cliprdr_server_format_list_response; + cliprdr->ServerLockClipboardData = wf_cliprdr_server_lock_clipboard_data; + cliprdr->ServerUnlockClipboardData = wf_cliprdr_server_unlock_clipboard_data; + cliprdr->ServerFormatDataRequest = wf_cliprdr_server_format_data_request; + cliprdr->ServerFormatDataResponse = wf_cliprdr_server_format_data_response; + cliprdr->ServerFileContentsRequest = wf_cliprdr_server_file_contents_request; + cliprdr->ServerFileContentsResponse = wf_cliprdr_server_file_contents_response; + cliprdr->custom = (void*)wfc->clipboard; + return TRUE; +error: + wf_cliprdr_uninit(wfc, cliprdr); + return FALSE; +} + +BOOL wf_cliprdr_uninit(wfContext* wfc, CliprdrClientContext* cliprdr) +{ + wfClipboard* clipboard; + + if (!wfc || !cliprdr) + return FALSE; + + clipboard = wfc->clipboard; + + if (!clipboard) + return FALSE; + + cliprdr->custom = NULL; + + if (clipboard->hwnd) + PostMessage(clipboard->hwnd, WM_QUIT, 0, 0); + + if (clipboard->thread) + { + (void)WaitForSingleObject(clipboard->thread, INFINITE); + (void)CloseHandle(clipboard->thread); + } + + if (clipboard->response_data_event) + (void)CloseHandle(clipboard->response_data_event); + + if (clipboard->req_fevent) + (void)CloseHandle(clipboard->req_fevent); + + clear_file_array(clipboard); + clear_format_map(clipboard); + free(clipboard->format_mappings); + free(clipboard); + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.h new file mode 100644 index 0000000000000000000000000000000000000000..3a6b4a1860764a3ea68c12ed87c004de197cba89 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_cliprdr.h @@ -0,0 +1,27 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Clipboard Redirection + * + * Copyright 2012 Jason Champion + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FREERDP_CLIENT_WIN_CLIPRDR_H +#define FREERDP_CLIENT_WIN_CLIPRDR_H + +#include "wf_client.h" + +BOOL wf_cliprdr_init(wfContext* wfc, CliprdrClientContext* cliprdr); +BOOL wf_cliprdr_uninit(wfContext* wfc, CliprdrClientContext* cliprdr); + +#endif /* FREERDP_CLIENT_WIN_CLIPRDR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.c new file mode 100644 index 0000000000000000000000000000000000000000..2e958830856f636ef801a6400d488a8cfe7ae7d4 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.c @@ -0,0 +1,161 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2022 Stefan Koell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "wf_defaults.h" + +static PCWSTR ValidateString(const BYTE* pb, ULONG cb) +{ + if (!pb || !cb) + return 0; + + if (cb % sizeof(WCHAR) != 0) + return 0; + + return (PCWSTR)pb; +} + +static void AddDefaultSettings_I(rdpSettings* settings, size_t idHostname, size_t idUsername, + size_t idDomain, size_t idPassword) +{ + static const PSTR TERMSRV = "TERMSRV/%s"; + + PSTR TargetName = NULL; + PSTR UserName = NULL; + PWSTR TargetNameW = NULL; + PWSTR ServerHostNameW = NULL; + PWSTR ParsedUserNameW = NULL; + PWSTR ParsedDomainW = NULL; + PWSTR PasswordNullTerminatedW = NULL; + PCREDENTIALW Credential = { 0 }; + + PCSTR ServerHostname = freerdp_settings_get_string(settings, idHostname); + + if (!ServerHostname) + return; + + BOOL bExistUserName = freerdp_settings_get_string(settings, idUsername) != 0; + BOOL bExistPassword = freerdp_settings_get_string(settings, idPassword) != 0; + + if (bExistUserName && bExistPassword) + return; + + int len = _snprintf(TargetName, 0, TERMSRV, ServerHostname); + len++; + TargetName = (PSTR)malloc(len); + + if (!TargetName) + goto fail; + + _snprintf(TargetName, len, TERMSRV, ServerHostname); + + TargetName[len - 1] = 0; + + TargetNameW = ConvertUtf8ToWCharAlloc(TargetName, NULL); + if (!TargetNameW) + goto fail; + + if (!CredReadW(TargetNameW, CRED_TYPE_GENERIC, 0, &Credential)) + goto fail; + + if (!bExistPassword) + { + const WCHAR* PasswordW = + ValidateString(Credential->CredentialBlob, Credential->CredentialBlobSize); + + PasswordNullTerminatedW = (PWSTR)calloc(Credential->CredentialBlobSize + 1, sizeof(WCHAR)); + + if (!PasswordNullTerminatedW) + goto fail; + + memcpy(PasswordNullTerminatedW, PasswordW, Credential->CredentialBlobSize * sizeof(WCHAR)); + + if (PasswordNullTerminatedW) + { + if (!freerdp_settings_set_string_from_utf16(settings, idPassword, + PasswordNullTerminatedW)) + { + goto fail; + } + } + } + + if (!bExistUserName) + { + const WCHAR* UserNameW = Credential->UserName; + + if (UserNameW) + { + ParsedUserNameW = calloc(CREDUI_MAX_USERNAME_LENGTH + 1, sizeof(WCHAR)); + if (!ParsedUserNameW) + goto fail; + + ParsedDomainW = calloc(CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1, sizeof(WCHAR)); + if (!ParsedDomainW) + goto fail; + + DWORD ParseResult = + CredUIParseUserNameW(UserNameW, ParsedUserNameW, CREDUI_MAX_USERNAME_LENGTH + 1, + ParsedDomainW, CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1); + + if (ParseResult == NO_ERROR) + { + if (!freerdp_settings_set_string_from_utf16(settings, idUsername, ParsedUserNameW)) + goto fail; + + if (*ParsedDomainW != 0) + { + if (!freerdp_settings_set_string_from_utf16(settings, idDomain, ParsedDomainW)) + goto fail; + } + } + else if (ParseResult == ERROR_INVALID_ACCOUNT_NAME) + { + if (!freerdp_settings_set_string_from_utf16(settings, idUsername, UserNameW)) + goto fail; + } + } + } + +fail: + if (Credential) + { + CredFree(Credential); + } + free(TargetName); + free(UserName); + free(TargetNameW); + free(ServerHostNameW); + free(ParsedUserNameW); + free(ParsedDomainW); + free(PasswordNullTerminatedW); + return; +} + +void WINAPI AddDefaultSettings(rdpSettings* settings) +{ + AddDefaultSettings_I(settings, FreeRDP_ServerHostname, FreeRDP_Username, FreeRDP_Domain, + FreeRDP_Password); + AddDefaultSettings_I(settings, FreeRDP_GatewayHostname, FreeRDP_GatewayUsername, + FreeRDP_GatewayDomain, FreeRDP_GatewayPassword); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.h new file mode 100644 index 0000000000000000000000000000000000000000..79ebfdd2e246da038ffe558ed57a0f66a5c01d78 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_defaults.h @@ -0,0 +1,28 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2022 Stefan Koell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_DEFAULTS_H +#define FREERDP_CLIENT_WIN_DEFAULTS_H + +#include +#include +#include + +FREERDP_API void WINAPI AddDefaultSettings(_Inout_ rdpSettings* settings); + +#endif /* FREERDP_CLIENT_WIN_DEFAULTS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.c new file mode 100644 index 0000000000000000000000000000000000000000..e16b9e6c4b10af44139f35b447086a476169255a --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.c @@ -0,0 +1,967 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Event Handling + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include +#include + +#include "wf_client.h" + +#include "wf_gdi.h" +#include "wf_event.h" + +#include + +#include + +static HWND g_focus_hWnd = NULL; +static HWND g_main_hWnd = NULL; +static HWND g_parent_hWnd = NULL; + +#define RESIZE_MIN_DELAY 200 /* minimum delay in ms between two resizes */ + +static BOOL wf_scale_blt(wfContext* wfc, HDC hdc, int x, int y, int w, int h, HDC hdcSrc, int x1, + int y1, DWORD rop); +static BOOL wf_scale_mouse_event(wfContext* wfc, UINT16 flags, INT32 x, INT32 y); +#if (_WIN32_WINNT >= 0x0500) +static BOOL wf_scale_mouse_event_ex(wfContext* wfc, UINT16 flags, UINT16 buttonMask, INT32 x, + INT32 y); +#endif + +static BOOL g_flipping_in = FALSE; +static BOOL g_flipping_out = FALSE; + +static BOOL g_keystates[256] = { 0 }; + +static BOOL ctrl_down(void) +{ + return g_keystates[VK_CONTROL] || g_keystates[VK_LCONTROL] || g_keystates[VK_RCONTROL]; +} + +static BOOL alt_ctrl_down(void) +{ + const BOOL altDown = g_keystates[VK_MENU] || g_keystates[VK_LMENU] || g_keystates[VK_RMENU]; + return altDown && ctrl_down(); +} + +LRESULT CALLBACK wf_ll_kbd_proc(int nCode, WPARAM wParam, LPARAM lParam) +{ + DWORD ext_proc_id = 0; + + wfContext* wfc = NULL; + DWORD rdp_scancode; + BOOL keystate; + rdpInput* input; + PKBDLLHOOKSTRUCT p; + + DEBUG_KBD("Low-level keyboard hook, hWnd %X nCode %X wParam %X", g_focus_hWnd, nCode, wParam); + + if (g_flipping_in) + { + if (!alt_ctrl_down()) + g_flipping_in = FALSE; + + return CallNextHookEx(NULL, nCode, wParam, lParam); + } + + if (g_parent_hWnd && g_main_hWnd) + { + wfc = (wfContext*)GetWindowLongPtr(g_main_hWnd, GWLP_USERDATA); + GUITHREADINFO gui_thread_info; + gui_thread_info.cbSize = sizeof(GUITHREADINFO); + HWND fg_win_hwnd = GetForegroundWindow(); + DWORD fg_win_thread_id = GetWindowThreadProcessId(fg_win_hwnd, &ext_proc_id); + BOOL result = GetGUIThreadInfo(fg_win_thread_id, &gui_thread_info); + if (gui_thread_info.hwndFocus != wfc->hWndParent) + { + g_focus_hWnd = NULL; + return CallNextHookEx(NULL, nCode, wParam, lParam); + } + + g_focus_hWnd = g_main_hWnd; + } + + if (g_focus_hWnd && (nCode == HC_ACTION)) + { + switch (wParam) + { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + case WM_KEYUP: + case WM_SYSKEYUP: + if (!wfc) + wfc = (wfContext*)GetWindowLongPtr(g_focus_hWnd, GWLP_USERDATA); + p = (PKBDLLHOOKSTRUCT)lParam; + + if (!wfc || !p) + return 1; + + input = wfc->common.context.input; + rdp_scancode = MAKE_RDP_SCANCODE((BYTE)p->scanCode, p->flags & LLKHF_EXTENDED); + keystate = g_keystates[p->scanCode & 0xFF]; + + switch (wParam) + { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + g_keystates[p->scanCode & 0xFF] = TRUE; + break; + case WM_KEYUP: + case WM_SYSKEYUP: + default: + g_keystates[p->scanCode & 0xFF] = FALSE; + break; + } + DEBUG_KBD("keydown %d scanCode 0x%08lX flags 0x%08lX vkCode 0x%08lX", + (wParam == WM_KEYDOWN), p->scanCode, p->flags, p->vkCode); + + if (wfc->fullscreen_toggle && (p->vkCode == VK_RETURN || p->vkCode == VK_CANCEL)) + { + if (alt_ctrl_down()) + { + if (wParam == WM_KEYDOWN) + { + wf_toggle_fullscreen(wfc); + return 1; + } + } + } + + if (rdp_scancode == RDP_SCANCODE_NUMLOCK_EXTENDED) + { + /* Windows sends NumLock as extended - rdp doesn't */ + DEBUG_KBD("hack: NumLock (x45) should not be extended"); + rdp_scancode = RDP_SCANCODE_NUMLOCK; + } + else if (rdp_scancode == RDP_SCANCODE_NUMLOCK) + { + /* Windows sends Pause as if it was a RDP NumLock (handled above). + * It must however be sent as a one-shot Ctrl+NumLock */ + if (wParam == WM_KEYDOWN) + { + DEBUG_KBD("Pause, sent as Ctrl+NumLock"); + freerdp_input_send_keyboard_event_ex(input, TRUE, FALSE, + RDP_SCANCODE_LCONTROL); + freerdp_input_send_keyboard_event_ex(input, TRUE, FALSE, + RDP_SCANCODE_NUMLOCK); + freerdp_input_send_keyboard_event_ex(input, FALSE, FALSE, + RDP_SCANCODE_LCONTROL); + freerdp_input_send_keyboard_event_ex(input, FALSE, FALSE, + RDP_SCANCODE_NUMLOCK); + } + else + { + DEBUG_KBD("Pause up"); + } + + return 1; + } + else if (rdp_scancode == RDP_SCANCODE_RSHIFT_EXTENDED) + { + DEBUG_KBD("right shift (x36) should not be extended"); + rdp_scancode = RDP_SCANCODE_RSHIFT; + } + + freerdp_input_send_keyboard_event_ex(input, !(p->flags & LLKHF_UP), keystate, + rdp_scancode); + + if (p->vkCode == VK_NUMLOCK || p->vkCode == VK_CAPITAL || p->vkCode == VK_SCROLL || + p->vkCode == VK_KANA) + DEBUG_KBD( + "lock keys are processed on client side too to toggle their indicators"); + else + return 1; + + break; + default: + break; + } + } + + if (g_flipping_out) + { + if (!alt_ctrl_down()) + { + g_flipping_out = FALSE; + g_focus_hWnd = NULL; + } + } + + return CallNextHookEx(NULL, nCode, wParam, lParam); +} + +void wf_event_focus_in(wfContext* wfc) +{ + UINT16 syncFlags; + rdpInput* input; + POINT pt; + RECT rc; + input = wfc->common.context.input; + syncFlags = 0; + + if (GetKeyState(VK_NUMLOCK)) + syncFlags |= KBD_SYNC_NUM_LOCK; + + if (GetKeyState(VK_CAPITAL)) + syncFlags |= KBD_SYNC_CAPS_LOCK; + + if (GetKeyState(VK_SCROLL)) + syncFlags |= KBD_SYNC_SCROLL_LOCK; + + if (GetKeyState(VK_KANA)) + syncFlags |= KBD_SYNC_KANA_LOCK; + + input->FocusInEvent(input, syncFlags); + /* send pointer position if the cursor is currently inside our client area */ + GetCursorPos(&pt); + ScreenToClient(wfc->hwnd, &pt); + GetClientRect(wfc->hwnd, &rc); + + if (pt.x >= rc.left && pt.x < rc.right && pt.y >= rc.top && pt.y < rc.bottom) + input->MouseEvent(input, PTR_FLAGS_MOVE, (UINT16)pt.x, (UINT16)pt.y); +} + +static BOOL wf_event_process_WM_MOUSEWHEEL(wfContext* wfc, HWND hWnd, UINT Msg, WPARAM wParam, + LPARAM lParam, BOOL horizontal, INT32 x, INT32 y) +{ + int delta; + UINT16 flags = 0; + rdpInput* input; + + WINPR_ASSERT(wfc); + + input = wfc->common.context.input; + WINPR_ASSERT(input); + + DefWindowProc(hWnd, Msg, wParam, lParam); + delta = ((signed short)HIWORD(wParam)); /* GET_WHEEL_DELTA_WPARAM(wParam); */ + + if (horizontal) + flags |= PTR_FLAGS_HWHEEL; + else + flags |= PTR_FLAGS_WHEEL; + + if (delta < 0) + { + flags |= PTR_FLAGS_WHEEL_NEGATIVE; + /* 9bit twos complement, delta already negative */ + delta = 0x100 + delta; + } + + flags |= delta; + return wf_scale_mouse_event(wfc, flags, x, y); +} + +static void wf_sizing(wfContext* wfc, WPARAM wParam, LPARAM lParam) +{ + rdpSettings* settings = wfc->common.context.settings; + // Holding the CTRL key down while resizing the window will force the desktop aspect ratio. + LPRECT rect; + + if ((freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) && + ctrl_down()) + { + rect = (LPRECT)wParam; + + switch (lParam) + { + case WMSZ_LEFT: + case WMSZ_RIGHT: + case WMSZ_BOTTOMRIGHT: + // Adjust height + rect->bottom = + rect->top + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) * + (rect->right - rect->left) / + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + break; + + case WMSZ_TOP: + case WMSZ_BOTTOM: + case WMSZ_TOPRIGHT: + // Adjust width + rect->right = + rect->left + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) * + (rect->bottom - rect->top) / + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + break; + + case WMSZ_BOTTOMLEFT: + case WMSZ_TOPLEFT: + // adjust width + rect->left = + rect->right - (freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) * + (rect->bottom - rect->top) / + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + break; + } + } +} + +static void wf_send_resize(wfContext* wfc) +{ + RECT windowRect; + int targetWidth = wfc->client_width; + int targetHeight = wfc->client_height; + rdpSettings* settings = wfc->common.context.settings; + + if (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate) && wfc->disp != NULL) + { + if (GetTickCount64() - wfc->lastSentDate > RESIZE_MIN_DELAY) + { + if (wfc->fullscreen) + { + GetWindowRect(wfc->hwnd, &windowRect); + targetWidth = windowRect.right - windowRect.left; + targetHeight = windowRect.bottom - windowRect.top; + } + if (freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth) != targetWidth || + freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight) != targetHeight) + { + DISPLAY_CONTROL_MONITOR_LAYOUT layout = { 0 }; + + layout.Flags = DISPLAY_CONTROL_MONITOR_PRIMARY; + layout.Top = layout.Left = 0; + layout.Width = targetWidth; + layout.Height = targetHeight; + layout.Orientation = + freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation); + layout.DesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + layout.DeviceScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + layout.PhysicalWidth = targetWidth; + layout.PhysicalHeight = targetHeight; + + if (IFCALLRESULT(CHANNEL_RC_OK, wfc->disp->SendMonitorLayout, wfc->disp, 1, + &layout) != CHANNEL_RC_OK) + { + WLog_ERR("", "SendMonitorLayout failed."); + } + (void)freerdp_settings_set_uint32(settings, FreeRDP_SmartSizingWidth, targetWidth); + (void)freerdp_settings_set_uint32(settings, FreeRDP_SmartSizingHeight, + targetHeight); + } + wfc->lastSentDate = GetTickCount64(); + } + } +} + +LRESULT CALLBACK wf_event_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) +{ + HDC hdc = { 0 }; + PAINTSTRUCT ps = { 0 }; + BOOL processed = FALSE; + RECT windowRect = { 0 }; + MINMAXINFO* minmax = NULL; + SCROLLINFO si = { 0 }; + processed = TRUE; + LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); + wfContext* wfc = (wfContext*)ptr; + + if (wfc != NULL) + { + rdpInput* input = wfc->common.context.input; + rdpSettings* settings = wfc->common.context.settings; + + if (!g_parent_hWnd && wfc->hWndParent) + g_parent_hWnd = wfc->hWndParent; + + if (!g_main_hWnd) + g_main_hWnd = wfc->hwnd; + + switch (Msg) + { + case WM_MOVE: + if (!wfc->disablewindowtracking) + { + int x = (int)(short)LOWORD(lParam); + int y = (int)(short)HIWORD(lParam); + wfc->client_x = x; + wfc->client_y = y; + } + + break; + + case WM_GETMINMAXINFO: + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate))) + { + processed = FALSE; + } + else + { + // Set maximum window size for resizing + minmax = (MINMAXINFO*)lParam; + + // always use the last determined canvas diff, because it could be + // that the window is minimized when this gets called + // wf_update_canvas_diff(wfc); + + if (!wfc->fullscreen) + { + // add window decoration + minmax->ptMaxTrackSize.x = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) + + wfc->diff.x; + minmax->ptMaxTrackSize.y = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) + + wfc->diff.y; + } + } + + break; + + case WM_SIZING: + wf_sizing(wfc, lParam, wParam); + break; + + case WM_SIZE: + GetWindowRect(wfc->hwnd, &windowRect); + + if (!wfc->fullscreen) + { + wfc->client_width = LOWORD(lParam); + wfc->client_height = HIWORD(lParam); + wfc->client_x = windowRect.left; + wfc->client_y = windowRect.top; + } + else + { + wfc->wasMaximized = TRUE; + wf_send_resize(wfc); + } + + if (wfc->client_width && wfc->client_height) + { + wf_size_scrollbars(wfc, LOWORD(lParam), HIWORD(lParam)); + + // Workaround: when the window is maximized, the call to "ShowScrollBars" + // returns TRUE but has no effect. + if (wParam == SIZE_MAXIMIZED && !wfc->fullscreen) + { + SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, windowRect.right - windowRect.left, + windowRect.bottom - windowRect.top, + SWP_NOMOVE | SWP_FRAMECHANGED); + wfc->wasMaximized = TRUE; + wf_send_resize(wfc); + } + else if (wParam == SIZE_RESTORED && !wfc->fullscreen && wfc->wasMaximized) + { + wfc->wasMaximized = FALSE; + wf_send_resize(wfc); + } + else if (wParam == SIZE_MINIMIZED) + { + g_focus_hWnd = NULL; + } + } + + break; + + case WM_EXITSIZEMOVE: + wf_size_scrollbars(wfc, wfc->client_width, wfc->client_height); + wf_send_resize(wfc); + break; + + case WM_ERASEBKGND: + /* Say we handled it - prevents flickering */ + return (LRESULT)1; + + case WM_PAINT: + { + hdc = BeginPaint(hWnd, &ps); + const int x = ps.rcPaint.left; + const int y = ps.rcPaint.top; + const int w = ps.rcPaint.right - ps.rcPaint.left + 1; + const int h = ps.rcPaint.bottom - ps.rcPaint.top + 1; + wf_scale_blt(wfc, hdc, x, y, w, h, wfc->primary->hdc, + x - wfc->offset_x + wfc->xCurrentScroll, + y - wfc->offset_y + wfc->yCurrentScroll, SRCCOPY); + EndPaint(hWnd, &ps); + } + break; +#if (_WIN32_WINNT >= 0x0500) + + case WM_XBUTTONDOWN: + wf_scale_mouse_event_ex(wfc, PTR_XFLAGS_DOWN, GET_XBUTTON_WPARAM(wParam), + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; + + case WM_XBUTTONUP: + wf_scale_mouse_event_ex(wfc, 0, GET_XBUTTON_WPARAM(wParam), + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; +#endif + + case WM_MBUTTONDOWN: + wf_scale_mouse_event(wfc, PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON3, + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; + + case WM_MBUTTONUP: + wf_scale_mouse_event(wfc, PTR_FLAGS_BUTTON3, GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; + + case WM_LBUTTONDOWN: + wf_scale_mouse_event(wfc, PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON1, + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + SetCapture(wfc->hwnd); + break; + + case WM_LBUTTONUP: + wf_scale_mouse_event(wfc, PTR_FLAGS_BUTTON1, GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + ReleaseCapture(); + break; + + case WM_RBUTTONDOWN: + wf_scale_mouse_event(wfc, PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON2, + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; + + case WM_RBUTTONUP: + wf_scale_mouse_event(wfc, PTR_FLAGS_BUTTON2, GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; + + case WM_MOUSEMOVE: + wf_scale_mouse_event(wfc, PTR_FLAGS_MOVE, GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; +#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) + + case WM_MOUSEWHEEL: + wf_event_process_WM_MOUSEWHEEL(wfc, hWnd, Msg, wParam, lParam, FALSE, + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; +#endif +#if (_WIN32_WINNT >= 0x0600) + + case WM_MOUSEHWHEEL: + wf_event_process_WM_MOUSEWHEEL(wfc, hWnd, Msg, wParam, lParam, TRUE, + GET_X_LPARAM(lParam) - wfc->offset_x, + GET_Y_LPARAM(lParam) - wfc->offset_y); + break; +#endif + + case WM_SETCURSOR: + if (LOWORD(lParam) == HTCLIENT) + SetCursor(wfc->cursor); + else + DefWindowProc(hWnd, Msg, wParam, lParam); + + break; + + case WM_HSCROLL: + { + int xDelta; // xDelta = new_pos - current_pos + int xNewPos; // new position + int yDelta = 0; + + switch (LOWORD(wParam)) + { + // User clicked the scroll bar shaft left of the scroll box. + case SB_PAGEUP: + xNewPos = wfc->xCurrentScroll - 50; + break; + + // User clicked the scroll bar shaft right of the scroll box. + case SB_PAGEDOWN: + xNewPos = wfc->xCurrentScroll + 50; + break; + + // User clicked the left arrow. + case SB_LINEUP: + xNewPos = wfc->xCurrentScroll - 5; + break; + + // User clicked the right arrow. + case SB_LINEDOWN: + xNewPos = wfc->xCurrentScroll + 5; + break; + + // User dragged the scroll box. + case SB_THUMBPOSITION: + xNewPos = HIWORD(wParam); + break; + + // user is dragging the scrollbar + case SB_THUMBTRACK: + xNewPos = HIWORD(wParam); + break; + + default: + xNewPos = wfc->xCurrentScroll; + } + + // New position must be between 0 and the screen width. + xNewPos = MAX(0, xNewPos); + xNewPos = MIN(wfc->xMaxScroll, xNewPos); + + // If the current position does not change, do not scroll. + if (xNewPos == wfc->xCurrentScroll) + break; + + // Determine the amount scrolled (in pixels). + xDelta = xNewPos - wfc->xCurrentScroll; + // Reset the current scroll position. + wfc->xCurrentScroll = xNewPos; + // Scroll the window. (The system repaints most of the + // client area when ScrollWindowEx is called; however, it is + // necessary to call UpdateWindow in order to repaint the + // rectangle of pixels that were invalidated.) + ScrollWindowEx(wfc->hwnd, -xDelta, -yDelta, (CONST RECT*)NULL, (CONST RECT*)NULL, + (HRGN)NULL, (PRECT)NULL, SW_INVALIDATE); + UpdateWindow(wfc->hwnd); + // Reset the scroll bar. + si.cbSize = sizeof(si); + si.fMask = SIF_POS; + si.nPos = wfc->xCurrentScroll; + SetScrollInfo(wfc->hwnd, SB_HORZ, &si, TRUE); + } + break; + + case WM_VSCROLL: + { + int xDelta = 0; + int yDelta; // yDelta = new_pos - current_pos + int yNewPos; // new position + + switch (LOWORD(wParam)) + { + // User clicked the scroll bar shaft above the scroll box. + case SB_PAGEUP: + yNewPos = wfc->yCurrentScroll - 50; + break; + + // User clicked the scroll bar shaft below the scroll box. + case SB_PAGEDOWN: + yNewPos = wfc->yCurrentScroll + 50; + break; + + // User clicked the top arrow. + case SB_LINEUP: + yNewPos = wfc->yCurrentScroll - 5; + break; + + // User clicked the bottom arrow. + case SB_LINEDOWN: + yNewPos = wfc->yCurrentScroll + 5; + break; + + // User dragged the scroll box. + case SB_THUMBPOSITION: + yNewPos = HIWORD(wParam); + break; + + // user is dragging the scrollbar + case SB_THUMBTRACK: + yNewPos = HIWORD(wParam); + break; + + default: + yNewPos = wfc->yCurrentScroll; + } + + // New position must be between 0 and the screen height. + yNewPos = MAX(0, yNewPos); + yNewPos = MIN(wfc->yMaxScroll, yNewPos); + + // If the current position does not change, do not scroll. + if (yNewPos == wfc->yCurrentScroll) + break; + + // Determine the amount scrolled (in pixels). + yDelta = yNewPos - wfc->yCurrentScroll; + // Reset the current scroll position. + wfc->yCurrentScroll = yNewPos; + // Scroll the window. (The system repaints most of the + // client area when ScrollWindowEx is called; however, it is + // necessary to call UpdateWindow in order to repaint the + // rectangle of pixels that were invalidated.) + ScrollWindowEx(wfc->hwnd, -xDelta, -yDelta, (CONST RECT*)NULL, (CONST RECT*)NULL, + (HRGN)NULL, (PRECT)NULL, SW_INVALIDATE); + UpdateWindow(wfc->hwnd); + // Reset the scroll bar. + si.cbSize = sizeof(si); + si.fMask = SIF_POS; + si.nPos = wfc->yCurrentScroll; + SetScrollInfo(wfc->hwnd, SB_VERT, &si, TRUE); + } + break; + + case WM_SYSCOMMAND: + { + if (wParam == SYSCOMMAND_ID_SMARTSIZING) + { + HMENU hMenu = GetSystemMenu(wfc->hwnd, FALSE); + const BOOL rc = freerdp_settings_get_bool(settings, FreeRDP_SmartSizing); + (void)freerdp_settings_set_bool(settings, FreeRDP_SmartSizing, !rc); + CheckMenuItem(hMenu, SYSCOMMAND_ID_SMARTSIZING, + freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) + ? MF_CHECKED + : MF_UNCHECKED); + if (!freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + { + SetWindowPos(wfc->hwnd, HWND_TOP, -1, -1, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) + + wfc->diff.x, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) + + wfc->diff.y, + SWP_NOMOVE); + } + else + { + wf_size_scrollbars(wfc, wfc->client_width, wfc->client_height); + wf_send_resize(wfc); + } + } + else if (wParam == SYSCOMMAND_ID_REQUEST_CONTROL) + { + freerdp_client_encomsp_set_control(wfc->common.encomsp, TRUE); + } + else + { + processed = FALSE; + } + } + break; + + default: + processed = FALSE; + break; + } + } + else + { + processed = FALSE; + } + + if (processed) + return 0; + + switch (Msg) + { + case WM_DESTROY: + PostQuitMessage(WM_QUIT); + break; + + case WM_SETFOCUS: + DEBUG_KBD("getting focus %X", hWnd); + + (void)freerdp_settings_set_bool(wfc->common.context.settings, FreeRDP_SuspendInput, + FALSE); + + if (alt_ctrl_down()) + g_flipping_in = TRUE; + + g_focus_hWnd = hWnd; + freerdp_set_focus(wfc->common.context.instance); + break; + + case WM_KILLFOCUS: + (void)freerdp_settings_set_bool(wfc->common.context.settings, FreeRDP_SuspendInput, + TRUE); + + if (g_focus_hWnd == hWnd && wfc && !wfc->fullscreen) + { + DEBUG_KBD("losing focus %X", hWnd); + + if (alt_ctrl_down()) + g_flipping_out = TRUE; + else + g_focus_hWnd = NULL; + } + + break; + + case WM_ACTIVATE: + { + int activate = (int)(short)LOWORD(wParam); + BOOL minimized_flag = (BOOL)HIWORD(wParam); + + if (activate != WA_INACTIVE && !minimized_flag) + { + if (alt_ctrl_down()) + g_flipping_in = TRUE; + + g_focus_hWnd = hWnd; + } + else + { + if (alt_ctrl_down()) + g_flipping_out = TRUE; + else + g_focus_hWnd = NULL; + } + } + + default: + return DefWindowProc(hWnd, Msg, wParam, lParam); + break; + } + + return 0; +} + +BOOL wf_scale_blt(wfContext* wfc, HDC hdc, int x, int y, int w, int h, HDC hdcSrc, int x1, int y1, + DWORD rop) +{ + UINT32 ww, wh, dw, dh; + WINPR_ASSERT(wfc); + + rdpSettings* settings = wfc->common.context.settings; + WINPR_ASSERT(settings); + + if (!wfc->client_width) + wfc->client_width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + + if (!wfc->client_height) + wfc->client_height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + ww = wfc->client_width; + wh = wfc->client_height; + dw = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + dh = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!ww) + ww = dw; + + if (!wh) + wh = dh; + + if (wfc->fullscreen || !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + (ww == dw && wh == dh)) + { + return BitBlt(hdc, x, y, w, h, wfc->primary->hdc, x1, y1, SRCCOPY); + } + else + { + SetStretchBltMode(hdc, HALFTONE); + SetBrushOrgEx(hdc, 0, 0, NULL); + return StretchBlt(hdc, 0, 0, ww, wh, wfc->primary->hdc, 0, 0, dw, dh, SRCCOPY); + } + + return TRUE; +} + +static BOOL wf_scale_mouse_pos(wfContext* wfc, INT32 x, INT32 y, UINT16* px, UINT16* py) +{ + int ww, wh, dw, dh; + rdpSettings* settings; + + if (!wfc || !px || !py) + return FALSE; + + settings = wfc->common.context.settings; + + if (!settings) + return FALSE; + + if (!wfc->client_width) + wfc->client_width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + + if (!wfc->client_height) + wfc->client_height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + ww = wfc->client_width; + wh = wfc->client_height; + dw = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + dh = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || ((ww == dw) && (wh == dh))) + { + x += wfc->xCurrentScroll; + y += wfc->yCurrentScroll; + } + else + { + x = x * dw / ww + wfc->xCurrentScroll; + y = y * dh / wh + wfc->yCurrentScroll; + } + + *px = MIN(UINT16_MAX, MAX(0, x)); + *py = MIN(UINT16_MAX, MAX(0, y)); + + return TRUE; +} + +static BOOL wf_pub_mouse_event(wfContext* wfc, UINT16 flags, UINT16 x, UINT16 y) +{ + MouseEventEventArgs eventArgs = { 0 }; + + eventArgs.flags = flags; + eventArgs.x = x; + eventArgs.y = y; + PubSub_OnMouseEvent(wfc->common.context.pubSub, &wfc->common.context, &eventArgs); + return TRUE; +} + +static BOOL wf_scale_mouse_event(wfContext* wfc, UINT16 flags, INT32 x, INT32 y) +{ + UINT16 px, py; + + WINPR_ASSERT(wfc); + + if (!wf_scale_mouse_pos(wfc, x, y, &px, &py)) + return FALSE; + + if (freerdp_client_send_button_event(&wfc->common, FALSE, flags, px, py)) + return FALSE; + + return wf_pub_mouse_event(wfc, flags, px, py); +} + +#if (_WIN32_WINNT >= 0x0500) +static BOOL wf_scale_mouse_event_ex(wfContext* wfc, UINT16 flags, UINT16 buttonMask, INT32 x, + INT32 y) +{ + UINT16 px, py; + + WINPR_ASSERT(wfc); + + if (buttonMask & XBUTTON1) + flags |= PTR_XFLAGS_BUTTON1; + + if (buttonMask & XBUTTON2) + flags |= PTR_XFLAGS_BUTTON2; + + if (!wf_scale_mouse_pos(wfc, x, y, &px, &py)) + return FALSE; + + if (freerdp_client_send_extended_button_event(&wfc->common, FALSE, flags, px, py)) + return FALSE; + + return wf_pub_mouse_event(wfc, flags, px, py); +} +#endif diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.h new file mode 100644 index 0000000000000000000000000000000000000000..f879f873a0208bd7388e49a4bb65d197ffbc0c1b --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_event.h @@ -0,0 +1,43 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Event Handling + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_EVENT_H +#define FREERDP_CLIENT_WIN_EVENT_H + +#include "wf_client.h" +#include + +LRESULT CALLBACK wf_ll_kbd_proc(int nCode, WPARAM wParam, LPARAM lParam); +LRESULT CALLBACK wf_event_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); + +void wf_event_focus_in(wfContext* wfc); + +#define KBD_TAG CLIENT_TAG("windows") +#ifdef WITH_DEBUG_KBD +#define DEBUG_KBD(...) WLog_DBG(KBD_TAG, __VA_ARGS__) +#else +#define DEBUG_KBD(...) \ + do \ + { \ + } while (0) +#endif + +#endif /* FREERDP_CLIENT_WIN_EVENT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.c new file mode 100644 index 0000000000000000000000000000000000000000..f91047ce2b25db43272993a970889464ecf4e83d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.c @@ -0,0 +1,730 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Float Bar + * + * Copyright 2013 Zhang Zhaolong + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "wf_client.h" +#include "wf_floatbar.h" + +#include "resource/resource.h" +#include "wf_gdi.h" +#ifdef _MSC_VER +#pragma comment(lib, "Msimg32.lib") +#endif + +#define TAG CLIENT_TAG("windows.floatbar") + +/* TIMERs */ +#define TIMER_HIDE 1 +#define TIMER_ANIMAT_SHOW 2 +#define TIMER_ANIMAT_HIDE 3 + +/* Button Type */ +#define BUTTON_LOCKPIN 0 +#define BUTTON_MINIMIZE 1 +#define BUTTON_RESTORE 2 +#define BUTTON_CLOSE 3 +#define BTN_MAX 4 + +/* bmp size */ +#define BACKGROUND_W 576 +#define BACKGROUND_H 27 +#define BUTTON_OFFSET 5 +#define BUTTON_Y 2 +#define BUTTON_WIDTH 23 +#define BUTTON_HEIGHT 21 +#define BUTTON_SPACING 1 + +#define LOCK_X (BACKGROUND_H + BUTTON_OFFSET) +#define CLOSE_X ((BACKGROUND_W - (BACKGROUND_H + BUTTON_OFFSET)) - BUTTON_WIDTH) +#define RESTORE_X (CLOSE_X - (BUTTON_WIDTH + BUTTON_SPACING)) +#define MINIMIZE_X (RESTORE_X - (BUTTON_WIDTH + BUTTON_SPACING)) +#define TEXT_X (BACKGROUND_H + ((BUTTON_WIDTH + BUTTON_SPACING) * 3) + 5) + +typedef struct +{ + wfFloatBar* floatbar; + int type; + int x, y, h, w; + int active; + HBITMAP bmp; + HBITMAP bmp_act; + + /* Lock Specified */ + HBITMAP locked_bmp; + HBITMAP locked_bmp_act; + HBITMAP unlocked_bmp; + HBITMAP unlocked_bmp_act; +} Button; + +struct s_FloatBar +{ + HINSTANCE root_window; + DWORD flags; + HWND parent; + HWND hwnd; + RECT rect; + LONG width; + LONG height; + LONG offset; + wfContext* wfc; + Button* buttons[BTN_MAX]; + BOOL shown; + BOOL locked; + HDC hdcmem; + RECT textRect; + UINT_PTR animating; +}; + +static BOOL floatbar_kill_timers(wfFloatBar* floatbar) +{ + UINT_PTR timers[] = { TIMER_HIDE, TIMER_ANIMAT_HIDE, TIMER_ANIMAT_SHOW }; + + if (!floatbar) + return FALSE; + + for (size_t x = 0; x < ARRAYSIZE(timers); x++) + KillTimer(floatbar->hwnd, timers[x]); + + floatbar->animating = 0; + return TRUE; +} + +static BOOL floatbar_animation(wfFloatBar* const floatbar, const BOOL show) +{ + UINT_PTR timer = show ? TIMER_ANIMAT_SHOW : TIMER_ANIMAT_HIDE; + + if (!floatbar) + return FALSE; + + if (floatbar->shown == show) + return TRUE; + + if (floatbar->animating == timer) + return TRUE; + + floatbar->animating = timer; + + if (SetTimer(floatbar->hwnd, timer, USER_TIMER_MINIMUM, NULL) == 0) + { + DWORD err = GetLastError(); + WLog_ERR(TAG, "SetTimer failed with %08" PRIx32, err); + return FALSE; + } + + return TRUE; +} + +static BOOL floatbar_trigger_hide(wfFloatBar* floatbar) +{ + if (!floatbar_kill_timers(floatbar)) + return FALSE; + + if (!floatbar->locked && floatbar->shown) + { + if (SetTimer(floatbar->hwnd, TIMER_HIDE, 3000, NULL) == 0) + { + DWORD err = GetLastError(); + WLog_ERR(TAG, "SetTimer failed with %08" PRIx32, err); + return FALSE; + } + } + + return TRUE; +} + +static BOOL floatbar_hide(wfFloatBar* floatbar) +{ + if (!floatbar_kill_timers(floatbar)) + return FALSE; + + floatbar->offset = floatbar->height - 2; + + if (!MoveWindow(floatbar->hwnd, floatbar->rect.left, -floatbar->offset, floatbar->width, + floatbar->height, TRUE)) + { + DWORD err = GetLastError(); + WLog_ERR(TAG, "MoveWindow failed with %08" PRIx32, err); + return FALSE; + } + + floatbar->shown = FALSE; + + if (!floatbar_trigger_hide(floatbar)) + return FALSE; + + return TRUE; +} + +static BOOL floatbar_show(wfFloatBar* floatbar) +{ + if (!floatbar_kill_timers(floatbar)) + return FALSE; + + floatbar->offset = 0; + + if (!MoveWindow(floatbar->hwnd, floatbar->rect.left, -floatbar->offset, floatbar->width, + floatbar->height, TRUE)) + { + DWORD err = GetLastError(); + WLog_ERR(TAG, "MoveWindow failed with %08" PRIx32, err); + return FALSE; + } + + floatbar->shown = TRUE; + + if (!floatbar_trigger_hide(floatbar)) + return FALSE; + + return TRUE; +} + +static BOOL button_set_locked(Button* button, BOOL locked) +{ + if (locked) + { + button->bmp = button->locked_bmp; + button->bmp_act = button->locked_bmp_act; + } + else + { + button->bmp = button->unlocked_bmp; + button->bmp_act = button->unlocked_bmp_act; + } + + InvalidateRect(button->floatbar->hwnd, NULL, FALSE); + UpdateWindow(button->floatbar->hwnd); + return TRUE; +} + +static BOOL update_locked_state(wfFloatBar* floatbar) +{ + Button* button; + + if (!floatbar) + return FALSE; + + button = floatbar->buttons[3]; + + if (!button_set_locked(button, floatbar->locked)) + return FALSE; + + return TRUE; +} + +static int button_hit(Button* const button) +{ + wfFloatBar* const floatbar = button->floatbar; + + switch (button->type) + { + case BUTTON_LOCKPIN: + floatbar->locked = !floatbar->locked; + update_locked_state(floatbar); + break; + + case BUTTON_MINIMIZE: + ShowWindow(floatbar->parent, SW_MINIMIZE); + break; + + case BUTTON_RESTORE: + wf_toggle_fullscreen(floatbar->wfc); + break; + + case BUTTON_CLOSE: + SendMessage(floatbar->parent, WM_DESTROY, 0, 0); + break; + + default: + return 0; + } + + return 0; +} + +static int button_paint(const Button* const button, const HDC hdc) +{ + if (button != NULL) + { + wfFloatBar* floatbar = button->floatbar; + BLENDFUNCTION bf; + SelectObject(floatbar->hdcmem, button->active ? button->bmp_act : button->bmp); + bf.BlendOp = AC_SRC_OVER; + bf.BlendFlags = 0; + bf.SourceConstantAlpha = 255; + bf.AlphaFormat = AC_SRC_ALPHA; + AlphaBlend(hdc, button->x, button->y, button->w, button->h, floatbar->hdcmem, 0, 0, + button->w, button->h, bf); + } + + return 0; +} + +static Button* floatbar_create_button(wfFloatBar* const floatbar, const int type, const int resid, + const int resid_act, const int x, const int y, const int h, + const int w) +{ + Button* button = (Button*)calloc(1, sizeof(Button)); + + if (!button) + return NULL; + + button->floatbar = floatbar; + button->type = type; + button->x = x; + button->y = y; + button->w = w; + button->h = h; + button->active = FALSE; + button->bmp = (HBITMAP)LoadImage(floatbar->root_window, MAKEINTRESOURCE(resid), IMAGE_BITMAP, 0, + 0, LR_DEFAULTCOLOR); + button->bmp_act = (HBITMAP)LoadImage(floatbar->root_window, MAKEINTRESOURCE(resid_act), + IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR); + return button; +} + +static Button* floatbar_create_lock_button(wfFloatBar* const floatbar, const int unlock_resid, + const int unlock_resid_act, const int lock_resid, + const int lock_resid_act, const int x, const int y, + const int h, const int w) +{ + Button* button = floatbar_create_button(floatbar, BUTTON_LOCKPIN, unlock_resid, + unlock_resid_act, x, y, h, w); + + if (!button) + return NULL; + + button->unlocked_bmp = button->bmp; + button->unlocked_bmp_act = button->bmp_act; + button->locked_bmp = (HBITMAP)LoadImage(floatbar->wfc->hInstance, MAKEINTRESOURCE(lock_resid), + IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR); + button->locked_bmp_act = + (HBITMAP)LoadImage(floatbar->wfc->hInstance, MAKEINTRESOURCE(lock_resid_act), IMAGE_BITMAP, + 0, 0, LR_DEFAULTCOLOR); + return button; +} + +static Button* floatbar_get_button(const wfFloatBar* const floatbar, const int x, const int y) +{ + if ((y > BUTTON_Y) && (y < BUTTON_Y + BUTTON_HEIGHT)) + { + for (int i = 0; i < BTN_MAX; i++) + { + if ((floatbar->buttons[i] != NULL) && (x > floatbar->buttons[i]->x) && + (x < floatbar->buttons[i]->x + floatbar->buttons[i]->w)) + { + return floatbar->buttons[i]; + } + } + } + + return NULL; +} + +static BOOL floatbar_paint(wfFloatBar* const floatbar, const HDC hdc) +{ + HPEN hpen; + HGDIOBJECT orig; + /* paint background */ + GRADIENT_RECT gradientRect = { 0, 1 }; + COLORREF rgbTop = RGB(117, 154, 198); + COLORREF rgbBottom = RGB(6, 55, 120); + const int top = 0; + int left = 0; + int bottom = BACKGROUND_H - 1; + int right = BACKGROUND_W - 1; + const int angleOffset = BACKGROUND_H - 1; + TRIVERTEX triVertext[2] = { { left, top, GetRValue(rgbTop) << 8, GetGValue(rgbTop) << 8, + GetBValue(rgbTop) << 8, 0x0000 }, + { right, bottom, GetRValue(rgbBottom) << 8, + GetGValue(rgbBottom) << 8, GetBValue(rgbBottom) << 8, 0x0000 } }; + + if (!floatbar) + return FALSE; + + GradientFill(hdc, triVertext, 2, &gradientRect, 1, GRADIENT_FILL_RECT_V); + /* paint shadow */ + hpen = CreatePen(PS_SOLID, 1, RGB(71, 71, 71)); + orig = SelectObject(hdc, hpen); + MoveToEx(hdc, left, top, NULL); + LineTo(hdc, left + angleOffset, bottom); + LineTo(hdc, right - angleOffset, bottom); + LineTo(hdc, right + 1, top - 1); + DeleteObject(hpen); + hpen = CreatePen(PS_SOLID, 1, RGB(107, 141, 184)); + SelectObject(hdc, hpen); + left += 1; + bottom -= 1; + right -= 1; + MoveToEx(hdc, left, top, NULL); + LineTo(hdc, left + (angleOffset - 1), bottom); + LineTo(hdc, right - (angleOffset - 1), bottom); + LineTo(hdc, right + 1, top - 1); + DeleteObject(hpen); + SelectObject(hdc, orig); + DrawText(hdc, floatbar->wfc->window_title, wcslen(floatbar->wfc->window_title), + &floatbar->textRect, + DT_CENTER | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX | DT_SINGLELINE); + + /* paint buttons */ + + for (int i = 0; i < BTN_MAX; i++) + button_paint(floatbar->buttons[i], hdc); + + return TRUE; +} + +static LRESULT CALLBACK floatbar_proc(const HWND hWnd, const UINT Msg, const WPARAM wParam, + const LPARAM lParam) +{ + static int dragging = FALSE; + static int lbtn_dwn = FALSE; + static int btn_dwn_x = 0; + static wfFloatBar* floatbar; + static TRACKMOUSEEVENT tme; + PAINTSTRUCT ps; + Button* button; + HDC hdc; + int pos_x; + int pos_y; + NONCLIENTMETRICS ncm; + int xScreen = GetSystemMetrics(SM_CXSCREEN); + + switch (Msg) + { + case WM_CREATE: + floatbar = ((wfFloatBar*)((CREATESTRUCT*)lParam)->lpCreateParams); + floatbar->hwnd = hWnd; + GetWindowRect(floatbar->hwnd, &floatbar->rect); + floatbar->width = floatbar->rect.right - floatbar->rect.left; + floatbar->height = floatbar->rect.bottom - floatbar->rect.top; + hdc = GetDC(hWnd); + floatbar->hdcmem = CreateCompatibleDC(hdc); + ReleaseDC(hWnd, hdc); + tme.cbSize = sizeof(TRACKMOUSEEVENT); + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hWnd; + tme.dwHoverTime = HOVER_DEFAULT; + // Use caption font, white, draw transparent + GetClientRect(hWnd, &floatbar->textRect); + InflateRect(&floatbar->textRect, -TEXT_X, 0); + SetBkMode(hdc, TRANSPARENT); + SetTextColor(hdc, RGB(255, 255, 255)); + ncm.cbSize = sizeof(NONCLIENTMETRICS); + SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0); + SelectObject(hdc, CreateFontIndirect(&ncm.lfCaptionFont)); + floatbar_trigger_hide(floatbar); + break; + + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + floatbar_paint(floatbar, hdc); + EndPaint(hWnd, &ps); + break; + + case WM_LBUTTONDOWN: + pos_x = lParam & 0xffff; + pos_y = (lParam >> 16) & 0xffff; + button = floatbar_get_button(floatbar, pos_x, pos_y); + + if (!button) + { + SetCapture(hWnd); + dragging = TRUE; + btn_dwn_x = lParam & 0xffff; + } + else + lbtn_dwn = TRUE; + + break; + + case WM_LBUTTONUP: + pos_x = lParam & 0xffff; + pos_y = (lParam >> 16) & 0xffff; + ReleaseCapture(); + dragging = FALSE; + + if (lbtn_dwn) + { + button = floatbar_get_button(floatbar, pos_x, pos_y); + + if (button) + button_hit(button); + + lbtn_dwn = FALSE; + } + + break; + + case WM_MOUSEMOVE: + pos_x = lParam & 0xffff; + pos_y = (lParam >> 16) & 0xffff; + + if (!floatbar->locked) + floatbar_animation(floatbar, TRUE); + + if (dragging) + { + floatbar->rect.left = floatbar->rect.left + (lParam & 0xffff) - btn_dwn_x; + + if (floatbar->rect.left < 0) + floatbar->rect.left = 0; + else if (floatbar->rect.left > xScreen - floatbar->width) + floatbar->rect.left = xScreen - floatbar->width; + + MoveWindow(hWnd, floatbar->rect.left, 0, floatbar->width, floatbar->height, TRUE); + } + else + { + for (int i = 0; i < BTN_MAX; i++) + { + if (floatbar->buttons[i] != NULL) + { + floatbar->buttons[i]->active = FALSE; + } + } + + button = floatbar_get_button(floatbar, pos_x, pos_y); + + if (button) + button->active = TRUE; + + InvalidateRect(hWnd, NULL, FALSE); + UpdateWindow(hWnd); + } + + TrackMouseEvent(&tme); + break; + + case WM_CAPTURECHANGED: + dragging = FALSE; + break; + + case WM_MOUSELEAVE: + { + for (int i = 0; i < BTN_MAX; i++) + { + if (floatbar->buttons[i] != NULL) + { + floatbar->buttons[i]->active = FALSE; + } + } + + InvalidateRect(hWnd, NULL, FALSE); + UpdateWindow(hWnd); + floatbar_trigger_hide(floatbar); + break; + } + + case WM_TIMER: + switch (wParam) + { + case TIMER_HIDE: + floatbar_animation(floatbar, FALSE); + break; + + case TIMER_ANIMAT_SHOW: + { + floatbar->offset--; + MoveWindow(floatbar->hwnd, floatbar->rect.left, -floatbar->offset, + floatbar->width, floatbar->height, TRUE); + + if (floatbar->offset <= 0) + floatbar_show(floatbar); + + break; + } + + case TIMER_ANIMAT_HIDE: + { + floatbar->offset++; + MoveWindow(floatbar->hwnd, floatbar->rect.left, -floatbar->offset, + floatbar->width, floatbar->height, TRUE); + + if (floatbar->offset >= floatbar->height - 2) + floatbar_hide(floatbar); + + break; + } + + default: + break; + } + + break; + + case WM_DESTROY: + DeleteDC(floatbar->hdcmem); + PostQuitMessage(0); + break; + + default: + return DefWindowProc(hWnd, Msg, wParam, lParam); + } + + return 0; +} + +static BOOL floatbar_window_create(wfFloatBar* floatbar) +{ + WNDCLASSEX wnd_cls; + HWND barWnd; + HRGN hRgn; + POINT pt[4]; + RECT rect; + LONG x; + + if (!floatbar) + return FALSE; + + if (!GetWindowRect(floatbar->parent, &rect)) + return FALSE; + + x = (rect.right - rect.left - BACKGROUND_W) / 2; + wnd_cls.cbSize = sizeof(WNDCLASSEX); + wnd_cls.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; + wnd_cls.lpfnWndProc = floatbar_proc; + wnd_cls.cbClsExtra = 0; + wnd_cls.cbWndExtra = 0; + wnd_cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wnd_cls.hCursor = LoadCursor(floatbar->root_window, IDC_ARROW); + wnd_cls.hbrBackground = NULL; + wnd_cls.lpszMenuName = NULL; + wnd_cls.lpszClassName = L"floatbar"; + wnd_cls.hInstance = floatbar->root_window; + wnd_cls.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + RegisterClassEx(&wnd_cls); + barWnd = CreateWindowEx(WS_EX_TOPMOST, L"floatbar", L"floatbar", WS_CHILD, x, 0, BACKGROUND_W, + BACKGROUND_H, floatbar->parent, NULL, floatbar->root_window, floatbar); + + if (barWnd == NULL) + return FALSE; + + pt[0].x = 0; + pt[0].y = 0; + pt[1].x = BACKGROUND_W; + pt[1].y = 0; + pt[2].x = BACKGROUND_W - BACKGROUND_H; + pt[2].y = BACKGROUND_H; + pt[3].x = BACKGROUND_H; + pt[3].y = BACKGROUND_H; + hRgn = CreatePolygonRgn(pt, 4, ALTERNATE); + SetWindowRgn(barWnd, hRgn, TRUE); + return TRUE; +} + +void wf_floatbar_free(wfFloatBar* floatbar) +{ + if (!floatbar) + return; + + free(floatbar); +} + +wfFloatBar* wf_floatbar_new(wfContext* wfc, HINSTANCE window, DWORD flags) +{ + wfFloatBar* floatbar; + + /* Floatbar not enabled */ + if ((flags & 0x0001) == 0) + return NULL; + + if (!wfc) + return NULL; + + // TODO: Disable for remote app + floatbar = (wfFloatBar*)calloc(1, sizeof(wfFloatBar)); + + if (!floatbar) + return NULL; + + floatbar->root_window = window; + floatbar->flags = flags; + floatbar->wfc = wfc; + floatbar->locked = (flags & 0x0002) != 0; + floatbar->shown = (flags & 0x0006) != 0; /* If it is loked or shown show it */ + floatbar->hwnd = NULL; + floatbar->parent = wfc->hwnd; + floatbar->hdcmem = NULL; + + if (wfc->fullscreen_toggle) + { + floatbar->buttons[0] = + floatbar_create_button(floatbar, BUTTON_MINIMIZE, IDB_MINIMIZE, IDB_MINIMIZE_ACT, + MINIMIZE_X, BUTTON_Y, BUTTON_HEIGHT, BUTTON_WIDTH); + floatbar->buttons[1] = + floatbar_create_button(floatbar, BUTTON_RESTORE, IDB_RESTORE, IDB_RESTORE_ACT, + RESTORE_X, BUTTON_Y, BUTTON_HEIGHT, BUTTON_WIDTH); + } + else + { + floatbar->buttons[0] = NULL; + floatbar->buttons[1] = NULL; + } + + floatbar->buttons[2] = floatbar_create_button(floatbar, BUTTON_CLOSE, IDB_CLOSE, IDB_CLOSE_ACT, + CLOSE_X, BUTTON_Y, BUTTON_HEIGHT, BUTTON_WIDTH); + floatbar->buttons[3] = + floatbar_create_lock_button(floatbar, IDB_UNLOCK, IDB_UNLOCK_ACT, IDB_LOCK, IDB_LOCK_ACT, + LOCK_X, BUTTON_Y, BUTTON_HEIGHT, BUTTON_WIDTH); + + if (!floatbar_window_create(floatbar)) + goto fail; + + if (!update_locked_state(floatbar)) + goto fail; + + if (!wf_floatbar_toggle_fullscreen( + floatbar, freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_Fullscreen))) + goto fail; + + return floatbar; +fail: + wf_floatbar_free(floatbar); + return NULL; +} + +BOOL wf_floatbar_toggle_fullscreen(wfFloatBar* floatbar, BOOL fullscreen) +{ + BOOL show_fs, show_wn; + + if (!floatbar) + return FALSE; + + show_fs = (floatbar->flags & 0x0010) != 0; + show_wn = (floatbar->flags & 0x0020) != 0; + + if ((show_fs && fullscreen) || (show_wn && !fullscreen)) + { + ShowWindow(floatbar->hwnd, SW_SHOWNORMAL); + Sleep(10); + + if (floatbar->shown) + floatbar_show(floatbar); + else + floatbar_hide(floatbar); + } + else + { + ShowWindow(floatbar->hwnd, SW_HIDE); + } + + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.h new file mode 100644 index 0000000000000000000000000000000000000000..761eeb2a9e36f552044ddba14d94402abdfca19e --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_floatbar.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Float Bar + * + * Copyright 2013 Zhang Zhaolong + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_FLOATBAR_H +#define FREERDP_CLIENT_WIN_FLOATBAR_H + +#include + +typedef struct s_FloatBar wfFloatBar; +typedef struct wf_context wfContext; + +wfFloatBar* wf_floatbar_new(wfContext* wfc, HINSTANCE window, DWORD flags); +void wf_floatbar_free(wfFloatBar* floatbar); + +BOOL wf_floatbar_toggle_fullscreen(wfFloatBar* floatbar, BOOL fullscreen); + +#endif /* FREERDP_CLIENT_WIN_FLOATBAR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.c new file mode 100644 index 0000000000000000000000000000000000000000..4dc964709c87341db56fe34717bd08ef96d00681 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.c @@ -0,0 +1,848 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows GDI + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "wf_client.h" +#include "wf_graphics.h" +#include "wf_gdi.h" + +#define TAG CLIENT_TAG("windows.gdi") + +static const BYTE wf_rop2_table[] = { + R2_BLACK, /* 0 */ + R2_NOTMERGEPEN, /* DPon */ + R2_MASKNOTPEN, /* DPna */ + R2_NOTCOPYPEN, /* Pn */ + R2_MASKPENNOT, /* PDna */ + R2_NOT, /* Dn */ + R2_XORPEN, /* DPx */ + R2_NOTMASKPEN, /* DPan */ + R2_MASKPEN, /* DPa */ + R2_NOTXORPEN, /* DPxn */ + R2_NOP, /* D */ + R2_MERGENOTPEN, /* DPno */ + R2_COPYPEN, /* P */ + R2_MERGEPENNOT, /* PDno */ + R2_MERGEPEN, /* PDo */ + R2_WHITE, /* 1 */ +}; + +static BOOL wf_decode_color(wfContext* wfc, const UINT32 srcColor, COLORREF* color, UINT32* format) +{ + rdpGdi* gdi; + rdpSettings* settings; + UINT32 SrcFormat, DstFormat; + + if (!wfc) + return FALSE; + + gdi = wfc->common.context.gdi; + settings = wfc->common.context.settings; + + if (!gdi || !settings) + return FALSE; + + SrcFormat = gdi_get_pixel_format(freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth)); + + if (format) + *format = SrcFormat; + + switch (FreeRDPGetBitsPerPixel(gdi->dstFormat)) + { + case 32: + DstFormat = PIXEL_FORMAT_ABGR32; + break; + + case 24: + DstFormat = PIXEL_FORMAT_BGR24; + break; + + case 16: + DstFormat = PIXEL_FORMAT_RGB16; + break; + + default: + return FALSE; + } + + *color = FreeRDPConvertColor(srcColor, SrcFormat, DstFormat, &gdi->palette); + return TRUE; +} + +static BOOL wf_set_rop2(HDC hdc, int rop2) +{ + if ((rop2 < 0x01) || (rop2 > 0x10)) + { + WLog_ERR(TAG, "Unsupported ROP2: %d", rop2); + return FALSE; + } + + SetROP2(hdc, wf_rop2_table[rop2 - 1]); + return TRUE; +} + +static wfBitmap* wf_glyph_new(wfContext* wfc, GLYPH_DATA* glyph) +{ + wfBitmap* glyph_bmp; + glyph_bmp = wf_image_new(wfc, glyph->cx, glyph->cy, PIXEL_FORMAT_MONO, glyph->aj); + return glyph_bmp; +} + +static void wf_glyph_free(wfBitmap* glyph) +{ + wf_image_free(glyph); +} + +static BYTE* wf_glyph_convert(wfContext* wfc, int width, int height, const BYTE* data) +{ + const int src_bytes_per_row = (width + 7) / 8; + const int dst_bytes_per_row = src_bytes_per_row + (src_bytes_per_row % 2); + BYTE* cdata = (BYTE*)malloc(dst_bytes_per_row * height); + const BYTE* src = data; + + for (int indexy = 0; indexy < height; indexy++) + { + BYTE* dst = &cdata[1ull * indexy * dst_bytes_per_row]; + + for (int indexx = 0; indexx < dst_bytes_per_row; indexx++) + { + if (indexx < src_bytes_per_row) + *dst++ = *src++; + else + *dst++ = 0; + } + } + + return cdata; +} + +static HBRUSH wf_create_brush(wfContext* wfc, rdpBrush* brush, UINT32 color, UINT32 bpp) +{ + HBRUSH br; + LOGBRUSH lbr; + BYTE* cdata; + BYTE ipattern[8]; + HBITMAP pattern = NULL; + lbr.lbStyle = brush->style; + + if (lbr.lbStyle == BS_DIBPATTERN || lbr.lbStyle == BS_DIBPATTERN8X8 || + lbr.lbStyle == BS_DIBPATTERNPT) + lbr.lbColor = DIB_RGB_COLORS; + else + lbr.lbColor = color; + + if (lbr.lbStyle == BS_PATTERN || lbr.lbStyle == BS_PATTERN8X8) + { + if (brush->bpp > 1) + { + UINT32 format = gdi_get_pixel_format(bpp); + pattern = wf_create_dib(wfc, 8, 8, format, brush->data, NULL); + lbr.lbHatch = (ULONG_PTR)pattern; + } + else + { + for (UINT32 i = 0; i != 8; i++) + ipattern[7 - i] = brush->data[i]; + + cdata = wf_glyph_convert(wfc, 8, 8, ipattern); + pattern = CreateBitmap(8, 8, 1, 1, cdata); + lbr.lbHatch = (ULONG_PTR)pattern; + free(cdata); + } + } + else if (lbr.lbStyle == BS_HATCHED) + { + lbr.lbHatch = brush->hatch; + } + else + { + lbr.lbHatch = 0; + } + + br = CreateBrushIndirect(&lbr); + SetBrushOrgEx(wfc->drawing->hdc, brush->x, brush->y, NULL); + + if (pattern != NULL) + DeleteObject(pattern); + + return br; +} + +BOOL wf_scale_rect(wfContext* wfc, RECT* source) +{ + UINT32 ww, wh, dw, dh; + rdpSettings* settings; + + if (!wfc || !source || !wfc->common.context.settings) + return FALSE; + + settings = wfc->common.context.settings; + + if (!settings) + return FALSE; + + dw = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + dh = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!wfc->client_width) + wfc->client_width = dw; + + if (!wfc->client_height) + wfc->client_height = dh; + + ww = wfc->client_width; + wh = wfc->client_height; + + if (!ww) + ww = dw; + + if (!wh) + wh = dh; + + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_SmartSizing) && + (ww != dw || wh != dh)) + { + source->bottom = source->bottom * wh / dh + 20; + source->top = source->top * wh / dh - 20; + source->left = source->left * ww / dw - 20; + source->right = source->right * ww / dw + 20; + } + + source->bottom -= wfc->yCurrentScroll; + source->top -= wfc->yCurrentScroll; + source->left -= wfc->xCurrentScroll; + source->right -= wfc->xCurrentScroll; + return TRUE; +} + +void wf_invalidate_region(wfContext* wfc, UINT32 x, UINT32 y, UINT32 width, UINT32 height) +{ + RECT rect; + rdpGdi* gdi = wfc->common.context.gdi; + wfc->update_rect.left = x + wfc->offset_x; + wfc->update_rect.top = y + wfc->offset_y; + wfc->update_rect.right = wfc->update_rect.left + width; + wfc->update_rect.bottom = wfc->update_rect.top + height; + wf_scale_rect(wfc, &(wfc->update_rect)); + InvalidateRect(wfc->hwnd, &(wfc->update_rect), FALSE); + rect.left = x; + rect.right = width; + rect.top = y; + rect.bottom = height; + wf_scale_rect(wfc, &rect); + gdi_InvalidateRegion(gdi->primary->hdc, rect.left, rect.top, rect.right, rect.bottom); +} + +void wf_update_offset(wfContext* wfc) +{ + rdpSettings* settings; + settings = wfc->common.context.settings; + + if (wfc->fullscreen) + { + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_UseMultimon)) + { + int x = GetSystemMetrics(SM_XVIRTUALSCREEN); + int y = GetSystemMetrics(SM_YVIRTUALSCREEN); + int w = GetSystemMetrics(SM_CXVIRTUALSCREEN); + int h = GetSystemMetrics(SM_CYVIRTUALSCREEN); + wfc->offset_x = (w - freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)) / 2; + + if (wfc->offset_x < x) + wfc->offset_x = x; + + wfc->offset_y = (h - freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)) / 2; + + if (wfc->offset_y < y) + wfc->offset_y = y; + } + else + { + wfc->offset_x = (GetSystemMetrics(SM_CXSCREEN) - + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)) / + 2; + + if (wfc->offset_x < 0) + wfc->offset_x = 0; + + wfc->offset_y = (GetSystemMetrics(SM_CYSCREEN) - + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)) / + 2; + + if (wfc->offset_y < 0) + wfc->offset_y = 0; + } + } + else + { + wfc->offset_x = 0; + wfc->offset_y = 0; + } +} + +void wf_resize_window(wfContext* wfc) +{ + rdpSettings* settings; + settings = wfc->common.context.settings; + + if (wfc->fullscreen) + { + if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_UseMultimon)) + { + int x = GetSystemMetrics(SM_XVIRTUALSCREEN); + int y = GetSystemMetrics(SM_YVIRTUALSCREEN); + int w = GetSystemMetrics(SM_CXVIRTUALSCREEN); + int h = GetSystemMetrics(SM_CYVIRTUALSCREEN); + SetWindowLongPtr(wfc->hwnd, GWL_STYLE, WS_POPUP); + SetWindowPos(wfc->hwnd, HWND_TOP, x, y, w, h, SWP_FRAMECHANGED); + } + else + { + SetWindowLongPtr(wfc->hwnd, GWL_STYLE, WS_POPUP); + SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), + GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED); + } + } + else if (!freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_Decorations)) + { + SetWindowLongPtr(wfc->hwnd, GWL_STYLE, WS_CHILD); + + if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow)) + { + if (!wfc->client_height) + wfc->client_height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!wfc->client_width) + wfc->client_width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + + wf_update_canvas_diff(wfc); + /* Now resize to get full canvas size and room for caption and borders */ + SetWindowPos(wfc->hwnd, HWND_TOP, wfc->client_x, wfc->client_y, + wfc->client_width + wfc->diff.x, wfc->client_height + wfc->diff.y, + 0 /*SWP_FRAMECHANGED*/); + } + else + { + /* Now resize to get full canvas size and room for caption and borders */ + SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + SWP_FRAMECHANGED); + wf_update_canvas_diff(wfc); + SetWindowPos(wfc->hwnd, HWND_TOP, -1, -1, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) + wfc->diff.x, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) + wfc->diff.y, + SWP_NOMOVE | SWP_FRAMECHANGED); + } + } + else + { + SetWindowLongPtr(wfc->hwnd, GWL_STYLE, + WS_CAPTION | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX | + WS_MAXIMIZEBOX); + + if (!wfc->client_height) + wfc->client_height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (!wfc->client_width) + wfc->client_width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + + if (!wfc->client_x) + wfc->client_x = 10; + + if (!wfc->client_y) + wfc->client_y = 10; + + wf_update_canvas_diff(wfc); + /* Now resize to get full canvas size and room for caption and borders */ + int width, height; + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) && + freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth) && + freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight)) + { + width = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth); + height = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight); + } + else + { + width = wfc->client_width + wfc->diff.x; + height = wfc->client_height + wfc->diff.y; + } + + int xpos, ypos; + if ((freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX) != UINT32_MAX) && + (freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY) != UINT32_MAX)) + { + xpos = freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX); + ypos = freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY); + } + else + { + xpos = wfc->client_x; + ypos = wfc->client_y; + } + SetWindowPos(wfc->hwnd, HWND_TOP, xpos, ypos, width, height, 0 /*SWP_FRAMECHANGED*/); + // wf_size_scrollbars(wfc, wfc->client_width, wfc->client_height); + } + + wf_update_offset(wfc); +} + +void wf_toggle_fullscreen(wfContext* wfc) +{ + ShowWindow(wfc->hwnd, SW_HIDE); + wfc->fullscreen = !wfc->fullscreen; + + if (wfc->fullscreen) + { + wfc->disablewindowtracking = TRUE; + } + + wf_floatbar_toggle_fullscreen(wfc->floatbar, wfc->fullscreen); + SetParent(wfc->hwnd, wfc->fullscreen ? NULL : wfc->hWndParent); + wf_resize_window(wfc); + ShowWindow(wfc->hwnd, SW_SHOW); + SetForegroundWindow(wfc->hwnd); + + if (!wfc->fullscreen) + { + // Re-enable window tracking AFTER resizing it back, otherwise it can lean to repositioning + // errors. + wfc->disablewindowtracking = FALSE; + } +} + +static BOOL wf_gdi_palette_update(rdpContext* context, const PALETTE_UPDATE* palette) +{ + return TRUE; +} + +void wf_set_null_clip_rgn(wfContext* wfc) +{ + SelectClipRgn(wfc->drawing->hdc, NULL); +} + +void wf_set_clip_rgn(wfContext* wfc, int x, int y, int width, int height) +{ + HRGN clip; + clip = CreateRectRgn(x, y, x + width, y + height); + SelectClipRgn(wfc->drawing->hdc, clip); + DeleteObject(clip); +} + +static BOOL wf_gdi_set_bounds(rdpContext* context, const rdpBounds* bounds) +{ + HRGN hrgn; + wfContext* wfc = (wfContext*)context; + + if (!context || !bounds) + return FALSE; + + if (bounds != NULL) + { + hrgn = CreateRectRgn(bounds->left, bounds->top, bounds->right + 1, bounds->bottom + 1); + SelectClipRgn(wfc->drawing->hdc, hrgn); + DeleteObject(hrgn); + } + else + SelectClipRgn(wfc->drawing->hdc, NULL); + + return TRUE; +} + +static BOOL wf_gdi_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) +{ + wfContext* wfc = (wfContext*)context; + + if (!context || !dstblt) + return FALSE; + + if (!BitBlt(wfc->drawing->hdc, dstblt->nLeftRect, dstblt->nTopRect, dstblt->nWidth, + dstblt->nHeight, NULL, 0, 0, gdi_rop3_code(dstblt->bRop))) + return FALSE; + + wf_invalidate_region(wfc, dstblt->nLeftRect, dstblt->nTopRect, dstblt->nWidth, dstblt->nHeight); + return TRUE; +} + +static BOOL wf_gdi_patblt(rdpContext* context, PATBLT_ORDER* patblt) +{ + HBRUSH brush; + HBRUSH org_brush; + int org_bkmode; + COLORREF fgcolor; + COLORREF bgcolor; + COLORREF org_bkcolor; + COLORREF org_textcolor; + BOOL rc; + wfContext* wfc = (wfContext*)context; + + if (!context || !patblt) + return FALSE; + + if (!wf_decode_color(wfc, patblt->foreColor, &fgcolor, NULL)) + return FALSE; + + if (!wf_decode_color(wfc, patblt->backColor, &bgcolor, NULL)) + return FALSE; + + brush = wf_create_brush(wfc, &patblt->brush, fgcolor, + freerdp_settings_get_uint32(context->settings, FreeRDP_ColorDepth)); + org_bkmode = SetBkMode(wfc->drawing->hdc, OPAQUE); + org_bkcolor = SetBkColor(wfc->drawing->hdc, bgcolor); + org_textcolor = SetTextColor(wfc->drawing->hdc, fgcolor); + org_brush = (HBRUSH)SelectObject(wfc->drawing->hdc, brush); + rc = PatBlt(wfc->drawing->hdc, patblt->nLeftRect, patblt->nTopRect, patblt->nWidth, + patblt->nHeight, gdi_rop3_code(patblt->bRop)); + SelectObject(wfc->drawing->hdc, org_brush); + DeleteObject(brush); + SetBkMode(wfc->drawing->hdc, org_bkmode); + SetBkColor(wfc->drawing->hdc, org_bkcolor); + SetTextColor(wfc->drawing->hdc, org_textcolor); + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, patblt->nLeftRect, patblt->nTopRect, patblt->nWidth, + patblt->nHeight); + + return rc; +} + +static BOOL wf_gdi_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) +{ + wfContext* wfc = (wfContext*)context; + + if (!context || !scrblt || !wfc->drawing) + return FALSE; + + if (!BitBlt(wfc->drawing->hdc, scrblt->nLeftRect, scrblt->nTopRect, scrblt->nWidth, + scrblt->nHeight, wfc->primary->hdc, scrblt->nXSrc, scrblt->nYSrc, + gdi_rop3_code(scrblt->bRop))) + return FALSE; + + wf_invalidate_region(wfc, scrblt->nLeftRect, scrblt->nTopRect, scrblt->nWidth, scrblt->nHeight); + return TRUE; +} + +static BOOL wf_gdi_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) +{ + RECT rect; + HBRUSH brush; + COLORREF brush_color; + wfContext* wfc = (wfContext*)context; + + if (!context || !opaque_rect) + return FALSE; + + if (!wf_decode_color(wfc, opaque_rect->color, &brush_color, NULL)) + return FALSE; + + rect.left = opaque_rect->nLeftRect; + rect.top = opaque_rect->nTopRect; + rect.right = opaque_rect->nLeftRect + opaque_rect->nWidth; + rect.bottom = opaque_rect->nTopRect + opaque_rect->nHeight; + brush = CreateSolidBrush(brush_color); + FillRect(wfc->drawing->hdc, &rect, brush); + DeleteObject(brush); + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, rect.left, rect.top, rect.right - rect.left + 1, + rect.bottom - rect.top + 1); + + return TRUE; +} + +static BOOL wf_gdi_multi_opaque_rect(rdpContext* context, + const MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect) +{ + RECT rect; + HBRUSH brush; + COLORREF brush_color; + wfContext* wfc = (wfContext*)context; + + if (!context || !multi_opaque_rect) + return FALSE; + + if (!wf_decode_color(wfc, multi_opaque_rect->color, &brush_color, NULL)) + return FALSE; + + for (UINT32 i = 0; i < multi_opaque_rect->numRectangles; i++) + { + const DELTA_RECT* rectangle = &multi_opaque_rect->rectangles[i]; + rect.left = rectangle->left; + rect.top = rectangle->top; + rect.right = rectangle->left + rectangle->width; + rect.bottom = rectangle->top + rectangle->height; + brush = CreateSolidBrush(brush_color); + FillRect(wfc->drawing->hdc, &rect, brush); + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, rect.left, rect.top, rect.right - rect.left + 1, + rect.bottom - rect.top + 1); + + DeleteObject(brush); + } + + return TRUE; +} + +static BOOL wf_gdi_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) +{ + HPEN pen; + HPEN org_pen; + int x, y, w, h; + COLORREF pen_color; + wfContext* wfc = (wfContext*)context; + + if (!context || !line_to) + return FALSE; + + if (!wf_decode_color(wfc, line_to->penColor, &pen_color, NULL)) + return FALSE; + + pen = CreatePen(line_to->penStyle, line_to->penWidth, pen_color); + wf_set_rop2(wfc->drawing->hdc, line_to->bRop2); + org_pen = (HPEN)SelectObject(wfc->drawing->hdc, pen); + MoveToEx(wfc->drawing->hdc, line_to->nXStart, line_to->nYStart, NULL); + LineTo(wfc->drawing->hdc, line_to->nXEnd, line_to->nYEnd); + x = (line_to->nXStart < line_to->nXEnd) ? line_to->nXStart : line_to->nXEnd; + y = (line_to->nYStart < line_to->nYEnd) ? line_to->nYStart : line_to->nYEnd; + w = (line_to->nXStart < line_to->nXEnd) ? (line_to->nXEnd - line_to->nXStart) + : (line_to->nXStart - line_to->nXEnd); + h = (line_to->nYStart < line_to->nYEnd) ? (line_to->nYEnd - line_to->nYStart) + : (line_to->nYStart - line_to->nYEnd); + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, x, y, w, h); + + SelectObject(wfc->drawing->hdc, org_pen); + DeleteObject(pen); + return TRUE; +} + +static BOOL wf_gdi_polyline(rdpContext* context, const POLYLINE_ORDER* polyline) +{ + int org_rop2; + HPEN hpen; + HPEN org_hpen; + COLORREF pen_color; + wfContext* wfc = (wfContext*)context; + + if (!context || !polyline) + return FALSE; + + if (!wf_decode_color(wfc, polyline->penColor, &pen_color, NULL)) + return FALSE; + + hpen = CreatePen(0, 1, pen_color); + org_rop2 = wf_set_rop2(wfc->drawing->hdc, polyline->bRop2); + org_hpen = (HPEN)SelectObject(wfc->drawing->hdc, hpen); + + if (polyline->numDeltaEntries > 0) + { + POINT* pts; + POINT temp; + int numPoints; + numPoints = polyline->numDeltaEntries + 1; + pts = (POINT*)malloc(sizeof(POINT) * numPoints); + pts[0].x = temp.x = polyline->xStart; + pts[0].y = temp.y = polyline->yStart; + + for (UINT32 i = 0; i < polyline->numDeltaEntries; i++) + { + temp.x += polyline->points[i].x; + temp.y += polyline->points[i].y; + pts[i + 1].x = temp.x; + pts[i + 1].y = temp.y; + } + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, wfc->client_x, wfc->client_y, wfc->client_width, + wfc->client_height); + + Polyline(wfc->drawing->hdc, pts, numPoints); + free(pts); + } + + SelectObject(wfc->drawing->hdc, org_hpen); + wf_set_rop2(wfc->drawing->hdc, org_rop2); + DeleteObject(hpen); + return TRUE; +} + +static BOOL wf_gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt) +{ + wfBitmap* bitmap; + wfContext* wfc = (wfContext*)context; + + if (!context || !memblt) + return FALSE; + + bitmap = (wfBitmap*)memblt->bitmap; + + if (!bitmap || !wfc->drawing || !wfc->drawing->hdc) + return FALSE; + + if (!BitBlt(wfc->drawing->hdc, memblt->nLeftRect, memblt->nTopRect, memblt->nWidth, + memblt->nHeight, bitmap->hdc, memblt->nXSrc, memblt->nYSrc, + gdi_rop3_code(memblt->bRop))) + return FALSE; + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, memblt->nLeftRect, memblt->nTopRect, memblt->nWidth, + memblt->nHeight); + + return TRUE; +} + +static BOOL wf_gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt) +{ + BOOL rc = FALSE; + HDC hdc; + wfBitmap* bitmap; + wfContext* wfc = (wfContext*)context; + COLORREF fgcolor, bgcolor, orgColor; + HBRUSH orgBrush = NULL, brush = NULL; + + if (!context || !mem3blt) + return FALSE; + + bitmap = (wfBitmap*)mem3blt->bitmap; + + if (!bitmap || !wfc->drawing || !wfc->drawing->hdc) + return FALSE; + + hdc = wfc->drawing->hdc; + + if (!wf_decode_color(wfc, mem3blt->foreColor, &fgcolor, NULL)) + return FALSE; + + if (!wf_decode_color(wfc, mem3blt->backColor, &bgcolor, NULL)) + return FALSE; + + orgColor = SetTextColor(hdc, fgcolor); + + switch (mem3blt->brush.style) + { + case GDI_BS_SOLID: + brush = CreateSolidBrush(fgcolor); + break; + + case GDI_BS_HATCHED: + case GDI_BS_PATTERN: + { + HBITMAP bmp = CreateBitmap(8, 8, 1, mem3blt->brush.bpp, mem3blt->brush.data); + brush = CreatePatternBrush(bmp); + } + break; + + default: + goto fail; + } + + orgBrush = SelectObject(hdc, brush); + + if (!BitBlt(hdc, mem3blt->nLeftRect, mem3blt->nTopRect, mem3blt->nWidth, mem3blt->nHeight, + bitmap->hdc, mem3blt->nXSrc, mem3blt->nYSrc, gdi_rop3_code(mem3blt->bRop))) + goto fail; + + if (wfc->drawing == wfc->primary) + wf_invalidate_region(wfc, mem3blt->nLeftRect, mem3blt->nTopRect, mem3blt->nWidth, + mem3blt->nHeight); + + rc = TRUE; +fail: + + if (brush) + SelectObject(hdc, orgBrush); + + SetTextColor(hdc, orgColor); + return rc; +} + +static BOOL wf_gdi_surface_frame_marker(rdpContext* context, + const SURFACE_FRAME_MARKER* surface_frame_marker) +{ + rdpSettings* settings; + + if (!context || !surface_frame_marker || !context->instance) + return FALSE; + + settings = context->settings; + + if (!settings) + return FALSE; + + if (surface_frame_marker->frameAction == SURFACECMD_FRAMEACTION_END && + freerdp_settings_get_uint32(settings, FreeRDP_FrameAcknowledge) > 0) + { + IFCALL(context->update->SurfaceFrameAcknowledge, context, surface_frame_marker->frameId); + } + + return TRUE; +} + +void wf_gdi_register_update_callbacks(rdpUpdate* update) +{ + rdpPrimaryUpdate* primary = update->primary; + update->Palette = wf_gdi_palette_update; + update->SetBounds = wf_gdi_set_bounds; + primary->DstBlt = wf_gdi_dstblt; + primary->PatBlt = wf_gdi_patblt; + primary->ScrBlt = wf_gdi_scrblt; + primary->OpaqueRect = wf_gdi_opaque_rect; + primary->MultiOpaqueRect = wf_gdi_multi_opaque_rect; + primary->LineTo = wf_gdi_line_to; + primary->Polyline = wf_gdi_polyline; + primary->MemBlt = wf_gdi_memblt; + primary->Mem3Blt = wf_gdi_mem3blt; + update->SurfaceFrameMarker = wf_gdi_surface_frame_marker; +} + +void wf_update_canvas_diff(wfContext* wfc) +{ + RECT rc_client, rc_wnd; + int dx, dy; + GetClientRect(wfc->hwnd, &rc_client); + GetWindowRect(wfc->hwnd, &rc_wnd); + dx = (rc_wnd.right - rc_wnd.left) - rc_client.right; + dy = (rc_wnd.bottom - rc_wnd.top) - rc_client.bottom; + + if (!wfc->disablewindowtracking) + { + wfc->diff.x = dx; + wfc->diff.y = dy; + } +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.h new file mode 100644 index 0000000000000000000000000000000000000000..15b39ea85bd05706f23392147879f620b3eea772 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_gdi.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows GDI + * + * Copyright 2009-2011 Jay Sorg + * Copyright 2010-2011 Vic Lee + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_GDI_H +#define FREERDP_CLIENT_WIN_GDI_H + +#include "wf_client.h" + +void wf_invalidate_region(wfContext* wfc, UINT32 x, UINT32 y, UINT32 width, UINT32 height); +void wf_update_offset(wfContext* wfc); +void wf_resize_window(wfContext* wfc); +void wf_toggle_fullscreen(wfContext* wfc); +BOOL wf_scale_rect(wfContext* wfc, RECT* source); + +void wf_gdi_register_update_callbacks(rdpUpdate* update); + +void wf_update_canvas_diff(wfContext* wfc); + +#endif /* FREERDP_CLIENT_WIN_GDI_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.c new file mode 100644 index 0000000000000000000000000000000000000000..a60054a50f16f1e7b02dbe3b5e74310b7aca42cd --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.c @@ -0,0 +1,375 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Graphical Objects + * + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include "wf_gdi.h" +#include "wf_graphics.h" + +#define TAG CLIENT_TAG("windows") + +HBITMAP wf_create_dib(wfContext* wfc, UINT32 width, UINT32 height, UINT32 srcFormat, + const BYTE* data, BYTE** pdata) +{ + HDC hdc; + int negHeight; + HBITMAP bitmap; + BITMAPINFO bmi; + BYTE* cdata = NULL; + UINT32 dstFormat = srcFormat; + /** + * See: http://msdn.microsoft.com/en-us/library/dd183376 + * if biHeight is positive, the bitmap is bottom-up + * if biHeight is negative, the bitmap is top-down + * Since we get top-down bitmaps, let's keep it that way + */ + negHeight = (height < 0) ? height : height * (-1); + hdc = GetDC(NULL); + bmi.bmiHeader.biSize = sizeof(BITMAPINFO); + bmi.bmiHeader.biWidth = width; + bmi.bmiHeader.biHeight = negHeight; + bmi.bmiHeader.biPlanes = 1; + bmi.bmiHeader.biBitCount = FreeRDPGetBitsPerPixel(dstFormat); + bmi.bmiHeader.biCompression = BI_RGB; + bitmap = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**)&cdata, NULL, 0); + + if (data) + freerdp_image_copy(cdata, dstFormat, 0, 0, 0, width, height, data, srcFormat, 0, 0, 0, + &wfc->common.context.gdi->palette, FREERDP_FLIP_NONE); + + if (pdata) + *pdata = cdata; + + ReleaseDC(NULL, hdc); + GdiFlush(); + return bitmap; +} + +wfBitmap* wf_image_new(wfContext* wfc, UINT32 width, UINT32 height, UINT32 format, const BYTE* data) +{ + HDC hdc; + wfBitmap* image; + hdc = GetDC(NULL); + image = (wfBitmap*)malloc(sizeof(wfBitmap)); + image->hdc = CreateCompatibleDC(hdc); + image->bitmap = wf_create_dib(wfc, width, height, format, data, &(image->pdata)); + image->org_bitmap = (HBITMAP)SelectObject(image->hdc, image->bitmap); + ReleaseDC(NULL, hdc); + return image; +} + +void wf_image_free(wfBitmap* image) +{ + if (image != 0) + { + SelectObject(image->hdc, image->org_bitmap); + DeleteObject(image->bitmap); + DeleteDC(image->hdc); + free(image); + } +} + +/* Bitmap Class */ + +static BOOL wf_Bitmap_New(rdpContext* context, rdpBitmap* bitmap) +{ + HDC hdc; + wfContext* wfc = (wfContext*)context; + wfBitmap* wf_bitmap = (wfBitmap*)bitmap; + + if (!context || !bitmap) + return FALSE; + + wf_bitmap = (wfBitmap*)bitmap; + hdc = GetDC(NULL); + wf_bitmap->hdc = CreateCompatibleDC(hdc); + + if (!bitmap->data) + wf_bitmap->bitmap = CreateCompatibleBitmap(hdc, bitmap->width, bitmap->height); + else + wf_bitmap->bitmap = + wf_create_dib(wfc, bitmap->width, bitmap->height, bitmap->format, bitmap->data, NULL); + + wf_bitmap->org_bitmap = (HBITMAP)SelectObject(wf_bitmap->hdc, wf_bitmap->bitmap); + ReleaseDC(NULL, hdc); + return TRUE; +} + +static void wf_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap) +{ + wfBitmap* wf_bitmap = (wfBitmap*)bitmap; + + if (wf_bitmap != 0) + { + SelectObject(wf_bitmap->hdc, wf_bitmap->org_bitmap); + DeleteObject(wf_bitmap->bitmap); + DeleteDC(wf_bitmap->hdc); + + winpr_aligned_free(wf_bitmap->_bitmap.data); + wf_bitmap->_bitmap.data = NULL; + } +} + +static BOOL wf_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap) +{ + BOOL rc; + UINT32 width, height; + wfContext* wfc = (wfContext*)context; + wfBitmap* wf_bitmap = (wfBitmap*)bitmap; + + if (!context || !bitmap) + return FALSE; + + width = bitmap->right - bitmap->left + 1; + height = bitmap->bottom - bitmap->top + 1; + rc = BitBlt(wfc->primary->hdc, bitmap->left, bitmap->top, width, height, wf_bitmap->hdc, 0, 0, + SRCCOPY); + wf_invalidate_region(wfc, bitmap->left, bitmap->top, width, height); + return rc; +} + +static BOOL wf_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary) +{ + wfContext* wfc = (wfContext*)context; + wfBitmap* bmp = (wfBitmap*)bitmap; + rdpGdi* gdi = context->gdi; + + if (!gdi || !wfc) + return FALSE; + + if (primary) + wfc->drawing = wfc->primary; + else if (!bmp) + return FALSE; + else + wfc->drawing = bmp; + + return TRUE; +} + +/* Pointer Class */ + +static BOOL flip_bitmap(const BYTE* src, BYTE* dst, UINT32 scanline, UINT32 nHeight) +{ + BYTE* bottomLine = dst + scanline * (nHeight - 1); + + for (UINT32 x = 0; x < nHeight; x++) + { + memcpy(bottomLine, src, scanline); + src += scanline; + bottomLine -= scanline; + } + + return TRUE; +} + +static BOOL wf_Pointer_New(rdpContext* context, rdpPointer* pointer) +{ + HCURSOR hCur; + ICONINFO info; + rdpGdi* gdi; + BOOL rc = FALSE; + + if (!context || !pointer) + return FALSE; + + gdi = context->gdi; + + if (!gdi) + return FALSE; + + info.fIcon = FALSE; + info.xHotspot = pointer->xPos; + info.yHotspot = pointer->yPos; + + if (pointer->xorBpp == 1) + { + BYTE* pdata = NULL; + + if ((pointer->lengthAndMask > 0) || (pointer->lengthXorMask > 0)) + { + pdata = + (BYTE*)winpr_aligned_malloc(pointer->lengthAndMask + pointer->lengthXorMask, 16); + + if (!pdata) + goto fail; + } + + CopyMemory(pdata, pointer->andMaskData, pointer->lengthAndMask); + CopyMemory(pdata + pointer->lengthAndMask, pointer->xorMaskData, pointer->lengthXorMask); + info.hbmMask = CreateBitmap(pointer->width, pointer->height * 2, 1, 1, pdata); + winpr_aligned_free(pdata); + info.hbmColor = NULL; + } + else + { + UINT32 srcFormat; + BYTE* pdata = NULL; + + if (pointer->lengthAndMask > 0) + { + pdata = (BYTE*)winpr_aligned_malloc(pointer->lengthAndMask, 16); + + if (!pdata) + goto fail; + flip_bitmap(pointer->andMaskData, pdata, (pointer->width + 7) / 8, pointer->height); + } + + info.hbmMask = CreateBitmap(pointer->width, pointer->height, 1, 1, pdata); + winpr_aligned_free(pdata); + + /* currently color xorBpp is only 24 per [T128] section 8.14.3 */ + srcFormat = gdi_get_pixel_format(pointer->xorBpp); + + if (!srcFormat) + goto fail; + + info.hbmColor = wf_create_dib((wfContext*)context, pointer->width, pointer->height, + gdi->dstFormat, NULL, &pdata); + + if (!info.hbmColor) + goto fail; + + if (!freerdp_image_copy_from_pointer_data( + pdata, gdi->dstFormat, 0, 0, 0, pointer->width, pointer->height, + pointer->xorMaskData, pointer->lengthXorMask, pointer->andMaskData, + pointer->lengthAndMask, pointer->xorBpp, &gdi->palette)) + { + goto fail; + } + } + + hCur = CreateIconIndirect(&info); + ((wfPointer*)pointer)->cursor = hCur; + rc = TRUE; +fail: + + if (info.hbmMask) + DeleteObject(info.hbmMask); + + if (info.hbmColor) + DeleteObject(info.hbmColor); + + return rc; +} + +static void wf_Pointer_Free(rdpContext* context, rdpPointer* pointer) +{ + HCURSOR hCur; + + if (!context || !pointer) + return; + + hCur = ((wfPointer*)pointer)->cursor; + + if (hCur != 0) + DestroyIcon(hCur); +} + +static BOOL wf_Pointer_Set(rdpContext* context, rdpPointer* pointer) +{ + HCURSOR hCur; + wfContext* wfc = (wfContext*)context; + + if (!context || !pointer) + return FALSE; + + hCur = ((wfPointer*)pointer)->cursor; + + if (hCur != NULL) + { + SetCursor(hCur); + wfc->cursor = hCur; + } + + return TRUE; +} + +static BOOL wf_Pointer_SetNull(rdpContext* context) +{ + if (!context) + return FALSE; + + return TRUE; +} + +static BOOL wf_Pointer_SetDefault(rdpContext* context) +{ + if (!context) + return FALSE; + + return TRUE; +} + +static BOOL wf_Pointer_SetPosition(rdpContext* context, UINT32 x, UINT32 y) +{ + if (!context) + return FALSE; + + return TRUE; +} + +BOOL wf_register_pointer(rdpGraphics* graphics) +{ + wfContext* wfc; + rdpPointer pointer = { 0 }; + + if (!graphics) + return FALSE; + + wfc = (wfContext*)graphics->context; + pointer.size = sizeof(wfPointer); + pointer.New = wf_Pointer_New; + pointer.Free = wf_Pointer_Free; + pointer.Set = wf_Pointer_Set; + pointer.SetNull = wf_Pointer_SetNull; + pointer.SetDefault = wf_Pointer_SetDefault; + pointer.SetPosition = wf_Pointer_SetPosition; + graphics_register_pointer(graphics, &pointer); + return TRUE; +} + +/* Graphics Module */ + +BOOL wf_register_graphics(rdpGraphics* graphics) +{ + wfContext* wfc; + rdpGlyph glyph; + rdpBitmap bitmap; + + if (!graphics) + return FALSE; + + wfc = (wfContext*)graphics->context; + bitmap = *graphics->Bitmap_Prototype; + bitmap.size = sizeof(wfBitmap); + bitmap.New = wf_Bitmap_New; + bitmap.Free = wf_Bitmap_Free; + bitmap.Paint = wf_Bitmap_Paint; + bitmap.SetSurface = wf_Bitmap_SetSurface; + graphics_register_bitmap(graphics, &bitmap); + glyph = *graphics->Glyph_Prototype; + graphics_register_glyph(graphics, &glyph); + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.h new file mode 100644 index 0000000000000000000000000000000000000000..241575fd2eb866e391ae3b692b6e3c92ca6d94be --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_graphics.h @@ -0,0 +1,34 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Windows Graphical Objects + * + * Copyright 2010-2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_GRAPHICS_H +#define FREERDP_CLIENT_WIN_GRAPHICS_H + +#include "wf_client.h" + +HBITMAP wf_create_dib(wfContext* wfc, UINT32 width, UINT32 height, UINT32 format, const BYTE* data, + BYTE** pdata); +wfBitmap* wf_image_new(wfContext* wfc, UINT32 width, UINT32 height, UINT32 format, + const BYTE* data); +void wf_image_free(wfBitmap* image); + +BOOL wf_register_pointer(rdpGraphics* graphics); +BOOL wf_register_graphics(rdpGraphics* graphics); + +#endif /* FREERDP_CLIENT_WIN_GRAPHICS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.c b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.c new file mode 100644 index 0000000000000000000000000000000000000000..6d185e3fc2143ed547836d15d8bd69a7757973e3 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.c @@ -0,0 +1,994 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2013-2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +#include "wf_rail.h" + +#define TAG CLIENT_TAG("windows") + +#define GET_X_LPARAM(lParam) ((UINT16)(lParam & 0xFFFF)) +#define GET_Y_LPARAM(lParam) ((UINT16)((lParam >> 16) & 0xFFFF)) + +struct wf_rail_window +{ + wfContext* wfc; + + HWND hWnd; + + DWORD dwStyle; + DWORD dwExStyle; + + int x; + int y; + int width; + int height; + char* title; +}; + +/* RemoteApp Core Protocol Extension */ + +typedef struct +{ + UINT32 style; + const char* name; + BOOL multi; +} WINDOW_STYLE; + +static const WINDOW_STYLE WINDOW_STYLES[] = { { WS_BORDER, "WS_BORDER", FALSE }, + { WS_CAPTION, "WS_CAPTION", FALSE }, + { WS_CHILD, "WS_CHILD", FALSE }, + { WS_CLIPCHILDREN, "WS_CLIPCHILDREN", FALSE }, + { WS_CLIPSIBLINGS, "WS_CLIPSIBLINGS", FALSE }, + { WS_DISABLED, "WS_DISABLED", FALSE }, + { WS_DLGFRAME, "WS_DLGFRAME", FALSE }, + { WS_GROUP, "WS_GROUP", FALSE }, + { WS_HSCROLL, "WS_HSCROLL", FALSE }, + { WS_ICONIC, "WS_ICONIC", FALSE }, + { WS_MAXIMIZE, "WS_MAXIMIZE", FALSE }, + { WS_MAXIMIZEBOX, "WS_MAXIMIZEBOX", FALSE }, + { WS_MINIMIZE, "WS_MINIMIZE", FALSE }, + { WS_MINIMIZEBOX, "WS_MINIMIZEBOX", FALSE }, + { WS_OVERLAPPED, "WS_OVERLAPPED", FALSE }, + { WS_OVERLAPPEDWINDOW, "WS_OVERLAPPEDWINDOW", TRUE }, + { WS_POPUP, "WS_POPUP", FALSE }, + { WS_POPUPWINDOW, "WS_POPUPWINDOW", TRUE }, + { WS_SIZEBOX, "WS_SIZEBOX", FALSE }, + { WS_SYSMENU, "WS_SYSMENU", FALSE }, + { WS_TABSTOP, "WS_TABSTOP", FALSE }, + { WS_THICKFRAME, "WS_THICKFRAME", FALSE }, + { WS_VISIBLE, "WS_VISIBLE", FALSE } }; + +static const WINDOW_STYLE EXTENDED_WINDOW_STYLES[] = { + { WS_EX_ACCEPTFILES, "WS_EX_ACCEPTFILES", FALSE }, + { WS_EX_APPWINDOW, "WS_EX_APPWINDOW", FALSE }, + { WS_EX_CLIENTEDGE, "WS_EX_CLIENTEDGE", FALSE }, + { WS_EX_COMPOSITED, "WS_EX_COMPOSITED", FALSE }, + { WS_EX_CONTEXTHELP, "WS_EX_CONTEXTHELP", FALSE }, + { WS_EX_CONTROLPARENT, "WS_EX_CONTROLPARENT", FALSE }, + { WS_EX_DLGMODALFRAME, "WS_EX_DLGMODALFRAME", FALSE }, + { WS_EX_LAYERED, "WS_EX_LAYERED", FALSE }, + { WS_EX_LAYOUTRTL, "WS_EX_LAYOUTRTL", FALSE }, + { WS_EX_LEFT, "WS_EX_LEFT", FALSE }, + { WS_EX_LEFTSCROLLBAR, "WS_EX_LEFTSCROLLBAR", FALSE }, + { WS_EX_LTRREADING, "WS_EX_LTRREADING", FALSE }, + { WS_EX_MDICHILD, "WS_EX_MDICHILD", FALSE }, + { WS_EX_NOACTIVATE, "WS_EX_NOACTIVATE", FALSE }, + { WS_EX_NOINHERITLAYOUT, "WS_EX_NOINHERITLAYOUT", FALSE }, + { WS_EX_NOPARENTNOTIFY, "WS_EX_NOPARENTNOTIFY", FALSE }, + { WS_EX_OVERLAPPEDWINDOW, "WS_EX_OVERLAPPEDWINDOW", TRUE }, + { WS_EX_PALETTEWINDOW, "WS_EX_PALETTEWINDOW", TRUE }, + { WS_EX_RIGHT, "WS_EX_RIGHT", FALSE }, + { WS_EX_RIGHTSCROLLBAR, "WS_EX_RIGHTSCROLLBAR", FALSE }, + { WS_EX_RTLREADING, "WS_EX_RTLREADING", FALSE }, + { WS_EX_STATICEDGE, "WS_EX_STATICEDGE", FALSE }, + { WS_EX_TOOLWINDOW, "WS_EX_TOOLWINDOW", FALSE }, + { WS_EX_TOPMOST, "WS_EX_TOPMOST", FALSE }, + { WS_EX_TRANSPARENT, "WS_EX_TRANSPARENT", FALSE }, + { WS_EX_WINDOWEDGE, "WS_EX_WINDOWEDGE", FALSE } +}; + +static void PrintWindowStyles(UINT32 style) +{ + WLog_INFO(TAG, "\tWindow Styles:\t{"); + + for (size_t i = 0; i < ARRAYSIZE(WINDOW_STYLES); i++) + { + if (style & WINDOW_STYLES[i].style) + { + if (WINDOW_STYLES[i].multi) + { + if ((style & WINDOW_STYLES[i].style) != WINDOW_STYLES[i].style) + continue; + } + + WLog_INFO(TAG, "\t\t%s", WINDOW_STYLES[i].name); + } + } +} + +static void PrintExtendedWindowStyles(UINT32 style) +{ + WLog_INFO(TAG, "\tExtended Window Styles:\t{"); + + for (size_t i = 0; i < ARRAYSIZE(EXTENDED_WINDOW_STYLES); i++) + { + if (style & EXTENDED_WINDOW_STYLES[i].style) + { + if (EXTENDED_WINDOW_STYLES[i].multi) + { + if ((style & EXTENDED_WINDOW_STYLES[i].style) != EXTENDED_WINDOW_STYLES[i].style) + continue; + } + + WLog_INFO(TAG, "\t\t%s", EXTENDED_WINDOW_STYLES[i].name); + } + } +} + +static void PrintRailWindowState(const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_STATE_ORDER* windowState) +{ + if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW) + WLog_INFO(TAG, "WindowCreate: WindowId: 0x%08X", orderInfo->windowId); + else + WLog_INFO(TAG, "WindowUpdate: WindowId: 0x%08X", orderInfo->windowId); + + WLog_INFO(TAG, "{"); + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) + { + WLog_INFO(TAG, "\tOwnerWindowId: 0x%08X", windowState->ownerWindowId); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) + { + WLog_INFO(TAG, "\tStyle: 0x%08X ExtendedStyle: 0x%08X", windowState->style, + windowState->extendedStyle); + PrintWindowStyles(windowState->style); + PrintExtendedWindowStyles(windowState->extendedStyle); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) + { + WLog_INFO(TAG, "\tShowState: %u", windowState->showState); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + const WCHAR* str = (const WCHAR*)windowState->titleInfo.string; + char* title = + ConvertWCharNToUtf8Alloc(str, windowState->titleInfo.length / sizeof(WCHAR), NULL); + WLog_INFO(TAG, "\tTitleInfo: %s (length = %hu)", title, windowState->titleInfo.length); + free(title); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) + { + WLog_INFO(TAG, "\tClientOffsetX: %d ClientOffsetY: %d", windowState->clientOffsetX, + windowState->clientOffsetY); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) + { + WLog_INFO(TAG, "\tClientAreaWidth: %u ClientAreaHeight: %u", windowState->clientAreaWidth, + windowState->clientAreaHeight); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) + { + WLog_INFO(TAG, "\tRPContent: %u", windowState->RPContent); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) + { + WLog_INFO(TAG, "\tRootParentHandle: 0x%08X", windowState->rootParentHandle); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) + { + WLog_INFO(TAG, "\tWindowOffsetX: %d WindowOffsetY: %d", windowState->windowOffsetX, + windowState->windowOffsetY); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) + { + WLog_INFO(TAG, "\tWindowClientDeltaX: %d WindowClientDeltaY: %d", + windowState->windowClientDeltaX, windowState->windowClientDeltaY); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) + { + WLog_INFO(TAG, "\tWindowWidth: %u WindowHeight: %u", windowState->windowWidth, + windowState->windowHeight); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) + { + RECTANGLE_16* rect; + WLog_INFO(TAG, "\tnumWindowRects: %u", windowState->numWindowRects); + + for (UINT32 index = 0; index < windowState->numWindowRects; index++) + { + rect = &windowState->windowRects[index]; + WLog_INFO(TAG, "\twindowRect[%u]: left: %hu top: %hu right: %hu bottom: %hu", index, + rect->left, rect->top, rect->right, rect->bottom); + } + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) + { + WLog_INFO(TAG, "\tvisibileOffsetX: %d visibleOffsetY: %d", windowState->visibleOffsetX, + windowState->visibleOffsetY); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) + { + RECTANGLE_16* rect; + WLog_INFO(TAG, "\tnumVisibilityRects: %u", windowState->numVisibilityRects); + + for (UINT32 index = 0; index < windowState->numVisibilityRects; index++) + { + rect = &windowState->visibilityRects[index]; + WLog_INFO(TAG, "\tvisibilityRect[%u]: left: %hu top: %hu right: %hu bottom: %hu", index, + rect->left, rect->top, rect->right, rect->bottom); + } + } + + WLog_INFO(TAG, "}"); +} + +static void PrintRailIconInfo(const WINDOW_ORDER_INFO* orderInfo, const ICON_INFO* iconInfo) +{ + WLog_INFO(TAG, "ICON_INFO"); + WLog_INFO(TAG, "{"); + WLog_INFO(TAG, "\tbigIcon: %s", + (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? "true" : "false"); + WLog_INFO(TAG, "\tcacheEntry; 0x%08X", iconInfo->cacheEntry); + WLog_INFO(TAG, "\tcacheId: 0x%08X", iconInfo->cacheId); + WLog_INFO(TAG, "\tbpp: %u", iconInfo->bpp); + WLog_INFO(TAG, "\twidth: %u", iconInfo->width); + WLog_INFO(TAG, "\theight: %u", iconInfo->height); + WLog_INFO(TAG, "\tcbColorTable: %u", iconInfo->cbColorTable); + WLog_INFO(TAG, "\tcbBitsMask: %u", iconInfo->cbBitsMask); + WLog_INFO(TAG, "\tcbBitsColor: %u", iconInfo->cbBitsColor); + WLog_INFO(TAG, "\tcolorTable: %p", (void*)iconInfo->colorTable); + WLog_INFO(TAG, "\tbitsMask: %p", (void*)iconInfo->bitsMask); + WLog_INFO(TAG, "\tbitsColor: %p", (void*)iconInfo->bitsColor); + WLog_INFO(TAG, "}"); +} + +LRESULT CALLBACK wf_RailWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + HDC hDC; + int x, y; + int width; + int height; + UINT32 xPos; + UINT32 yPos; + PAINTSTRUCT ps; + UINT32 inputFlags; + wfContext* wfc = NULL; + rdpInput* input = NULL; + rdpContext* context = NULL; + wfRailWindow* railWindow; + railWindow = (wfRailWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); + + if (railWindow) + wfc = railWindow->wfc; + + if (wfc) + context = (rdpContext*)wfc; + + if (context) + input = context->input; + + switch (msg) + { + case WM_PAINT: + { + if (!wfc) + return 0; + + hDC = BeginPaint(hWnd, &ps); + x = ps.rcPaint.left; + y = ps.rcPaint.top; + width = ps.rcPaint.right - ps.rcPaint.left + 1; + height = ps.rcPaint.bottom - ps.rcPaint.top + 1; + BitBlt(hDC, x, y, width, height, wfc->primary->hdc, railWindow->x + x, + railWindow->y + y, SRCCOPY); + EndPaint(hWnd, &ps); + } + break; + + case WM_LBUTTONDOWN: + { + if (!railWindow || !input) + return 0; + + xPos = GET_X_LPARAM(lParam) + railWindow->x; + yPos = GET_Y_LPARAM(lParam) + railWindow->y; + inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON1; + + if (input) + input->MouseEvent(input, inputFlags, xPos, yPos); + } + break; + + case WM_LBUTTONUP: + { + if (!railWindow || !input) + return 0; + + xPos = GET_X_LPARAM(lParam) + railWindow->x; + yPos = GET_Y_LPARAM(lParam) + railWindow->y; + inputFlags = PTR_FLAGS_BUTTON1; + + if (input) + input->MouseEvent(input, inputFlags, xPos, yPos); + } + break; + + case WM_RBUTTONDOWN: + { + if (!railWindow || !input) + return 0; + + xPos = GET_X_LPARAM(lParam) + railWindow->x; + yPos = GET_Y_LPARAM(lParam) + railWindow->y; + inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON2; + + if (input) + input->MouseEvent(input, inputFlags, xPos, yPos); + } + break; + + case WM_RBUTTONUP: + { + if (!railWindow || !input) + return 0; + + xPos = GET_X_LPARAM(lParam) + railWindow->x; + yPos = GET_Y_LPARAM(lParam) + railWindow->y; + inputFlags = PTR_FLAGS_BUTTON2; + + if (input) + input->MouseEvent(input, inputFlags, xPos, yPos); + } + break; + + case WM_MOUSEMOVE: + { + if (!railWindow || !input) + return 0; + + xPos = GET_X_LPARAM(lParam) + railWindow->x; + yPos = GET_Y_LPARAM(lParam) + railWindow->y; + inputFlags = PTR_FLAGS_MOVE; + + if (input) + input->MouseEvent(input, inputFlags, xPos, yPos); + } + break; + + case WM_MOUSEWHEEL: + break; + + case WM_CLOSE: + DestroyWindow(hWnd); + break; + + case WM_DESTROY: + PostQuitMessage(0); + break; + + default: + return DefWindowProc(hWnd, msg, wParam, lParam); + } + + return 0; +} + +#define RAIL_DISABLED_WINDOW_STYLES \ + (WS_BORDER | WS_THICKFRAME | WS_DLGFRAME | WS_CAPTION | WS_OVERLAPPED | WS_VSCROLL | \ + WS_HSCROLL | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX) +#define RAIL_DISABLED_EXTENDED_WINDOW_STYLES \ + (WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE | WS_EX_WINDOWEDGE) + +static BOOL wf_rail_window_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_STATE_ORDER* windowState) +{ + wfRailWindow* railWindow = NULL; + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + UINT32 fieldFlags = orderInfo->fieldFlags; + PrintRailWindowState(orderInfo, windowState); + + if (fieldFlags & WINDOW_ORDER_STATE_NEW) + { + BOOL rc; + HANDLE hInstance; + WCHAR* titleW = NULL; + WNDCLASSEX wndClassEx = { 0 }; + railWindow = (wfRailWindow*)calloc(1, sizeof(wfRailWindow)); + + if (!railWindow) + return FALSE; + + railWindow->wfc = wfc; + railWindow->dwStyle = windowState->style; + railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES; + railWindow->dwExStyle = windowState->extendedStyle; + railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES; + railWindow->x = windowState->windowOffsetX; + railWindow->y = windowState->windowOffsetY; + railWindow->width = windowState->windowWidth; + railWindow->height = windowState->windowHeight; + + if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + const WCHAR* str = (const WCHAR*)windowState->titleInfo.string; + char* title = NULL; + + if (windowState->titleInfo.length == 0) + { + if (!(title = _strdup(""))) + { + WLog_ERR(TAG, "failed to duplicate empty window title string"); + /* error handled below */ + } + } + else if (!(title = ConvertWCharNToUtf8Alloc( + str, windowState->titleInfo.length / sizeof(WCHAR), NULL))) + { + WLog_ERR(TAG, "failed to convert window title"); + /* error handled below */ + } + + railWindow->title = title; + } + else + { + if (!(railWindow->title = _strdup("RdpRailWindow"))) + WLog_ERR(TAG, "failed to duplicate default window title string"); + } + + if (!railWindow->title) + { + free(railWindow); + return FALSE; + } + + titleW = ConvertUtf8ToWCharAlloc(railWindow->title, NULL); + hInstance = GetModuleHandle(NULL); + + wndClassEx.cbSize = sizeof(WNDCLASSEX); + wndClassEx.style = 0; + wndClassEx.lpfnWndProc = wf_RailWndProc; + wndClassEx.cbClsExtra = 0; + wndClassEx.cbWndExtra = 0; + wndClassEx.hIcon = NULL; + wndClassEx.hCursor = NULL; + wndClassEx.hbrBackground = NULL; + wndClassEx.lpszMenuName = NULL; + wndClassEx.lpszClassName = _T("RdpRailWindow"); + wndClassEx.hInstance = hInstance; + wndClassEx.hIconSm = NULL; + RegisterClassEx(&wndClassEx); + railWindow->hWnd = CreateWindowExW(railWindow->dwExStyle, /* dwExStyle */ + _T("RdpRailWindow"), /* lpClassName */ + titleW, /* lpWindowName */ + railWindow->dwStyle, /* dwStyle */ + railWindow->x, /* x */ + railWindow->y, /* y */ + railWindow->width, /* nWidth */ + railWindow->height, /* nHeight */ + NULL, /* hWndParent */ + NULL, /* hMenu */ + hInstance, /* hInstance */ + NULL /* lpParam */ + ); + + if (!railWindow->hWnd) + { + free(titleW); + free(railWindow->title); + free(railWindow); + WLog_ERR(TAG, "CreateWindowExW failed with error %" PRIu32 "", GetLastError()); + return FALSE; + } + + SetWindowLongPtr(railWindow->hWnd, GWLP_USERDATA, (LONG_PTR)railWindow); + rc = HashTable_Insert(wfc->railWindows, (void*)(UINT_PTR)orderInfo->windowId, + (void*)railWindow); + free(titleW); + UpdateWindow(railWindow->hWnd); + return rc; + } + else + { + railWindow = (wfRailWindow*)HashTable_GetItemValue(wfc->railWindows, + (void*)(UINT_PTR)orderInfo->windowId); + } + + if (!railWindow) + return TRUE; + + if ((fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) || (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)) + { + if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) + { + railWindow->x = windowState->windowOffsetX; + railWindow->y = windowState->windowOffsetY; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) + { + railWindow->width = windowState->windowWidth; + railWindow->height = windowState->windowHeight; + } + + SetWindowPos(railWindow->hWnd, NULL, railWindow->x, railWindow->y, railWindow->width, + railWindow->height, 0); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_OWNER) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) + { + railWindow->dwStyle = windowState->style; + railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES; + railWindow->dwExStyle = windowState->extendedStyle; + railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES; + SetWindowLongPtr(railWindow->hWnd, GWL_STYLE, (LONG)railWindow->dwStyle); + SetWindowLongPtr(railWindow->hWnd, GWL_EXSTYLE, (LONG)railWindow->dwExStyle); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) + { + ShowWindow(railWindow->hWnd, windowState->showState); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + const WCHAR* str = (const WCHAR*)windowState->titleInfo.string; + char* title = NULL; + + if (windowState->titleInfo.length == 0) + { + if (!(title = _strdup(""))) + { + WLog_ERR(TAG, "failed to duplicate empty window title string"); + return FALSE; + } + } + else if (!(title = ConvertWCharNToUtf8Alloc( + str, windowState->titleInfo.length / sizeof(WCHAR), NULL))) + { + WLog_ERR(TAG, "failed to convert window title"); + return FALSE; + } + + free(railWindow->title); + railWindow->title = title; + SetWindowTextW(railWindow->hWnd, str); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) + { + HRGN hWndRect; + HRGN hWndRects; + RECTANGLE_16* rect; + + if (windowState->numWindowRects > 0) + { + rect = &(windowState->windowRects[0]); + hWndRects = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom); + + for (UINT32 index = 1; index < windowState->numWindowRects; index++) + { + rect = &(windowState->windowRects[index]); + hWndRect = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom); + CombineRgn(hWndRects, hWndRects, hWndRect, RGN_OR); + DeleteObject(hWndRect); + } + + SetWindowRgn(railWindow->hWnd, hWndRects, TRUE); + DeleteObject(hWndRects); + } + } + + if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) + { + } + + UpdateWindow(railWindow->hWnd); + return TRUE; +} + +static BOOL wf_rail_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + wfRailWindow* railWindow = NULL; + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailWindowDelete"); + railWindow = (wfRailWindow*)HashTable_GetItemValue(wfc->railWindows, + (void*)(UINT_PTR)orderInfo->windowId); + + if (!railWindow) + return TRUE; + + HashTable_Remove(wfc->railWindows, (void*)(UINT_PTR)orderInfo->windowId); + DestroyWindow(railWindow->hWnd); + free(railWindow); + return TRUE; +} + +static BOOL wf_rail_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_ICON_ORDER* windowIcon) +{ + HDC hDC; + int bpp; + int width; + int height; + HICON hIcon; + BOOL bigIcon; + ICONINFO iconInfo = { 0 }; + BITMAPINFO bitmapInfo = { 0 }; + wfRailWindow* railWindow; + BITMAPINFOHEADER* bitmapInfoHeader; + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailWindowIcon"); + PrintRailIconInfo(orderInfo, windowIcon->iconInfo); + railWindow = (wfRailWindow*)HashTable_GetItemValue(wfc->railWindows, + (void*)(UINT_PTR)orderInfo->windowId); + + if (!railWindow) + return TRUE; + + bigIcon = (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? TRUE : FALSE; + hDC = GetDC(railWindow->hWnd); + iconInfo.fIcon = TRUE; + iconInfo.xHotspot = 0; + iconInfo.yHotspot = 0; + + bitmapInfoHeader = &(bitmapInfo.bmiHeader); + bpp = windowIcon->iconInfo->bpp; + width = windowIcon->iconInfo->width; + height = windowIcon->iconInfo->height; + bitmapInfoHeader->biSize = sizeof(BITMAPINFOHEADER); + bitmapInfoHeader->biWidth = width; + bitmapInfoHeader->biHeight = height; + bitmapInfoHeader->biPlanes = 1; + bitmapInfoHeader->biBitCount = bpp; + bitmapInfoHeader->biCompression = 0; + bitmapInfoHeader->biSizeImage = height * width * ((bpp + 7) / 8); + bitmapInfoHeader->biXPelsPerMeter = width; + bitmapInfoHeader->biYPelsPerMeter = height; + bitmapInfoHeader->biClrUsed = 0; + bitmapInfoHeader->biClrImportant = 0; + iconInfo.hbmMask = CreateDIBitmap(hDC, bitmapInfoHeader, CBM_INIT, + windowIcon->iconInfo->bitsMask, &bitmapInfo, DIB_RGB_COLORS); + iconInfo.hbmColor = + CreateDIBitmap(hDC, bitmapInfoHeader, CBM_INIT, windowIcon->iconInfo->bitsColor, + &bitmapInfo, DIB_RGB_COLORS); + hIcon = CreateIconIndirect(&iconInfo); + + if (hIcon) + { + WPARAM wParam; + LPARAM lParam; + wParam = (WPARAM)bigIcon ? ICON_BIG : ICON_SMALL; + lParam = (LPARAM)hIcon; + SendMessage(railWindow->hWnd, WM_SETICON, wParam, lParam); + } + + ReleaseDC(NULL, hDC); + + if (windowIcon->iconInfo->cacheEntry != 0xFFFF) + { + /* icon should be cached */ + } + + return TRUE; +} + +static BOOL wf_rail_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_CACHED_ICON_ORDER* windowCachedIcon) +{ + WLog_DBG(TAG, "RailWindowCachedIcon"); + return TRUE; +} + +static void wf_rail_notify_icon_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_ICON) + { + const ICON_INFO* iconInfo = &(notifyIconState->icon); + PrintRailIconInfo(orderInfo, iconInfo); + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) + { + } +} + +static BOOL wf_rail_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailNotifyIconCreate"); + wf_rail_notify_icon_common(context, orderInfo, notifyIconState); + return TRUE; +} + +static BOOL wf_rail_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailNotifyIconUpdate"); + wf_rail_notify_icon_common(context, orderInfo, notifyIconState); + return TRUE; +} + +static BOOL wf_rail_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailNotifyIconDelete"); + return TRUE; +} + +static BOOL wf_rail_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const MONITORED_DESKTOP_ORDER* monitoredDesktop) +{ + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailMonitorDesktop"); + return TRUE; +} + +static BOOL wf_rail_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + wfContext* wfc = (wfContext*)context; + RailClientContext* rail = wfc->rail; + WLog_DBG(TAG, "RailNonMonitorDesktop"); + return TRUE; +} + +void wf_rail_register_update_callbacks(rdpUpdate* update) +{ + rdpWindowUpdate* window = update->window; + window->WindowCreate = wf_rail_window_common; + window->WindowUpdate = wf_rail_window_common; + window->WindowDelete = wf_rail_window_delete; + window->WindowIcon = wf_rail_window_icon; + window->WindowCachedIcon = wf_rail_window_cached_icon; + window->NotifyIconCreate = wf_rail_notify_icon_create; + window->NotifyIconUpdate = wf_rail_notify_icon_update; + window->NotifyIconDelete = wf_rail_notify_icon_delete; + window->MonitoredDesktop = wf_rail_monitored_desktop; + window->NonMonitoredDesktop = wf_rail_non_monitored_desktop; +} + +/* RemoteApp Virtual Channel Extension */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_execute_result(RailClientContext* context, + const RAIL_EXEC_RESULT_ORDER* execResult) +{ + WLog_DBG(TAG, "RailServerExecuteResult: 0x%08X", execResult->rawResult); + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_system_param(RailClientContext* context, + const RAIL_SYSPARAM_ORDER* sysparam) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_handshake(RailClientContext* context, + const RAIL_HANDSHAKE_ORDER* handshake) +{ + return client_rail_server_start_cmd(context); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_handshake_ex(RailClientContext* context, + const RAIL_HANDSHAKE_EX_ORDER* handshakeEx) +{ + return client_rail_server_start_cmd(context); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_local_move_size(RailClientContext* context, + const RAIL_LOCALMOVESIZE_ORDER* localMoveSize) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_min_max_info(RailClientContext* context, + const RAIL_MINMAXINFO_ORDER* minMaxInfo) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_language_bar_info(RailClientContext* context, + const RAIL_LANGBAR_INFO_ORDER* langBarInfo) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT wf_rail_server_get_appid_response(RailClientContext* context, + const RAIL_GET_APPID_RESP_ORDER* getAppIdResp) +{ + return CHANNEL_RC_OK; +} + +void wf_rail_invalidate_region(wfContext* wfc, REGION16* invalidRegion) +{ + RECT updateRect; + RECTANGLE_16 windowRect; + ULONG_PTR* pKeys = NULL; + wfRailWindow* railWindow; + const RECTANGLE_16* extents; + REGION16 windowInvalidRegion; + region16_init(&windowInvalidRegion); + size_t count = HashTable_GetKeys(wfc->railWindows, &pKeys); + + for (size_t index = 0; index < count; index++) + { + railWindow = (wfRailWindow*)HashTable_GetItemValue(wfc->railWindows, (void*)pKeys[index]); + + if (railWindow) + { + windowRect.left = railWindow->x; + windowRect.top = railWindow->y; + windowRect.right = railWindow->x + railWindow->width; + windowRect.bottom = railWindow->y + railWindow->height; + region16_clear(&windowInvalidRegion); + region16_intersect_rect(&windowInvalidRegion, invalidRegion, &windowRect); + + if (!region16_is_empty(&windowInvalidRegion)) + { + extents = region16_extents(&windowInvalidRegion); + updateRect.left = extents->left - railWindow->x; + updateRect.top = extents->top - railWindow->y; + updateRect.right = extents->right - railWindow->x; + updateRect.bottom = extents->bottom - railWindow->y; + InvalidateRect(railWindow->hWnd, &updateRect, FALSE); + } + } + } + + region16_uninit(&windowInvalidRegion); +} + +BOOL wf_rail_init(wfContext* wfc, RailClientContext* rail) +{ + rdpContext* context = (rdpContext*)wfc; + wfc->rail = rail; + rail->custom = (void*)wfc; + rail->ServerExecuteResult = wf_rail_server_execute_result; + rail->ServerSystemParam = wf_rail_server_system_param; + rail->ServerHandshake = wf_rail_server_handshake; + rail->ServerHandshakeEx = wf_rail_server_handshake_ex; + rail->ServerLocalMoveSize = wf_rail_server_local_move_size; + rail->ServerMinMaxInfo = wf_rail_server_min_max_info; + rail->ServerLanguageBarInfo = wf_rail_server_language_bar_info; + rail->ServerGetAppIdResponse = wf_rail_server_get_appid_response; + wf_rail_register_update_callbacks(context->update); + wfc->railWindows = HashTable_New(TRUE); + return (wfc->railWindows != NULL); +} + +void wf_rail_uninit(wfContext* wfc, RailClientContext* rail) +{ + wfc->rail = NULL; + rail->custom = NULL; + HashTable_Free(wfc->railWindows); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.h b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.h new file mode 100644 index 0000000000000000000000000000000000000000..2b73821e1a7d5a3428f20762b3ee75d734a597c0 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/Windows/wf_rail.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * + * Copyright 2013-2014 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_WIN_RAIL_H +#define FREERDP_CLIENT_WIN_RAIL_H + +typedef struct wf_rail_window wfRailWindow; + +#include "wf_client.h" + +#include + +BOOL wf_rail_init(wfContext* wfc, RailClientContext* rail); +void wf_rail_uninit(wfContext* wfc, RailClientContext* rail); + +void wf_rail_invalidate_region(wfContext* wfc, REGION16* invalidRegion); + +#endif /* FREERDP_CLIENT_WIN_RAIL_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/X11/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5fd376599f8d6dcbfac0b407f8c3a67996fc77ad --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/CMakeLists.txt @@ -0,0 +1,194 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP X11 Client +# +# Copyright 2012 Marc-Andre Moreau +# Copyright 2013 Corey Clayton +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +cmake_minimum_required(VERSION 3.13) + +if(NOT FREERDP_DEFAULT_PROJECT_VERSION) + set(FREERDP_DEFAULT_PROJECT_VERSION "1.0.0.0") +endif() + +project(xfreerdp-client LANGUAGES C VERSION ${FREERDP_DEFAULT_PROJECT_VERSION}) + +message("project ${PROJECT_NAME} is using version ${PROJECT_VERSION}") + +set(MODULE_NAME "xfreerdp") + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_C_EXTENSIONS ON) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/) +include(CommonConfigOptions) + +include(ConfigureFreeRDP) + +find_package(X11 REQUIRED) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../resources) +include_directories(SYSTEM ${X11_INCLUDE_DIRS}) +include_directories(SYSTEM ${OPENSSL_INCLUDE_DIR}) + +set(SRCS + xf_utils.h + xf_utils.c + xf_gfx.c + xf_gfx.h + xf_rail.c + xf_rail.h + xf_input.c + xf_input.h + xf_event.c + xf_event.h + xf_floatbar.c + xf_floatbar.h + xf_input.c + xf_input.h + xf_channels.c + xf_channels.h + xf_cliprdr.c + xf_cliprdr.h + xf_monitor.c + xf_monitor.h + xf_disp.c + xf_disp.h + xf_graphics.c + xf_graphics.h + xf_keyboard.c + xf_keyboard.h + xf_video.c + xf_video.h + xf_window.c + xf_window.h + xf_client.c + xf_client.h +) + +if(CHANNEL_TSMF_CLIENT) + list(APPEND SRCS xf_tsmf.c xf_tsmf.h) +endif() + +if(CLIENT_INTERFACE_SHARED) + addtargetwithresourcefile(${PROJECT_NAME} "SHARED" "${PROJECT_VERSION}" SRCS) +else() + addtargetwithresourcefile(${PROJECT_NAME} "STATIC" "${PROJECT_VERSION}" SRCS) +endif() +target_include_directories(${PROJECT_NAME} INTERFACE $) + +set(PRIV_LIBS ${X11_LIBRARIES}) + +find_package(X11 REQUIRED) +if(X11_XShm_FOUND) + add_compile_definitions(WITH_XSHM) + include_directories(SYSTEM ${X11_XShm_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xext_LIB}) +endif() + +option(WITH_XINERAMA "[X11] enable xinerama" ON) +if(WITH_XINERAMA) + find_package(X11 REQUIRED) + if(X11_Xinerama_FOUND) + add_compile_definitions(WITH_XINERAMA) + include_directories(SYSTEM ${X11_Xinerama_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xinerama_LIB}) + endif() +endif() + +option(WITH_XEXT "[X11] enable Xext" ON) +if(WITH_XEXT) + find_package(X11 REQUIRED) + if(X11_Xext_FOUND) + add_compile_definitions(WITH_XEXT) + list(APPEND PRIV_LIBS ${X11_Xext_LIB}) + endif() +endif() + +option(WITH_XCURSOR "[X11] enable Xcursor" ON) +if(WITH_XCURSOR) + find_package(X11 REQUIRED) + if(X11_Xcursor_FOUND) + add_compile_definitions(WITH_XCURSOR) + include_directories(SYSTEM ${X11_Xcursor_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xcursor_LIB}) + endif() +endif() + +option(WITH_XV "[X11] enable Xv" ON) +if(WITH_XV) + find_package(X11 REQUIRED) + if(X11_Xv_FOUND) + add_compile_definitions(WITH_XV) + include_directories(SYSTEM ${X11_Xv_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xv_LIB}) + endif() +endif() + +option(WITH_XI "[X11] enable Xi" ON) +if(WITH_XI) + find_package(X11 REQUIRED) + if(X11_Xi_FOUND) + add_compile_definitions(WITH_XI) + include_directories(SYSTEM ${X11_Xi_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xi_LIB}) + endif() +endif() + +option(WITH_XRENDER "[X11] enable XRender" ON) +if(WITH_XRENDER) + find_package(X11 REQUIRED) + if(X11_Xrender_FOUND) + add_compile_definitions(WITH_XRENDER) + include_directories(SYSTEM ${X11_Xrender_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xrender_LIB}) + endif() +endif() + +option(WITH_XRANDR "[X11] enable XRandR" ON) +if(WITH_XRANDR) + find_package(X11 REQUIRED) + if(X11_Xrandr_FOUND) + add_compile_definitions(WITH_XRANDR) + include_directories(SYSTEM ${X11_Xrandr_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xrandr_LIB}) + endif() +endif() + +option(WITH_XFIXES "[X11] enable Xfixes" ON) +if(WITH_XFIXES) + find_package(X11 REQUIRED) + if(X11_Xfixes_FOUND) + add_compile_definitions(WITH_XFIXES) + include_directories(SYSTEM ${X11_Xfixes_INCLUDE_PATH}) + list(APPEND PRIV_LIBS ${X11_Xfixes_LIB}) + endif() +endif() + +list(APPEND PUB_LIBS freerdp-client) + +list(APPEND PRIV_LIBS m) +if(NOT APPLE) + list(APPEND PRIV_LIBS rt) +endif() +target_link_libraries(${PROJECT_NAME} PUBLIC ${PUB_LIBS}) +target_link_libraries(${PROJECT_NAME} PRIVATE ${PRIV_LIBS}) + +if(WITH_CLIENT_INTERFACE) + install(TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) +endif() +add_subdirectory(cli) +add_subdirectory(man) + +set_property(TARGET ${PROJECT_NAME} PROPERTY FOLDER "Client/X11") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/ModuleOptions.cmake b/local-test-freerdp-full-01/afc-freerdp/client/X11/ModuleOptions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..de108a40dacb2775dba8935834e1cf227f2a2260 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/ModuleOptions.cmake @@ -0,0 +1,3 @@ +set(FREERDP_CLIENT_NAME "xfreerdp") +set(FREERDP_CLIENT_PLATFORM "X11") +set(FREERDP_CLIENT_VENDOR "FreeRDP") diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.c new file mode 100644 index 0000000000000000000000000000000000000000..71776225bebb8e1291fd606f1c3edb1ac1b224c6 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.c @@ -0,0 +1,132 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Channels + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include "xf_channels.h" + +#include "xf_client.h" +#include "xfreerdp.h" + +#include "xf_gfx.h" +#if defined(CHANNEL_TSMF_CLIENT) +#include "xf_tsmf.h" +#endif +#include "xf_rail.h" +#include "xf_cliprdr.h" +#include "xf_disp.h" +#include "xf_video.h" + +void xf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e) +{ + xfContext* xfc = (xfContext*)context; + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(e); + WINPR_ASSERT(e->name); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (FALSE) + { + } +#if defined(CHANNEL_TSMF_CLIENT) + else if (strcmp(e->name, TSMF_DVC_CHANNEL_NAME) == 0) + { + xf_tsmf_init(xfc, (TsmfClientContext*)e->pInterface); + } +#endif + else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) + { + xf_graphics_pipeline_init(xfc, (RdpgfxClientContext*)e->pInterface); + } + else if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + xf_rail_init(xfc, (RailClientContext*)e->pInterface); + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + xf_cliprdr_init(xfc, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + xf_disp_init(xfc->xfDisp, (DispClientContext*)e->pInterface); + } + else if (strcmp(e->name, VIDEO_CONTROL_DVC_CHANNEL_NAME) == 0) + { + if (freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)) + gdi_video_control_init(xfc->common.context.gdi, (VideoClientContext*)e->pInterface); + else + xf_video_control_init(xfc, (VideoClientContext*)e->pInterface); + } + else + freerdp_client_OnChannelConnectedEventHandler(context, e); +} + +void xf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e) +{ + xfContext* xfc = (xfContext*)context; + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(e); + WINPR_ASSERT(e->name); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (FALSE) + { + } + else if (strcmp(e->name, DISP_DVC_CHANNEL_NAME) == 0) + { + xf_disp_uninit(xfc->xfDisp, (DispClientContext*)e->pInterface); + } +#if defined(CHANNEL_TSMF_CLIENT) + else if (strcmp(e->name, TSMF_DVC_CHANNEL_NAME) == 0) + { + xf_tsmf_uninit(xfc, (TsmfClientContext*)e->pInterface); + } +#endif + else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) + { + xf_graphics_pipeline_uninit(xfc, (RdpgfxClientContext*)e->pInterface); + } + else if (strcmp(e->name, RAIL_SVC_CHANNEL_NAME) == 0) + { + xf_rail_uninit(xfc, (RailClientContext*)e->pInterface); + } + else if (strcmp(e->name, CLIPRDR_SVC_CHANNEL_NAME) == 0) + { + xf_cliprdr_uninit(xfc, (CliprdrClientContext*)e->pInterface); + } + else if (strcmp(e->name, VIDEO_CONTROL_DVC_CHANNEL_NAME) == 0) + { + if (freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)) + gdi_video_control_uninit(xfc->common.context.gdi, (VideoClientContext*)e->pInterface); + else + xf_video_control_uninit(xfc, (VideoClientContext*)e->pInterface); + } + else + freerdp_client_OnChannelDisconnectedEventHandler(context, e); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.h new file mode 100644 index 0000000000000000000000000000000000000000..86b00b9530fed0b06648dedaff31f14c360f7064 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_channels.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Channels + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_CHANNELS_H +#define FREERDP_CLIENT_X11_CHANNELS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void xf_OnChannelConnectedEventHandler(void* context, const ChannelConnectedEventArgs* e); +void xf_OnChannelDisconnectedEventHandler(void* context, const ChannelDisconnectedEventArgs* e); + +#endif /* FREERDP_CLIENT_X11_CHANNELS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.c new file mode 100644 index 0000000000000000000000000000000000000000..7bbbe558bea67f450182aa9da9745ca9808d693a --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.c @@ -0,0 +1,2115 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Interface + * + * Copyright 2013 Marc-Andre Moreau + * Copyright 2013 Corey Clayton + * Copyright 2014 Thincast Technologies GmbH + * Copyright 2014 Norbert Federa + * Copyright 2016 Armin Novak + * Copyright 2016 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#ifdef WITH_XRENDER +#include +#endif + +#ifdef WITH_XI +#include +#include +#endif + +#ifdef WITH_XCURSOR +#include +#endif + +#ifdef WITH_XINERAMA +#include +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include "xf_rail.h" +#if defined(CHANNEL_TSMF_CLIENT) +#include "xf_tsmf.h" +#endif +#include "xf_event.h" +#include "xf_input.h" +#include "xf_cliprdr.h" +#include "xf_disp.h" +#include "xf_video.h" +#include "xf_monitor.h" +#include "xf_graphics.h" +#include "xf_keyboard.h" +#include "xf_channels.h" +#include "xf_client.h" +#include "xfreerdp.h" +#include "xf_utils.h" + +#include +#define TAG CLIENT_TAG("x11") + +#define MIN_PIXEL_DIFF 0.001 + +struct xf_exit_code_map_t +{ + DWORD error; + int rc; +}; +static const struct xf_exit_code_map_t xf_exit_code_map[] = { + { FREERDP_ERROR_AUTHENTICATION_FAILED, XF_EXIT_AUTH_FAILURE }, + { FREERDP_ERROR_SECURITY_NEGO_CONNECT_FAILED, XF_EXIT_NEGO_FAILURE }, + { FREERDP_ERROR_CONNECT_LOGON_FAILURE, XF_EXIT_LOGON_FAILURE }, + { FREERDP_ERROR_CONNECT_ACCOUNT_LOCKED_OUT, XF_EXIT_ACCOUNT_LOCKED_OUT }, + { FREERDP_ERROR_PRE_CONNECT_FAILED, XF_EXIT_PRE_CONNECT_FAILED }, + { FREERDP_ERROR_CONNECT_UNDEFINED, XF_EXIT_CONNECT_UNDEFINED }, + { FREERDP_ERROR_POST_CONNECT_FAILED, XF_EXIT_POST_CONNECT_FAILED }, + { FREERDP_ERROR_DNS_ERROR, XF_EXIT_DNS_ERROR }, + { FREERDP_ERROR_DNS_NAME_NOT_FOUND, XF_EXIT_DNS_NAME_NOT_FOUND }, + { FREERDP_ERROR_CONNECT_FAILED, XF_EXIT_CONNECT_FAILED }, + { FREERDP_ERROR_MCS_CONNECT_INITIAL_ERROR, XF_EXIT_MCS_CONNECT_INITIAL_ERROR }, + { FREERDP_ERROR_TLS_CONNECT_FAILED, XF_EXIT_TLS_CONNECT_FAILED }, + { FREERDP_ERROR_INSUFFICIENT_PRIVILEGES, XF_EXIT_INSUFFICIENT_PRIVILEGES }, + { FREERDP_ERROR_CONNECT_CANCELLED, XF_EXIT_CONNECT_CANCELLED }, + { FREERDP_ERROR_CONNECT_TRANSPORT_FAILED, XF_EXIT_CONNECT_TRANSPORT_FAILED }, + { FREERDP_ERROR_CONNECT_PASSWORD_EXPIRED, XF_EXIT_CONNECT_PASSWORD_EXPIRED }, + { FREERDP_ERROR_CONNECT_PASSWORD_MUST_CHANGE, XF_EXIT_CONNECT_PASSWORD_MUST_CHANGE }, + { FREERDP_ERROR_CONNECT_KDC_UNREACHABLE, XF_EXIT_CONNECT_KDC_UNREACHABLE }, + { FREERDP_ERROR_CONNECT_ACCOUNT_DISABLED, XF_EXIT_CONNECT_ACCOUNT_DISABLED }, + { FREERDP_ERROR_CONNECT_PASSWORD_CERTAINLY_EXPIRED, + XF_EXIT_CONNECT_PASSWORD_CERTAINLY_EXPIRED }, + { FREERDP_ERROR_CONNECT_CLIENT_REVOKED, XF_EXIT_CONNECT_CLIENT_REVOKED }, + { FREERDP_ERROR_CONNECT_WRONG_PASSWORD, XF_EXIT_CONNECT_WRONG_PASSWORD }, + { FREERDP_ERROR_CONNECT_ACCESS_DENIED, XF_EXIT_CONNECT_ACCESS_DENIED }, + { FREERDP_ERROR_CONNECT_ACCOUNT_RESTRICTION, XF_EXIT_CONNECT_ACCOUNT_RESTRICTION }, + { FREERDP_ERROR_CONNECT_ACCOUNT_EXPIRED, XF_EXIT_CONNECT_ACCOUNT_EXPIRED }, + { FREERDP_ERROR_CONNECT_LOGON_TYPE_NOT_GRANTED, XF_EXIT_CONNECT_LOGON_TYPE_NOT_GRANTED }, + { FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS, XF_EXIT_CONNECT_NO_OR_MISSING_CREDENTIALS } +}; + +static BOOL xf_setup_x11(xfContext* xfc); +static void xf_teardown_x11(xfContext* xfc); + +static int xf_map_error_to_exit_code(DWORD error) +{ + for (size_t x = 0; x < ARRAYSIZE(xf_exit_code_map); x++) + { + const struct xf_exit_code_map_t* cur = &xf_exit_code_map[x]; + if (cur->error == error) + return cur->rc; + } + + return XF_EXIT_CONN_FAILED; +} +static int (*def_error_handler)(Display*, XErrorEvent*); +static int xf_error_handler_ex(Display* d, XErrorEvent* ev); +static void xf_check_extensions(xfContext* context); +static void xf_window_free(xfContext* xfc); +static BOOL xf_get_pixmap_info(xfContext* xfc); + +#ifdef WITH_XRENDER +static void xf_draw_screen_scaled(xfContext* xfc, int x, int y, int w, int h) +{ + XTransform transform = { 0 }; + Picture windowPicture = 0; + Picture primaryPicture = 0; + XRenderPictureAttributes pa; + XRenderPictFormat* picFormat = NULL; + int x2 = 0; + int y2 = 0; + const char* filter = NULL; + WINPR_ASSERT(xfc); + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (xfc->scaledWidth <= 0 || xfc->scaledHeight <= 0) + { + WLog_ERR(TAG, "the current window dimensions are invalid"); + return; + } + + if (freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) <= 0 || + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) <= 0) + { + WLog_ERR(TAG, "the window dimensions are invalid"); + return; + } + + const double xScalingFactor = 1.0 * + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) / + (double)xfc->scaledWidth; + const double yScalingFactor = 1.0 * + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) / + (double)xfc->scaledHeight; + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + XSetForeground(xfc->display, xfc->gc, 0); + /* Black out possible space between desktop and window borders */ + { + XRectangle box1 = { 0, 0, WINPR_ASSERTING_INT_CAST(UINT16, xfc->window->width), + WINPR_ASSERTING_INT_CAST(UINT16, xfc->window->height) }; + XRectangle box2 = { WINPR_ASSERTING_INT_CAST(INT16, xfc->offset_x), + WINPR_ASSERTING_INT_CAST(INT16, xfc->offset_y), + WINPR_ASSERTING_INT_CAST(UINT16, xfc->scaledWidth), + WINPR_ASSERTING_INT_CAST(UINT16, xfc->scaledHeight) }; + Region reg1 = XCreateRegion(); + Region reg2 = XCreateRegion(); + XUnionRectWithRegion(&box1, reg1, reg1); + XUnionRectWithRegion(&box2, reg2, reg2); + + if (XSubtractRegion(reg1, reg2, reg1) && !XEmptyRegion(reg1)) + { + XSetRegion(xfc->display, xfc->gc, reg1); + XFillRectangle(xfc->display, xfc->window->handle, xfc->gc, 0, 0, + WINPR_ASSERTING_INT_CAST(UINT16, xfc->window->width), + WINPR_ASSERTING_INT_CAST(UINT16, xfc->window->height)); + XSetClipMask(xfc->display, xfc->gc, None); + } + + XDestroyRegion(reg1); + XDestroyRegion(reg2); + } + picFormat = XRenderFindVisualFormat(xfc->display, xfc->visual); + pa.subwindow_mode = IncludeInferiors; + primaryPicture = + XRenderCreatePicture(xfc->display, xfc->primary, picFormat, CPSubwindowMode, &pa); + windowPicture = + XRenderCreatePicture(xfc->display, xfc->window->handle, picFormat, CPSubwindowMode, &pa); + /* avoid blurry filter when scaling factor is 2x, 3x, etc + * useful when the client has high-dpi monitor */ + filter = FilterBilinear; + if (fabs(xScalingFactor - yScalingFactor) < MIN_PIXEL_DIFF) + { + const double inverseX = 1.0 / xScalingFactor; + const double inverseRoundedX = round(inverseX); + const double absInverse = fabs(inverseX - inverseRoundedX); + + if (absInverse < MIN_PIXEL_DIFF) + filter = FilterNearest; + } + XRenderSetPictureFilter(xfc->display, primaryPicture, filter, 0, 0); + transform.matrix[0][0] = XDoubleToFixed(xScalingFactor); + transform.matrix[0][1] = XDoubleToFixed(0.0); + transform.matrix[0][2] = XDoubleToFixed(0.0); + transform.matrix[1][0] = XDoubleToFixed(0.0); + transform.matrix[1][1] = XDoubleToFixed(yScalingFactor); + transform.matrix[1][2] = XDoubleToFixed(0.0); + transform.matrix[2][0] = XDoubleToFixed(0.0); + transform.matrix[2][1] = XDoubleToFixed(0.0); + transform.matrix[2][2] = XDoubleToFixed(1.0); + /* calculate and fix up scaled coordinates */ + x2 = x + w; + y2 = y + h; + + const double dx1 = floor(x / xScalingFactor); + const double dy1 = floor(y / yScalingFactor); + const double dx2 = ceil(x2 / xScalingFactor); + const double dy2 = ceil(y2 / yScalingFactor); + x = ((int)dx1) - 1; + y = ((int)dy1) - 1; + w = ((int)dx2) + 1 - x; + h = ((int)dy2) + 1 - y; + XRenderSetPictureTransform(xfc->display, primaryPicture, &transform); + XRenderComposite(xfc->display, PictOpSrc, primaryPicture, 0, windowPicture, x, y, 0, 0, + xfc->offset_x + x, xfc->offset_y + y, WINPR_ASSERTING_INT_CAST(uint32_t, w), + WINPR_ASSERTING_INT_CAST(uint32_t, h)); + XRenderFreePicture(xfc->display, primaryPicture); + XRenderFreePicture(xfc->display, windowPicture); +} + +BOOL xf_picture_transform_required(xfContext* xfc) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if ((xfc->offset_x != 0) || (xfc->offset_y != 0) || + (xfc->scaledWidth != (INT64)freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)) || + (xfc->scaledHeight != (INT64)freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))) + { + return TRUE; + } + + return FALSE; +} +#endif /* WITH_XRENDER defined */ + +void xf_draw_screen_(xfContext* xfc, int x, int y, int w, int h, const char* fkt, const char* file, + int line) +{ + if (!xfc) + { + WLog_DBG(TAG, "called from [%s] xfc=%p", fkt, xfc); + return; + } + + if (w == 0 || h == 0) + { + WLog_WARN(TAG, "invalid width and/or height specified: w=%d h=%d", w, h); + return; + } + + if (!xfc->window) + { + WLog_WARN(TAG, "invalid xfc->window=%p", xfc->window); + return; + } + +#ifdef WITH_XRENDER + + if (xf_picture_transform_required(xfc)) + { + xf_draw_screen_scaled(xfc, x, y, w, h); + return; + } + +#endif + XCopyArea(xfc->display, xfc->primary, xfc->window->handle, xfc->gc, x, y, + WINPR_ASSERTING_INT_CAST(uint32_t, w), WINPR_ASSERTING_INT_CAST(uint32_t, h), x, y); +} + +static BOOL xf_desktop_resize(rdpContext* context) +{ + rdpSettings* settings = NULL; + xfContext* xfc = (xfContext*)context; + + WINPR_ASSERT(xfc); + + settings = context->settings; + WINPR_ASSERT(settings); + + if (xfc->primary) + { + BOOL same = (xfc->primary == xfc->drawing) ? TRUE : FALSE; + XFreePixmap(xfc->display, xfc->primary); + + WINPR_ASSERT(xfc->depth != 0); + if (!(xfc->primary = + XCreatePixmap(xfc->display, xfc->drawable, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth)))) + return FALSE; + + if (same) + xfc->drawing = xfc->primary; + } + +#ifdef WITH_XRENDER + + if (!freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + { + xfc->scaledWidth = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + xfc->scaledHeight = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + } + +#endif + + if (!xfc->fullscreen) + { + xf_ResizeDesktopWindow( + xfc, xfc->window, + WINPR_ASSERTING_INT_CAST(int, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)), + WINPR_ASSERTING_INT_CAST(int, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))); + } + else + { +#ifdef WITH_XRENDER + + if (!freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) +#endif + { + /* Update the saved width and height values the window will be + * resized to when toggling out of fullscreen */ + xfc->savedWidth = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + xfc->savedHeight = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + } + + XSetFunction(xfc->display, xfc->gc, GXcopy); + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + XSetForeground(xfc->display, xfc->gc, 0); + XFillRectangle(xfc->display, xfc->drawable, xfc->gc, 0, 0, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + } + + return TRUE; +} + +static BOOL xf_paint(xfContext* xfc, const GDI_RGN* region) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(region); + + if (xfc->remote_app) + { + const RECTANGLE_16 rect = { .left = WINPR_ASSERTING_INT_CAST(UINT16, region->x), + .top = WINPR_ASSERTING_INT_CAST(UINT16, region->y), + .right = + WINPR_ASSERTING_INT_CAST(UINT16, region->x + region->w), + .bottom = + WINPR_ASSERTING_INT_CAST(UINT16, region->y + region->h) }; + xf_rail_paint(xfc, &rect); + } + else + { + XPutImage(xfc->display, xfc->primary, xfc->gc, xfc->image, region->x, region->y, region->x, + region->y, WINPR_ASSERTING_INT_CAST(UINT16, region->w), + WINPR_ASSERTING_INT_CAST(UINT16, region->h)); + xf_draw_screen(xfc, region->x, region->y, region->w, region->h); + } + return TRUE; +} + +static BOOL xf_end_paint(rdpContext* context) +{ + xfContext* xfc = (xfContext*)context; + rdpGdi* gdi = context->gdi; + + if (gdi->suppressOutput) + return TRUE; + + HGDI_DC hdc = gdi->primary->hdc; + + if (!xfc->complex_regions) + { + const GDI_RGN* rgn = hdc->hwnd->invalid; + if (rgn->null) + return TRUE; + xf_lock_x11(xfc); + if (!xf_paint(xfc, rgn)) + return FALSE; + xf_unlock_x11(xfc); + } + else + { + const INT32 ninvalid = hdc->hwnd->ninvalid; + const GDI_RGN* cinvalid = hdc->hwnd->cinvalid; + + if (hdc->hwnd->ninvalid < 1) + return TRUE; + + xf_lock_x11(xfc); + + for (INT32 i = 0; i < ninvalid; i++) + { + const GDI_RGN* rgn = &cinvalid[i]; + if (!xf_paint(xfc, rgn)) + return FALSE; + } + + XFlush(xfc->display); + xf_unlock_x11(xfc); + } + + hdc->hwnd->invalid->null = TRUE; + hdc->hwnd->ninvalid = 0; + return TRUE; +} + +static BOOL xf_sw_desktop_resize(rdpContext* context) +{ + rdpGdi* gdi = context->gdi; + xfContext* xfc = (xfContext*)context; + rdpSettings* settings = context->settings; + BOOL ret = FALSE; + + if (!gdi_resize(gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))) + return FALSE; + + /* Do not lock during gdi_resize, there might still be drawing operations in progress. + * locking will deadlock. */ + xf_lock_x11(xfc); + if (xfc->image) + { + xfc->image->data = NULL; + XDestroyImage(xfc->image); + } + + WINPR_ASSERT(xfc->depth != 0); + if (!(xfc->image = XCreateImage( + xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), ZPixmap, 0, + (char*)gdi->primary_buffer, WINPR_ASSERTING_INT_CAST(uint32_t, gdi->width), + WINPR_ASSERTING_INT_CAST(uint32_t, gdi->height), xfc->scanline_pad, + WINPR_ASSERTING_INT_CAST(int, gdi->stride)))) + { + goto out; + } + + xfc->image->byte_order = LSBFirst; + xfc->image->bitmap_bit_order = LSBFirst; + ret = xf_desktop_resize(context); +out: + xf_unlock_x11(xfc); + return ret; +} + +static BOOL xf_process_x_events(freerdp* instance) +{ + BOOL status = TRUE; + int pending_status = 1; + xfContext* xfc = (xfContext*)instance->context; + + while (pending_status) + { + xf_lock_x11(xfc); + pending_status = XPending(xfc->display); + + if (pending_status) + { + XEvent xevent = { 0 }; + + XNextEvent(xfc->display, &xevent); + status = xf_event_process(instance, &xevent); + } + xf_unlock_x11(xfc); + if (!status) + break; + } + + return status; +} + +static char* xf_window_get_title(rdpSettings* settings) +{ + BOOL port = 0; + char* windowTitle = NULL; + size_t size = 0; + const char* prefix = "FreeRDP:"; + + if (!settings) + return NULL; + + const char* name = freerdp_settings_get_string(settings, FreeRDP_ServerHostname); + const char* title = freerdp_settings_get_string(settings, FreeRDP_WindowTitle); + + if (title) + return _strdup(title); + + port = (freerdp_settings_get_uint32(settings, FreeRDP_ServerPort) != 3389); + /* Just assume a window title is never longer than a filename... */ + size = strnlen(name, MAX_PATH) + 16; + windowTitle = calloc(size, sizeof(char)); + + if (!windowTitle) + return NULL; + + if (!port) + (void)sprintf_s(windowTitle, size, "%s %s", prefix, name); + else + (void)sprintf_s(windowTitle, size, "%s %s:%" PRIu32, prefix, name, + freerdp_settings_get_uint32(settings, FreeRDP_ServerPort)); + + return windowTitle; +} + +BOOL xf_create_window(xfContext* xfc) +{ + XGCValues gcv = { 0 }; + XEvent xevent = { 0 }; + char* windowTitle = NULL; + + WINPR_ASSERT(xfc); + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + int width = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + int height = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + + const XSetWindowAttributes empty = { 0 }; + xfc->attribs = empty; + + if (xfc->remote_app) + xfc->depth = 32; + else + xfc->depth = DefaultDepthOfScreen(xfc->screen); + + XVisualInfo vinfo = { 0 }; + if (XMatchVisualInfo(xfc->display, xfc->screen_number, xfc->depth, TrueColor, &vinfo)) + { + Window root = XDefaultRootWindow(xfc->display); + xfc->visual = vinfo.visual; + xfc->attribs.colormap = xfc->colormap = + XCreateColormap(xfc->display, root, vinfo.visual, AllocNone); + } + else + { + if (xfc->remote_app) + { + WLog_WARN(TAG, "running in remote app mode, but XServer does not support transparency"); + WLog_WARN(TAG, "display of remote applications might be distorted (black frames, ...)"); + } + xfc->depth = DefaultDepthOfScreen(xfc->screen); + xfc->visual = DefaultVisual(xfc->display, xfc->screen_number); + xfc->attribs.colormap = xfc->colormap = DefaultColormap(xfc->display, xfc->screen_number); + } + + /* + * Detect if the server visual has an inverted colormap + * (BGR vs RGB, or red being the least significant byte) + */ + if (vinfo.red_mask & 0xFF) + { + xfc->invert = FALSE; + } + + if (!xfc->remote_app) + { + xfc->attribs.background_pixel = BlackPixelOfScreen(xfc->screen); + xfc->attribs.border_pixel = WhitePixelOfScreen(xfc->screen); + xfc->attribs.backing_store = xfc->primary ? NotUseful : Always; + xfc->attribs.override_redirect = False; + + xfc->attribs.bit_gravity = NorthWestGravity; + xfc->attribs.win_gravity = NorthWestGravity; + xfc->attribs_mask = CWBackPixel | CWBackingStore | CWOverrideRedirect | CWColormap | + CWBorderPixel | CWWinGravity | CWBitGravity; + +#ifdef WITH_XRENDER + xfc->offset_x = 0; + xfc->offset_y = 0; +#endif + windowTitle = xf_window_get_title(settings); + + if (!windowTitle) + return FALSE; + +#ifdef WITH_XRENDER + + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) && !xfc->fullscreen) + { + if (freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth) > 0) + width = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth)); + + if (freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight) > 0) + height = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight)); + + xfc->scaledWidth = width; + xfc->scaledHeight = height; + } + +#endif + xfc->window = xf_CreateDesktopWindow(xfc, windowTitle, width, height); + free(windowTitle); + + if (xfc->fullscreen) + xf_SetWindowFullscreen(xfc, xfc->window, xfc->fullscreen); + + xfc->unobscured = (xevent.xvisibility.state == VisibilityUnobscured); + XSetWMProtocols(xfc->display, xfc->window->handle, &(xfc->WM_DELETE_WINDOW), 1); + xfc->drawable = xfc->window->handle; + } + else + { + xfc->attribs.border_pixel = 0; + xfc->attribs.background_pixel = 0; + xfc->attribs.backing_store = xfc->primary ? NotUseful : Always; + xfc->attribs.override_redirect = False; + + xfc->attribs.bit_gravity = NorthWestGravity; + xfc->attribs.win_gravity = NorthWestGravity; + xfc->attribs_mask = CWBackPixel | CWBackingStore | CWOverrideRedirect | CWColormap | + CWBorderPixel | CWWinGravity | CWBitGravity; + + xfc->drawable = xf_CreateDummyWindow(xfc); + } + + if (!xfc->gc) + xfc->gc = XCreateGC(xfc->display, xfc->drawable, GCGraphicsExposures, &gcv); + + WINPR_ASSERT(xfc->depth != 0); + if (!xfc->primary) + xfc->primary = XCreatePixmap(xfc->display, xfc->drawable, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth)); + + xfc->drawing = xfc->primary; + + if (!xfc->bitmap_mono) + xfc->bitmap_mono = XCreatePixmap(xfc->display, xfc->drawable, 8, 8, 1); + + if (!xfc->gc_mono) + xfc->gc_mono = XCreateGC(xfc->display, xfc->bitmap_mono, GCGraphicsExposures, &gcv); + + XSetFunction(xfc->display, xfc->gc, GXcopy); + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + XSetForeground(xfc->display, xfc->gc, BlackPixelOfScreen(xfc->screen)); + XFillRectangle(xfc->display, xfc->primary, xfc->gc, 0, 0, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + XFlush(xfc->display); + + return TRUE; +} + +BOOL xf_create_image(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + if (!xfc->image) + { + const rdpSettings* settings = xfc->common.context.settings; + rdpGdi* cgdi = xfc->common.context.gdi; + WINPR_ASSERT(cgdi); + + WINPR_ASSERT(xfc->depth != 0); + xfc->image = + XCreateImage(xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), + ZPixmap, 0, (char*)cgdi->primary_buffer, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), + xfc->scanline_pad, WINPR_ASSERTING_INT_CAST(int, cgdi->stride)); + xfc->image->byte_order = LSBFirst; + xfc->image->bitmap_bit_order = LSBFirst; + } + return TRUE; +} + +static void xf_window_free(xfContext* xfc) +{ + if (xfc->window) + { + xf_DestroyDesktopWindow(xfc, xfc->window); + xfc->window = NULL; + } + +#if defined(CHANNEL_TSMF_CLIENT) + if (xfc->xv_context) + { + xf_tsmf_uninit(xfc, NULL); + xfc->xv_context = NULL; + } +#endif + + if (xfc->image) + { + xfc->image->data = NULL; + XDestroyImage(xfc->image); + xfc->image = NULL; + } + + if (xfc->bitmap_mono) + { + XFreePixmap(xfc->display, xfc->bitmap_mono); + xfc->bitmap_mono = 0; + } + + if (xfc->gc_mono) + { + XFreeGC(xfc->display, xfc->gc_mono); + xfc->gc_mono = 0; + } + + if (xfc->primary) + { + XFreePixmap(xfc->display, xfc->primary); + xfc->primary = 0; + } + + if (xfc->gc) + { + XFreeGC(xfc->display, xfc->gc); + xfc->gc = 0; + } +} + +void xf_toggle_fullscreen(xfContext* xfc) +{ + WindowStateChangeEventArgs e = { 0 }; + rdpContext* context = (rdpContext*)xfc; + rdpSettings* settings = context->settings; + + /* + when debugging, ungrab keyboard when toggling fullscreen + to allow keyboard usage on the debugger + */ + if (xfc->debug) + xf_ungrab(xfc); + + xfc->fullscreen = (xfc->fullscreen) ? FALSE : TRUE; + xfc->decorations = + (xfc->fullscreen) ? FALSE : freerdp_settings_get_bool(settings, FreeRDP_Decorations); + xf_SetWindowFullscreen(xfc, xfc->window, xfc->fullscreen); + EventArgsInit(&e, "xfreerdp"); + e.state = xfc->fullscreen ? FREERDP_WINDOW_STATE_FULLSCREEN : 0; + PubSub_OnWindowStateChange(context->pubSub, context, &e); +} + +void xf_minimize(xfContext* xfc) +{ + WindowStateChangeEventArgs e = { 0 }; + rdpContext* context = (rdpContext*)xfc; + WINPR_ASSERT(context); + + /* + when debugging, ungrab keyboard when toggling fullscreen + to allow keyboard usage on the debugger + */ + if (xfc->debug) + xf_ungrab(xfc); + + xf_SetWindowMinimized(xfc, xfc->window); + + e.state = xfc->fullscreen ? FREERDP_WINDOW_STATE_FULLSCREEN : 0; + PubSub_OnWindowStateChange(context->pubSub, context, &e); +} + +void xf_lock_x11_(xfContext* xfc, const char* fkt) +{ + if (!xfc->UseXThreads) + (void)WaitForSingleObject(xfc->mutex, INFINITE); + else + XLockDisplay(xfc->display); + + xfc->locked++; +} + +void xf_unlock_x11_(xfContext* xfc, const char* fkt) +{ + if (xfc->locked == 0) + WLog_WARN(TAG, "X11: trying to unlock although not locked!"); + else + xfc->locked--; + + if (!xfc->UseXThreads) + (void)ReleaseMutex(xfc->mutex); + else + XUnlockDisplay(xfc->display); +} + +static BOOL xf_get_pixmap_info(xfContext* xfc) +{ + int pf_count = 0; + XPixmapFormatValues* pfs = NULL; + + WINPR_ASSERT(xfc->display); + pfs = XListPixmapFormats(xfc->display, &pf_count); + + if (!pfs) + { + WLog_ERR(TAG, "XListPixmapFormats failed"); + return 1; + } + + WINPR_ASSERT(xfc->depth != 0); + for (int i = 0; i < pf_count; i++) + { + const XPixmapFormatValues* pf = &pfs[i]; + + if (pf->depth == xfc->depth) + { + xfc->scanline_pad = pf->scanline_pad; + break; + } + } + + XFree(pfs); + if ((xfc->visual == NULL) || (xfc->scanline_pad == 0)) + return FALSE; + + return TRUE; +} + +static int xf_error_handler(Display* d, XErrorEvent* ev) +{ + char buf[256] = { 0 }; + XGetErrorText(d, ev->error_code, buf, sizeof(buf)); + WLog_ERR(TAG, "%s", buf); + winpr_log_backtrace(TAG, WLOG_ERROR, 20); + +#if 0 + const BOOL do_abort = TRUE; + if (do_abort) + abort(); +#endif + + if (def_error_handler) + return def_error_handler(d, ev); + + return 0; +} + +static int xf_error_handler_ex(Display* d, XErrorEvent* ev) +{ + /* + * ungrab the keyboard, in case a debugger is running in + * another window. This make xf_error_handler() a potential + * debugger breakpoint. + */ + + XUngrabKeyboard(d, CurrentTime); + XUngrabPointer(d, CurrentTime); + return xf_error_handler(d, ev); +} + +static BOOL xf_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) +{ + xfContext* xfc = (xfContext*)context; + WINPR_UNUSED(play_sound); + XkbBell(xfc->display, None, 100, 0); + return TRUE; +} + +static void xf_check_extensions(xfContext* context) +{ + int xkb_opcode = 0; + int xkb_event = 0; + int xkb_error = 0; + int xkb_major = XkbMajorVersion; + int xkb_minor = XkbMinorVersion; + + if (XkbLibraryVersion(&xkb_major, &xkb_minor) && + XkbQueryExtension(context->display, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, + &xkb_minor)) + { + context->xkbAvailable = TRUE; + } + +#ifdef WITH_XRENDER + { + int xrender_event_base = 0; + int xrender_error_base = 0; + + if (XRenderQueryExtension(context->display, &xrender_event_base, &xrender_error_base)) + { + context->xrenderAvailable = TRUE; + } + } +#endif +} + +#ifdef WITH_XI +/* Input device which does NOT have the correct mapping. We must disregard */ +/* this device when trying to find the input device which is the pointer. */ +static const char TEST_PTR_STR[] = "Virtual core XTEST pointer"; +static const size_t TEST_PTR_LEN = sizeof(TEST_PTR_STR) / sizeof(char); +#endif /* WITH_XI */ + +static void xf_get_x11_button_map(xfContext* xfc, unsigned char* x11_map) +{ +#ifdef WITH_XI + int opcode = 0; + int event = 0; + int error = 0; + XDevice* ptr_dev = NULL; + XExtensionVersion* version = NULL; + XDeviceInfo* devices1 = NULL; + XIDeviceInfo* devices2 = NULL; + int num_devices = 0; + + if (XQueryExtension(xfc->display, "XInputExtension", &opcode, &event, &error)) + { + WLog_DBG(TAG, "Searching for XInput pointer device"); + ptr_dev = NULL; + /* loop through every device, looking for a pointer */ + version = XGetExtensionVersion(xfc->display, INAME); + + if (version->major_version >= 2) + { + /* XID of pointer device using XInput version 2 */ + devices2 = XIQueryDevice(xfc->display, XIAllDevices, &num_devices); + + if (devices2) + { + for (int i = 0; i < num_devices; ++i) + { + XIDeviceInfo* dev = &devices2[i]; + if ((dev->use == XISlavePointer) && + (strncmp(dev->name, TEST_PTR_STR, TEST_PTR_LEN) != 0)) + { + ptr_dev = XOpenDevice(xfc->display, + WINPR_ASSERTING_INT_CAST(uint32_t, dev->deviceid)); + if (ptr_dev) + break; + } + } + + XIFreeDeviceInfo(devices2); + } + } + else + { + /* XID of pointer device using XInput version 1 */ + devices1 = XListInputDevices(xfc->display, &num_devices); + + if (devices1) + { + for (int i = 0; i < num_devices; ++i) + { + if ((devices1[i].use == IsXExtensionPointer) && + (strncmp(devices1[i].name, TEST_PTR_STR, TEST_PTR_LEN) != 0)) + { + ptr_dev = XOpenDevice(xfc->display, devices1[i].id); + if (ptr_dev) + break; + } + } + + XFreeDeviceList(devices1); + } + } + + XFree(version); + + /* get button mapping from input extension if there is a pointer device; */ + /* otherwise leave unchanged. */ + if (ptr_dev) + { + WLog_DBG(TAG, "Pointer device: %d", ptr_dev->device_id); + XGetDeviceButtonMapping(xfc->display, ptr_dev, x11_map, NUM_BUTTONS_MAPPED); + XCloseDevice(xfc->display, ptr_dev); + } + else + { + WLog_DBG(TAG, "No pointer device found!"); + } + } + else +#endif /* WITH_XI */ + { + WLog_DBG(TAG, "Get global pointer mapping (no XInput)"); + XGetPointerMapping(xfc->display, x11_map, NUM_BUTTONS_MAPPED); + } +} + +/* Assignment of physical (not logical) mouse buttons to wire flags. */ +/* Notice that the middle button is 2 in X11, but 3 in RDP. */ +static const button_map xf_button_flags[NUM_BUTTONS_MAPPED] = { + { Button1, PTR_FLAGS_BUTTON1 }, + { Button2, PTR_FLAGS_BUTTON3 }, + { Button3, PTR_FLAGS_BUTTON2 }, + { Button4, PTR_FLAGS_WHEEL | 0x78 }, + /* Negative value is 9bit twos complement */ + { Button5, PTR_FLAGS_WHEEL | PTR_FLAGS_WHEEL_NEGATIVE | (0x100 - 0x78) }, + { 6, PTR_FLAGS_HWHEEL | PTR_FLAGS_WHEEL_NEGATIVE | (0x100 - 0x78) }, + { 7, PTR_FLAGS_HWHEEL | 0x78 }, + { 8, PTR_XFLAGS_BUTTON1 }, + { 9, PTR_XFLAGS_BUTTON2 }, + { 97, PTR_XFLAGS_BUTTON1 }, + { 112, PTR_XFLAGS_BUTTON2 } +}; + +static UINT16 get_flags_for_button(size_t button) +{ + for (size_t x = 0; x < ARRAYSIZE(xf_button_flags); x++) + { + const button_map* map = &xf_button_flags[x]; + + if (map->button == button) + return map->flags; + } + + return 0; +} + +void xf_button_map_init(xfContext* xfc) +{ + size_t pos = 0; + /* loop counter for array initialization */ + + /* logical mouse button which is used for each physical mouse */ + /* button (indexed from zero). This is the default map. */ + unsigned char x11_map[112] = { 0 }; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->common.context.settings); + + x11_map[0] = Button1; + x11_map[1] = Button2; + x11_map[2] = Button3; + x11_map[3] = Button4; + x11_map[4] = Button5; + x11_map[5] = 6; + x11_map[6] = 7; + x11_map[7] = 8; + x11_map[8] = 9; + x11_map[96] = 97; + x11_map[111] = 112; + + /* query system for actual remapping */ + if (freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_UnmapButtons)) + { + xf_get_x11_button_map(xfc, x11_map); + } + + /* iterate over all (mapped) physical buttons; for each of them */ + /* find the logical button in X11, and assign to this the */ + /* appropriate value to send over the RDP wire. */ + for (size_t physical = 0; physical < ARRAYSIZE(x11_map); ++physical) + { + const unsigned char logical = x11_map[physical]; + const UINT16 flags = get_flags_for_button(logical); + + if ((logical != 0) && (flags != 0)) + { + if (pos >= NUM_BUTTONS_MAPPED) + { + WLog_ERR(TAG, "Failed to map mouse button to RDP button, no space"); + } + else + { + button_map* map = &xfc->button_map[pos++]; + map->button = logical; + map->flags = get_flags_for_button(physical + Button1); + } + } + } +} + +/** + * Callback given to freerdp_connect() to process the pre-connect operations. + * It will fill the rdp_freerdp structure (instance) with the appropriate options to use for the + * connection. + * + * @param instance - pointer to the rdp_freerdp structure that contains the connection's parameters, + * and will be filled with the appropriate information. + * + * @return TRUE if successful. FALSE otherwise. + * Can exit with error code XF_EXIT_PARSE_ARGUMENTS if there is an error in the parameters. + */ +static BOOL xf_pre_connect(freerdp* instance) +{ + UINT32 maxWidth = 0; + UINT32 maxHeight = 0; + + WINPR_ASSERT(instance); + + rdpContext* context = instance->context; + WINPR_ASSERT(context); + xfContext* xfc = (xfContext*)context; + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + if (!freerdp_settings_set_bool(settings, FreeRDP_CertificateCallbackPreferPEM, TRUE)) + return FALSE; + + if (!freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly)) + { + if (!xf_setup_x11(xfc)) + return FALSE; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_UNIX)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_NATIVE_XSERVER)) + return FALSE; + PubSub_SubscribeChannelConnected(context->pubSub, xf_OnChannelConnectedEventHandler); + PubSub_SubscribeChannelDisconnected(context->pubSub, xf_OnChannelDisconnectedEventHandler); + + if (!freerdp_settings_get_string(settings, FreeRDP_Username) && + !freerdp_settings_get_bool(settings, FreeRDP_CredentialsFromStdin) && + !freerdp_settings_get_bool(settings, FreeRDP_SmartcardLogon)) + { + char login_name[MAX_PATH] = { 0 }; + ULONG size = sizeof(login_name) - 1; + + if (GetUserNameExA(NameSamCompatible, login_name, &size)) + { + if (!freerdp_settings_set_string(settings, FreeRDP_Username, login_name)) + return FALSE; + + WLog_INFO(TAG, "No user name set. - Using login name: %s", + freerdp_settings_get_string(settings, FreeRDP_Username)); + } + } + + if (freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly)) + { + /* Check +auth-only has a username and password. */ + if (!freerdp_settings_get_string(settings, FreeRDP_Password)) + { + WLog_INFO(TAG, "auth-only, but no password set. Please provide one."); + return FALSE; + } + + WLog_INFO(TAG, "Authentication only. Don't connect to X."); + } + + if (!freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly)) + { + const char* KeyboardRemappingList = freerdp_settings_get_string( + xfc->common.context.settings, FreeRDP_KeyboardRemappingList); + + xfc->remap_table = freerdp_keyboard_remap_string_to_list(KeyboardRemappingList); + if (!xfc->remap_table) + return FALSE; + if (!xf_keyboard_init(xfc)) + return FALSE; + if (!xf_keyboard_action_script_init(xfc)) + return FALSE; + if (!xf_detect_monitors(xfc, &maxWidth, &maxHeight)) + return FALSE; + } + + if (maxWidth && maxHeight && !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, maxWidth)) + return FALSE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, maxHeight)) + return FALSE; + } + +#ifdef WITH_XRENDER + + /** + * If /f is specified in combination with /smart-sizing:widthxheight then + * we run the session in the /smart-sizing dimensions scaled to full screen + */ + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen) && + freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) && + (freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth) > 0) && + (freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight) > 0)) + { + if (!freerdp_settings_set_uint32( + settings, FreeRDP_DesktopWidth, + freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth))) + return FALSE; + if (!freerdp_settings_set_uint32( + settings, FreeRDP_DesktopHeight, + freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight))) + return FALSE; + } + +#endif + xfc->fullscreen = freerdp_settings_get_bool(settings, FreeRDP_Fullscreen); + xfc->decorations = freerdp_settings_get_bool(settings, FreeRDP_Decorations); + xfc->grab_keyboard = freerdp_settings_get_bool(settings, FreeRDP_GrabKeyboard); + xfc->fullscreen_toggle = freerdp_settings_get_bool(settings, FreeRDP_ToggleFullscreen); + if (!freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly)) + xf_button_map_init(xfc); + return TRUE; +} + +static BOOL xf_inject_keypress(rdpContext* context, const char* buffer, size_t size) +{ + WCHAR wbuffer[64] = { 0 }; + const SSIZE_T len = ConvertUtf8NToWChar(buffer, size, wbuffer, ARRAYSIZE(wbuffer)); + if (len < 0) + return FALSE; + + rdpInput* input = context->input; + WINPR_ASSERT(input); + + for (SSIZE_T x = 0; x < len; x++) + { + const WCHAR code = wbuffer[x]; + freerdp_input_send_unicode_keyboard_event(input, 0, code); + Sleep(5); + freerdp_input_send_unicode_keyboard_event(input, KBD_FLAGS_RELEASE, code); + Sleep(5); + } + return TRUE; +} + +static BOOL xf_process_pipe(rdpContext* context, const char* pipe) +{ + int fd = open(pipe, O_NONBLOCK | O_RDONLY); + if (fd < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pipe '%s' open returned %s [%d]", pipe, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return FALSE; + } + while (!freerdp_shall_disconnect_context(context)) + { + char buffer[64] = { 0 }; + ssize_t rd = read(fd, buffer, sizeof(buffer) - 1); + if (rd == 0) + { + char ebuffer[256] = { 0 }; + if ((errno == EAGAIN) || (errno == 0)) + { + Sleep(100); + continue; + } + + // EOF, abort reading. + WLog_ERR(TAG, "pipe '%s' read returned %s [%d]", pipe, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + break; + } + else if (rd < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "pipe '%s' read returned %s [%d]", pipe, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + break; + } + else + { + if (!xf_inject_keypress(context, buffer, WINPR_ASSERTING_INT_CAST(size_t, rd))) + break; + } + } + close(fd); + return TRUE; +} + +static void cleanup_pipe(int signum, const char* signame, void* context) +{ + const char* pipe = context; + if (!pipe) + return; + unlink(pipe); +} + +static DWORD WINAPI xf_handle_pipe(void* arg) +{ + xfContext* xfc = arg; + WINPR_ASSERT(xfc); + + rdpContext* context = &xfc->common.context; + WINPR_ASSERT(context); + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + const char* pipe = freerdp_settings_get_string(settings, FreeRDP_KeyboardPipeName); + WINPR_ASSERT(pipe); + + const int rc = mkfifo(pipe, S_IWUSR | S_IRUSR); + if (rc != 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "Failed to create named pipe '%s': %s [%d]", pipe, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return 0; + } + + void* ctx = WINPR_CAST_CONST_PTR_AWAY(pipe, void*); + freerdp_add_signal_cleanup_handler(ctx, cleanup_pipe); + + xf_process_pipe(context, pipe); + + freerdp_del_signal_cleanup_handler(ctx, cleanup_pipe); + + unlink(pipe); + return 0; +} + +/** + * Callback given to freerdp_connect() to perform post-connection operations. + * It will be called only if the connection was initialized properly, and will continue the + * initialization based on the newly created connection. + */ +static BOOL xf_post_connect(freerdp* instance) +{ + ResizeWindowEventArgs e = { 0 }; + + WINPR_ASSERT(instance); + xfContext* xfc = (xfContext*)instance->context; + rdpContext* context = instance->context; + WINPR_ASSERT(context); + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + rdpUpdate* update = context->update; + WINPR_ASSERT(update); + + if (freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode)) + xfc->remote_app = TRUE; + + if (!xf_create_window(xfc)) + return FALSE; + + if (!xf_get_pixmap_info(xfc)) + return FALSE; + + if (!gdi_init(instance, xf_get_local_color_format(xfc, TRUE))) + return FALSE; + + if (!xf_create_image(xfc)) + return FALSE; + + if (!xf_register_pointer(context->graphics)) + return FALSE; + +#ifdef WITH_XRENDER + xfc->scaledWidth = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + xfc->scaledHeight = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + xfc->offset_x = 0; + xfc->offset_y = 0; +#endif + + if (!xfc->xrenderAvailable) + { + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + { + WLog_ERR(TAG, "XRender not available: disabling smart-sizing"); + if (!freerdp_settings_set_bool(settings, FreeRDP_SmartSizing, FALSE)) + return FALSE; + } + + if (freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures)) + { + WLog_ERR(TAG, "XRender not available: disabling local multi-touch gestures"); + if (!freerdp_settings_set_bool(settings, FreeRDP_MultiTouchGestures, FALSE)) + return FALSE; + } + } + + update->DesktopResize = xf_sw_desktop_resize; + update->EndPaint = xf_end_paint; + update->PlaySound = xf_play_sound; + update->SetKeyboardIndicators = xf_keyboard_set_indicators; + update->SetKeyboardImeStatus = xf_keyboard_set_ime_status; + + const BOOL serverIsWindowsPlatform = + (freerdp_settings_get_uint32(settings, FreeRDP_OsMajorType) == OSMAJORTYPE_WINDOWS); + if (freerdp_settings_get_bool(settings, FreeRDP_RedirectClipboard) && + !(xfc->clipboard = xf_clipboard_new(xfc, !serverIsWindowsPlatform))) + return FALSE; + + if (!(xfc->xfDisp = xf_disp_new(xfc))) + return FALSE; + + const char* pipe = freerdp_settings_get_string(settings, FreeRDP_KeyboardPipeName); + if (pipe) + { + xfc->pipethread = CreateThread(NULL, 0, xf_handle_pipe, xfc, 0, NULL); + if (!xfc->pipethread) + return FALSE; + } + + EventArgsInit(&e, "xfreerdp"); + e.width = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + e.height = + WINPR_ASSERTING_INT_CAST(int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + PubSub_OnResizeWindow(context->pubSub, xfc, &e); + return TRUE; +} + +static void xf_post_disconnect(freerdp* instance) +{ + xfContext* xfc = NULL; + rdpContext* context = NULL; + + if (!instance || !instance->context) + return; + + context = instance->context; + xfc = (xfContext*)context; + PubSub_UnsubscribeChannelConnected(instance->context->pubSub, + xf_OnChannelConnectedEventHandler); + PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub, + xf_OnChannelDisconnectedEventHandler); + gdi_free(instance); + + if (xfc->pipethread) + { + (void)WaitForSingleObject(xfc->pipethread, INFINITE); + (void)CloseHandle(xfc->pipethread); + xfc->pipethread = NULL; + } + if (xfc->clipboard) + { + xf_clipboard_free(xfc->clipboard); + xfc->clipboard = NULL; + } + + if (xfc->xfDisp) + { + xf_disp_free(xfc->xfDisp); + xfc->xfDisp = NULL; + } + + if ((xfc->window != NULL) && (xfc->drawable == xfc->window->handle)) + xfc->drawable = 0; + else + xf_DestroyDummyWindow(xfc, xfc->drawable); + + freerdp_keyboard_remap_free(xfc->remap_table); + xfc->remap_table = NULL; + + xf_window_free(xfc); +} + +static void xf_post_final_disconnect(freerdp* instance) +{ + xfContext* xfc = NULL; + rdpContext* context = NULL; + + if (!instance || !instance->context) + return; + + context = instance->context; + xfc = (xfContext*)context; + + xf_keyboard_free(xfc); + xf_teardown_x11(xfc); +} + +static int xf_logon_error_info(freerdp* instance, UINT32 data, UINT32 type) +{ + xfContext* xfc = (xfContext*)instance->context; + const char* str_data = freerdp_get_logon_error_info_data(data); + const char* str_type = freerdp_get_logon_error_info_type(type); + WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type); + if (type != LOGON_MSG_SESSION_CONTINUE) + { + xf_rail_disable_remoteapp_mode(xfc); + } + return 1; +} + +static BOOL handle_window_events(freerdp* instance) +{ + if (!xf_process_x_events(instance)) + { + WLog_DBG(TAG, "Closed from X11"); + return FALSE; + } + + return TRUE; +} + +/** Main loop for the rdp connection. + * It will be run from the thread's entry point (thread_func()). + * It initiates the connection, and will continue to run until the session ends, + * processing events as they are received. + * + * @param param - pointer to the rdp_freerdp structure that contains the session's settings + * @return A code from the enum XF_EXIT_CODE (0 if successful) + */ +static DWORD WINAPI xf_client_thread(LPVOID param) +{ + DWORD exit_code = 0; + DWORD waitStatus = 0; + HANDLE inputEvent = NULL; + HANDLE timer = NULL; + LARGE_INTEGER due = { 0 }; + TimerEventArgs timerEvent = { 0 }; + + EventArgsInit(&timerEvent, "xfreerdp"); + freerdp* instance = (freerdp*)param; + WINPR_ASSERT(instance); + + const BOOL status = freerdp_connect(instance); + rdpContext* context = instance->context; + WINPR_ASSERT(context); + xfContext* xfc = (xfContext*)instance->context; + WINPR_ASSERT(xfc); + + rdpSettings* settings = context->settings; + WINPR_ASSERT(settings); + + if (!status) + { + UINT32 error = freerdp_get_last_error(instance->context); + exit_code = (uint32_t)xf_map_error_to_exit_code(error); + } + else + exit_code = XF_EXIT_SUCCESS; + + if (!status) + goto end; + + /* --authonly ? */ + if (freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly)) + { + WLog_ERR(TAG, "Authentication only, exit status %" PRId32 "", !status); + goto disconnect; + } + + if (!status) + { + WLog_ERR(TAG, "Freerdp connect error exit status %" PRId32 "", !status); + exit_code = freerdp_error_info(instance); + + if (freerdp_get_last_error(instance->context) == FREERDP_ERROR_AUTHENTICATION_FAILED) + exit_code = XF_EXIT_AUTH_FAILURE; + else if (exit_code == ERRINFO_SUCCESS) + exit_code = XF_EXIT_CONN_FAILED; + + goto disconnect; + } + + timer = CreateWaitableTimerA(NULL, FALSE, "mainloop-periodic-timer"); + + if (!timer) + { + WLog_ERR(TAG, "failed to create timer"); + goto disconnect; + } + + due.QuadPart = 0; + + if (!SetWaitableTimer(timer, &due, 20, NULL, NULL, FALSE)) + { + goto disconnect; + } + inputEvent = xfc->x11event; + + while (!freerdp_shall_disconnect_context(instance->context)) + { + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD nCount = 0; + handles[nCount++] = timer; + handles[nCount++] = inputEvent; + + /* + * win8 and server 2k12 seem to have some timing issue/race condition + * when a initial sync request is send to sync the keyboard indicators + * sending the sync event twice fixed this problem + */ + if (freerdp_focus_required(instance)) + { + xf_keyboard_focus_in(xfc); + xf_keyboard_focus_in(xfc); + } + + { + DWORD tmp = + freerdp_get_event_handles(context, &handles[nCount], ARRAYSIZE(handles) - nCount); + + if (tmp == 0) + { + WLog_ERR(TAG, "freerdp_get_event_handles failed"); + break; + } + + nCount += tmp; + } + + if (xfc->window) + xf_floatbar_hide_and_show(xfc->window->floatbar); + + waitStatus = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE); + + if (waitStatus == WAIT_FAILED) + break; + + { + if (!freerdp_check_event_handles(context)) + { + if (client_auto_reconnect_ex(instance, handle_window_events)) + continue; + else + { + /* + * Indicate an unsuccessful connection attempt if reconnect + * did not succeed and no other error was specified. + */ + const UINT32 error = freerdp_get_last_error(instance->context); + + if (freerdp_error_info(instance) == 0) + exit_code = (uint32_t)xf_map_error_to_exit_code(error); + } + + if (freerdp_get_last_error(context) == FREERDP_ERROR_SUCCESS) + WLog_ERR(TAG, "Failed to check FreeRDP file descriptor"); + + break; + } + } + + if (!handle_window_events(instance)) + break; + + if ((waitStatus != WAIT_TIMEOUT) && (waitStatus == WAIT_OBJECT_0)) + { + timerEvent.now = GetTickCount64(); + PubSub_OnTimer(context->pubSub, context, &timerEvent); + } + } + + if (!exit_code) + { + exit_code = freerdp_error_info(instance); + + if (exit_code == XF_EXIT_DISCONNECT && + freerdp_get_disconnect_ultimatum(context) == Disconnect_Ultimatum_user_requested) + { + /* This situation might be limited to Windows XP. */ + WLog_INFO(TAG, "Error info says user did not initiate but disconnect ultimatum says " + "they did; treat this as a user logoff"); + exit_code = XF_EXIT_LOGOFF; + } + } + +disconnect: + + if (timer) + (void)CloseHandle(timer); + + freerdp_disconnect(instance); +end: + ExitThread(exit_code); + return exit_code; +} + +int xf_exit_code_from_disconnect_reason(DWORD reason) +{ + if (reason == 0 || + (reason >= XF_EXIT_PARSE_ARGUMENTS && reason <= XF_EXIT_CONNECT_NO_OR_MISSING_CREDENTIALS)) + return WINPR_ASSERTING_INT_CAST(int, reason); + /* License error set */ + else if (reason >= 0x100 && reason <= 0x10A) + reason -= 0x100 + XF_EXIT_LICENSE_INTERNAL; + /* RDP protocol error set */ + else if (reason >= 0x10c9 && reason <= 0x1193) + reason = XF_EXIT_RDP; + /* There's no need to test protocol-independent codes: they match */ + else if (!(reason <= 0xC)) + reason = XF_EXIT_UNKNOWN; + + return WINPR_ASSERTING_INT_CAST(int, reason); +} + +static void xf_TerminateEventHandler(void* context, const TerminateEventArgs* e) +{ + rdpContext* ctx = (rdpContext*)context; + WINPR_UNUSED(e); + freerdp_abort_connect_context(ctx); +} + +#ifdef WITH_XRENDER +static void xf_ZoomingChangeEventHandler(void* context, const ZoomingChangeEventArgs* e) +{ + int w = 0; + int h = 0; + rdpSettings* settings = NULL; + xfContext* xfc = (xfContext*)context; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + w = xfc->scaledWidth + e->dx; + h = xfc->scaledHeight + e->dy; + + if (e->dx == 0 && e->dy == 0) + return; + + if (w < 10) + w = 10; + + if (h < 10) + h = 10; + + if (w == xfc->scaledWidth && h == xfc->scaledHeight) + return; + + xfc->scaledWidth = w; + xfc->scaledHeight = h; + xf_draw_screen(xfc, 0, 0, + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)), + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))); +} + +static void xf_PanningChangeEventHandler(void* context, const PanningChangeEventArgs* e) +{ + xfContext* xfc = (xfContext*)context; + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(e); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (e->dx == 0 && e->dy == 0) + return; + + xfc->offset_x += e->dx; + xfc->offset_y += e->dy; + xf_draw_screen(xfc, 0, 0, + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)), + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))); +} +#endif + +/** + * Client Interface + */ + +static BOOL xfreerdp_client_global_init(void) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + (void)setlocale(LC_ALL, ""); + + if (freerdp_handle_signals() != 0) + return FALSE; + + return TRUE; +} + +static void xfreerdp_client_global_uninit(void) +{ +} + +static int xfreerdp_client_start(rdpContext* context) +{ + xfContext* xfc = (xfContext*)context; + rdpSettings* settings = context->settings; + + if (!freerdp_settings_get_string(settings, FreeRDP_ServerHostname)) + { + WLog_ERR(TAG, "error: server hostname was not specified with /v:[:port]"); + return -1; + } + + if (!(xfc->common.thread = CreateThread(NULL, 0, xf_client_thread, context->instance, 0, NULL))) + { + WLog_ERR(TAG, "failed to create client thread"); + return -1; + } + + return 0; +} + +static Atom get_supported_atom(xfContext* xfc, const char* atomName) +{ + const Atom atom = Logging_XInternAtom(xfc->log, xfc->display, atomName, False); + + for (unsigned long i = 0; i < xfc->supportedAtomCount; i++) + { + if (xfc->supportedAtoms[i] == atom) + return atom; + } + + return None; +} + +void xf_teardown_x11(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + if (xfc->display) + { + XCloseDisplay(xfc->display); + xfc->display = NULL; + } + + if (xfc->x11event) + { + (void)CloseHandle(xfc->x11event); + xfc->x11event = NULL; + } + + if (xfc->mutex) + { + (void)CloseHandle(xfc->mutex); + xfc->mutex = NULL; + } + + if (xfc->vscreen.monitors) + { + free(xfc->vscreen.monitors); + xfc->vscreen.monitors = NULL; + } + xfc->vscreen.nmonitors = 0; + + free(xfc->supportedAtoms); + xfc->supportedAtoms = NULL; + xfc->supportedAtomCount = 0; +} + +BOOL xf_setup_x11(xfContext* xfc) +{ + + WINPR_ASSERT(xfc); + xfc->UseXThreads = TRUE; + +#if !defined(NDEBUG) + /* uncomment below if debugging to prevent keyboard grab */ + xfc->debug = TRUE; +#endif + + if (xfc->UseXThreads) + { + if (!XInitThreads()) + { + WLog_WARN(TAG, "XInitThreads() failure"); + xfc->UseXThreads = FALSE; + } + } + + xfc->display = XOpenDisplay(NULL); + + if (!xfc->display) + { + WLog_ERR(TAG, "failed to open display: %s", XDisplayName(NULL)); + WLog_ERR(TAG, "Please check that the $DISPLAY environment variable is properly set."); + goto fail; + } + if (xfc->debug) + { + WLog_INFO(TAG, "Enabling X11 debug mode."); + XSynchronize(xfc->display, TRUE); + } + def_error_handler = XSetErrorHandler(xf_error_handler_ex); + + xfc->mutex = CreateMutex(NULL, FALSE, NULL); + + if (!xfc->mutex) + { + WLog_ERR(TAG, "Could not create mutex!"); + goto fail; + } + + xfc->xfds = ConnectionNumber(xfc->display); + xfc->screen_number = DefaultScreen(xfc->display); + xfc->screen = ScreenOfDisplay(xfc->display, xfc->screen_number); + xfc->big_endian = (ImageByteOrder(xfc->display) == MSBFirst); + xfc->invert = TRUE; + xfc->complex_regions = TRUE; + xfc->_NET_SUPPORTED = Logging_XInternAtom(xfc->log, xfc->display, "_NET_SUPPORTED", True); + xfc->_NET_SUPPORTING_WM_CHECK = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_SUPPORTING_WM_CHECK", True); + + if ((xfc->_NET_SUPPORTED != None) && (xfc->_NET_SUPPORTING_WM_CHECK != None)) + { + Atom actual_type = 0; + int actual_format = 0; + unsigned long nitems = 0; + unsigned long after = 0; + unsigned char* data = NULL; + int status = LogTagAndXGetWindowProperty( + TAG, xfc->display, RootWindowOfScreen(xfc->screen), xfc->_NET_SUPPORTED, 0, 1024, False, + XA_ATOM, &actual_type, &actual_format, &nitems, &after, &data); + + if ((status == Success) && (actual_type == XA_ATOM) && (actual_format == 32)) + { + xfc->supportedAtomCount = nitems; + xfc->supportedAtoms = calloc(xfc->supportedAtomCount, sizeof(Atom)); + WINPR_ASSERT(xfc->supportedAtoms); + memcpy(xfc->supportedAtoms, data, nitems * sizeof(Atom)); + } + + if (data) + XFree(data); + } + + xfc->_XWAYLAND_MAY_GRAB_KEYBOARD = + Logging_XInternAtom(xfc->log, xfc->display, "_XWAYLAND_MAY_GRAB_KEYBOARD", False); + xfc->_NET_WM_ICON = Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ICON", False); + xfc->_MOTIF_WM_HINTS = Logging_XInternAtom(xfc->log, xfc->display, "_MOTIF_WM_HINTS", False); + xfc->_NET_NUMBER_OF_DESKTOPS = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_NUMBER_OF_DESKTOPS", False); + xfc->_NET_CURRENT_DESKTOP = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_CURRENT_DESKTOP", False); + xfc->_NET_WORKAREA = Logging_XInternAtom(xfc->log, xfc->display, "_NET_WORKAREA", False); + xfc->_NET_WM_STATE = get_supported_atom(xfc, "_NET_WM_STATE"); + xfc->_NET_WM_STATE_MODAL = get_supported_atom(xfc, "_NET_WM_STATE_MODAL"); + xfc->_NET_WM_STATE_STICKY = get_supported_atom(xfc, "_NET_WM_STATE_STICKY"); + xfc->_NET_WM_STATE_MAXIMIZED_HORZ = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_MAXIMIZED_HORZ", False); + xfc->_NET_WM_STATE_MAXIMIZED_VERT = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_MAXIMIZED_VERT", False); + xfc->_NET_WM_STATE_SHADED = get_supported_atom(xfc, "_NET_WM_STATE_SHADED"); + xfc->_NET_WM_STATE_SKIP_TASKBAR = get_supported_atom(xfc, "_NET_WM_STATE_SKIP_TASKBAR"); + xfc->_NET_WM_STATE_SKIP_PAGER = get_supported_atom(xfc, "_NET_WM_STATE_SKIP_PAGER"); + xfc->_NET_WM_STATE_HIDDEN = get_supported_atom(xfc, "_NET_WM_STATE_HIDDEN"); + xfc->_NET_WM_STATE_FULLSCREEN = get_supported_atom(xfc, "_NET_WM_STATE_FULLSCREEN"); + xfc->_NET_WM_STATE_ABOVE = get_supported_atom(xfc, "_NET_WM_STATE_ABOVE"); + xfc->_NET_WM_STATE_BELOW = get_supported_atom(xfc, "_NET_WM_STATE_BELOW"); + xfc->_NET_WM_STATE_DEMANDS_ATTENTION = + get_supported_atom(xfc, "_NET_WM_STATE_DEMANDS_ATTENTION"); + xfc->_NET_WM_FULLSCREEN_MONITORS = get_supported_atom(xfc, "_NET_WM_FULLSCREEN_MONITORS"); + xfc->_NET_WM_NAME = Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_NAME", False); + xfc->_NET_WM_PID = Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_PID", False); + xfc->_NET_WM_WINDOW_TYPE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE", False); + xfc->_NET_WM_WINDOW_TYPE_NORMAL = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_NORMAL", False); + xfc->_NET_WM_WINDOW_TYPE_DIALOG = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_DIALOG", False); + xfc->_NET_WM_WINDOW_TYPE_POPUP = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_POPUP", False); + xfc->_NET_WM_WINDOW_TYPE_POPUP_MENU = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_POPUP_MENU", False); + xfc->_NET_WM_WINDOW_TYPE_UTILITY = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_UTILITY", False); + xfc->_NET_WM_WINDOW_TYPE_DROPDOWN_MENU = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", False); + xfc->_NET_WM_STATE_SKIP_TASKBAR = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_SKIP_TASKBAR", False); + xfc->_NET_WM_STATE_SKIP_PAGER = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_SKIP_PAGER", False); + xfc->_NET_WM_MOVERESIZE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_MOVERESIZE", False); + xfc->_NET_MOVERESIZE_WINDOW = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_MOVERESIZE_WINDOW", False); + xfc->UTF8_STRING = Logging_XInternAtom(xfc->log, xfc->display, "UTF8_STRING", FALSE); + xfc->WM_PROTOCOLS = Logging_XInternAtom(xfc->log, xfc->display, "WM_PROTOCOLS", False); + xfc->WM_DELETE_WINDOW = Logging_XInternAtom(xfc->log, xfc->display, "WM_DELETE_WINDOW", False); + xfc->WM_STATE = Logging_XInternAtom(xfc->log, xfc->display, "WM_STATE", False); + xfc->x11event = CreateFileDescriptorEvent(NULL, FALSE, FALSE, xfc->xfds, WINPR_FD_READ); + + xfc->NET_WM_ALLOWED_ACTIONS = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ALLOWED_ACTIONS", False); + + xfc->NET_WM_ACTION_CLOSE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_CLOSE", False); + xfc->NET_WM_ACTION_MINIMIZE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_MINIMIZE", False); + xfc->NET_WM_ACTION_MOVE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_MOVE", False); + xfc->NET_WM_ACTION_RESIZE = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_RESIZE", False); + xfc->NET_WM_ACTION_MAXIMIZE_HORZ = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_MAXIMIZE_HORZ", False); + xfc->NET_WM_ACTION_MAXIMIZE_VERT = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_MAXIMIZE_VERT", False); + xfc->NET_WM_ACTION_FULLSCREEN = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_FULLSCREEN", False); + xfc->NET_WM_ACTION_CHANGE_DESKTOP = + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_ACTION_CHANGE_DESKTOP", False); + + if (!xfc->x11event) + { + WLog_ERR(TAG, "Could not create xfds event"); + goto fail; + } + + xf_check_extensions(xfc); + + xfc->vscreen.monitors = calloc(16, sizeof(MONITOR_INFO)); + + if (!xfc->vscreen.monitors) + goto fail; + return TRUE; + +fail: + xf_teardown_x11(xfc); + return FALSE; +} + +static BOOL xfreerdp_client_new(freerdp* instance, rdpContext* context) +{ + xfContext* xfc = (xfContext*)instance->context; + WINPR_ASSERT(context); + WINPR_ASSERT(xfc); + WINPR_ASSERT(!xfc->display); + WINPR_ASSERT(!xfc->mutex); + WINPR_ASSERT(!xfc->x11event); + instance->PreConnect = xf_pre_connect; + instance->PostConnect = xf_post_connect; + instance->PostDisconnect = xf_post_disconnect; + instance->PostFinalDisconnect = xf_post_final_disconnect; + instance->LogonErrorInfo = xf_logon_error_info; + instance->GetAccessToken = client_cli_get_access_token; + PubSub_SubscribeTerminate(context->pubSub, xf_TerminateEventHandler); +#ifdef WITH_XRENDER + PubSub_SubscribeZoomingChange(context->pubSub, xf_ZoomingChangeEventHandler); + PubSub_SubscribePanningChange(context->pubSub, xf_PanningChangeEventHandler); +#endif + xfc->log = WLog_Get(TAG); + + return TRUE; +} + +static void xfreerdp_client_free(freerdp* instance, rdpContext* context) +{ + if (!context) + return; + + if (context->pubSub) + { + PubSub_UnsubscribeTerminate(context->pubSub, xf_TerminateEventHandler); +#ifdef WITH_XRENDER + PubSub_UnsubscribeZoomingChange(context->pubSub, xf_ZoomingChangeEventHandler); + PubSub_UnsubscribePanningChange(context->pubSub, xf_PanningChangeEventHandler); +#endif + } +} + +int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + pEntryPoints->Version = 1; + pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1); + pEntryPoints->GlobalInit = xfreerdp_client_global_init; + pEntryPoints->GlobalUninit = xfreerdp_client_global_uninit; + pEntryPoints->ContextSize = sizeof(xfContext); + pEntryPoints->ClientNew = xfreerdp_client_new; + pEntryPoints->ClientFree = xfreerdp_client_free; + pEntryPoints->ClientStart = xfreerdp_client_start; + pEntryPoints->ClientStop = freerdp_client_common_stop; + return 0; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.h new file mode 100644 index 0000000000000000000000000000000000000000..c9bc21b125354ec8d4322b55f64f25cffbbaca75 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_client.h @@ -0,0 +1,53 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client Interface + * + * Copyright 2013 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_CLIENT_H +#define FREERDP_CLIENT_X11_CLIENT_H + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + /** + * Client Interface + */ + + FREERDP_API int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERDP_CLIENT_X11_CLIENT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.c new file mode 100644 index 0000000000000000000000000000000000000000..949a728e823d3fe498e17878c7fbf1c2b7cbc11d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.c @@ -0,0 +1,2658 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Clipboard Redirection + * + * Copyright 2010-2011 Vic Lee + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include + +#ifdef WITH_XFIXES +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "xf_cliprdr.h" +#include "xf_event.h" +#include "xf_utils.h" + +#define TAG CLIENT_TAG("x11.cliprdr") + +#define MAX_CLIPBOARD_FORMATS 255 + +#ifdef WITH_DEBUG_CLIPRDR +#define DEBUG_CLIPRDR(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_CLIPRDR(...) \ + do \ + { \ + } while (0) +#endif + +typedef struct +{ + Atom atom; + UINT32 formatToRequest; + UINT32 localFormat; + char* formatName; +} xfCliprdrFormat; + +typedef struct +{ + BYTE* data; + UINT32 data_length; +} xfCachedData; + +typedef struct +{ + UINT32 localFormat; + UINT32 formatToRequest; + char* formatName; +} RequestedFormat; + +struct xf_clipboard +{ + xfContext* xfc; + rdpChannels* channels; + CliprdrClientContext* context; + + wClipboard* system; + + Window root_window; + Atom clipboard_atom; + Atom property_atom; + + Atom timestamp_property_atom; + Time selection_ownership_timestamp; + + Atom raw_transfer_atom; + Atom raw_format_list_atom; + + UINT32 numClientFormats; + xfCliprdrFormat clientFormats[20]; + + UINT32 numServerFormats; + CLIPRDR_FORMAT* serverFormats; + + size_t numTargets; + Atom targets[20]; + + int requestedFormatId; + + wHashTable* cachedData; + wHashTable* cachedRawData; + + BOOL data_raw_format; + + RequestedFormat* requestedFormat; + + XSelectionEvent* respond; + + Window owner; + BOOL sync; + + /* INCR mechanism */ + Atom incr_atom; + BOOL incr_starts; + BYTE* incr_data; + size_t incr_data_length; + long event_mask; + + /* XFixes extension */ + int xfixes_event_base; + int xfixes_error_base; + BOOL xfixes_supported; + + /* last sent data */ + CLIPRDR_FORMAT* lastSentFormats; + UINT32 lastSentNumFormats; + CliprdrFileContext* file; +}; + +static const char mime_text_plain[] = "text/plain"; +static const char mime_uri_list[] = "text/uri-list"; +static const char mime_html[] = "text/html"; +static const char* mime_bitmap[] = { "image/bmp", "image/x-bmp", "image/x-MS-bmp", + "image/x-win-bitmap" }; +static const char mime_webp[] = "image/webp"; +static const char mime_png[] = "image/png"; +static const char mime_jpeg[] = "image/jpeg"; +static const char mime_tiff[] = "image/tiff"; +static const char* mime_images[] = { mime_webp, mime_png, mime_jpeg, mime_tiff }; + +static const char mime_gnome_copied_files[] = "x-special/gnome-copied-files"; +static const char mime_mate_copied_files[] = "x-special/mate-copied-files"; + +static const char type_FileGroupDescriptorW[] = "FileGroupDescriptorW"; +static const char type_HtmlFormat[] = "HTML Format"; + +static void xf_cliprdr_clear_cached_data(xfClipboard* clipboard); +static UINT xf_cliprdr_send_client_format_list(xfClipboard* clipboard, BOOL force); +static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp); + +static void requested_format_free(RequestedFormat** ppRequestedFormat) +{ + if (!ppRequestedFormat) + return; + if (!(*ppRequestedFormat)) + return; + + free((*ppRequestedFormat)->formatName); + free(*ppRequestedFormat); + *ppRequestedFormat = NULL; +} + +static BOOL requested_format_replace(RequestedFormat** ppRequestedFormat, UINT32 formatId, + const char* formatName) +{ + if (!ppRequestedFormat) + return FALSE; + + requested_format_free(ppRequestedFormat); + RequestedFormat* requested = calloc(1, sizeof(RequestedFormat)); + if (!requested) + return FALSE; + requested->localFormat = formatId; + requested->formatToRequest = formatId; + if (formatName) + { + requested->formatName = _strdup(formatName); + if (!requested->formatName) + { + free(requested); + return FALSE; + } + } + + *ppRequestedFormat = requested; + return TRUE; +} + +static void xf_cached_data_free(void* ptr) +{ + xfCachedData* cached_data = ptr; + if (!cached_data) + return; + + free(cached_data->data); + free(cached_data); +} + +static xfCachedData* xf_cached_data_new(BYTE* data, size_t data_length) +{ + if (data_length > UINT32_MAX) + return NULL; + + xfCachedData* cached_data = calloc(1, sizeof(xfCachedData)); + if (!cached_data) + return NULL; + + cached_data->data = data; + cached_data->data_length = (UINT32)data_length; + + return cached_data; +} + +static xfCachedData* xf_cached_data_new_copy(const BYTE* data, size_t data_length) +{ + BYTE* copy = NULL; + if (data_length > 0) + { + copy = calloc(data_length + 1, sizeof(BYTE)); + if (!copy) + return NULL; + memcpy(copy, data, data_length); + } + + xfCachedData* cache = xf_cached_data_new(copy, data_length); + if (!cache) + free(copy); + return cache; +} + +static void xf_clipboard_free_server_formats(xfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + if (clipboard->serverFormats) + { + for (size_t i = 0; i < clipboard->numServerFormats; i++) + { + CLIPRDR_FORMAT* format = &clipboard->serverFormats[i]; + free(format->formatName); + } + + free(clipboard->serverFormats); + clipboard->serverFormats = NULL; + } +} + +static BOOL xf_cliprdr_update_owner(xfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + xfContext* xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (!clipboard->sync) + return FALSE; + + Window owner = XGetSelectionOwner(xfc->display, clipboard->clipboard_atom); + if (clipboard->owner == owner) + return FALSE; + + clipboard->owner = owner; + return TRUE; +} + +static void xf_cliprdr_check_owner(xfClipboard* clipboard) +{ + if (xf_cliprdr_update_owner(clipboard)) + xf_cliprdr_send_client_format_list(clipboard, FALSE); +} + +static BOOL xf_cliprdr_is_self_owned(xfClipboard* clipboard) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + return XGetSelectionOwner(xfc->display, clipboard->clipboard_atom) == xfc->drawable; +} + +static void xf_cliprdr_set_raw_transfer_enabled(xfClipboard* clipboard, BOOL enabled) +{ + UINT32 data = WINPR_ASSERTING_INT_CAST(uint32_t, enabled); + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + LogTagAndXChangeProperty(TAG, xfc->display, xfc->drawable, clipboard->raw_transfer_atom, + XA_INTEGER, 32, PropModeReplace, (BYTE*)&data, 1); +} + +static BOOL xf_cliprdr_is_raw_transfer_available(xfClipboard* clipboard) +{ + Atom type = 0; + int format = 0; + int result = 0; + unsigned long length = 0; + unsigned long bytes_left = 0; + UINT32* data = NULL; + UINT32 is_enabled = 0; + Window owner = None; + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + owner = XGetSelectionOwner(xfc->display, clipboard->clipboard_atom); + + if (owner != None) + { + result = LogTagAndXGetWindowProperty(TAG, xfc->display, owner, clipboard->raw_transfer_atom, + 0, 4, 0, XA_INTEGER, &type, &format, &length, + &bytes_left, (BYTE**)&data); + } + + if (data) + { + is_enabled = *data; + XFree(data); + } + + if ((owner == None) || (owner == xfc->drawable)) + return FALSE; + + if (result != Success) + return FALSE; + + return is_enabled ? TRUE : FALSE; +} + +static BOOL xf_cliprdr_formats_equal(const CLIPRDR_FORMAT* server, const xfCliprdrFormat* client) +{ + WINPR_ASSERT(server); + WINPR_ASSERT(client); + + if (server->formatName && client->formatName) + { + /* The server may be using short format names while we store them in full form. */ + return (0 == strncmp(server->formatName, client->formatName, strlen(server->formatName))); + } + + if (!server->formatName && !client->formatName) + { + return (server->formatId == client->formatToRequest); + } + + return FALSE; +} + +static const xfCliprdrFormat* xf_cliprdr_get_client_format_by_id(xfClipboard* clipboard, + UINT32 formatId) +{ + WINPR_ASSERT(clipboard); + + for (size_t index = 0; index < clipboard->numClientFormats; index++) + { + const xfCliprdrFormat* format = &(clipboard->clientFormats[index]); + + if (format->formatToRequest == formatId) + return format; + } + + return NULL; +} + +static const xfCliprdrFormat* xf_cliprdr_get_client_format_by_atom(xfClipboard* clipboard, + Atom atom) +{ + WINPR_ASSERT(clipboard); + + for (UINT32 i = 0; i < clipboard->numClientFormats; i++) + { + const xfCliprdrFormat* format = &(clipboard->clientFormats[i]); + + if (format->atom == atom) + return format; + } + + return NULL; +} + +static const CLIPRDR_FORMAT* xf_cliprdr_get_server_format_by_atom(xfClipboard* clipboard, Atom atom) +{ + WINPR_ASSERT(clipboard); + + for (size_t i = 0; i < clipboard->numClientFormats; i++) + { + const xfCliprdrFormat* client_format = &(clipboard->clientFormats[i]); + + if (client_format->atom == atom) + { + for (size_t j = 0; j < clipboard->numServerFormats; j++) + { + const CLIPRDR_FORMAT* server_format = &(clipboard->serverFormats[j]); + + if (xf_cliprdr_formats_equal(server_format, client_format)) + return server_format; + } + } + } + + return NULL; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_send_data_request(xfClipboard* clipboard, UINT32 formatId, + const xfCliprdrFormat* cformat) +{ + CLIPRDR_FORMAT_DATA_REQUEST request = { 0 }; + request.requestedFormatId = formatId; + + DEBUG_CLIPRDR("requesting format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 "} [%s]", formatId, + ClipboardGetFormatIdString(formatId), cformat->localFormat, cformat->formatName); + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatDataRequest); + return clipboard->context->ClientFormatDataRequest(clipboard->context, &request); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_send_data_response(xfClipboard* clipboard, const xfCliprdrFormat* format, + const BYTE* data, size_t size) +{ + CLIPRDR_FORMAT_DATA_RESPONSE response = { 0 }; + + WINPR_ASSERT(clipboard); + + /* No request currently pending, do not send a response. */ + if (clipboard->requestedFormatId < 0) + return CHANNEL_RC_OK; + + if (size == 0) + { + if (format) + DEBUG_CLIPRDR("send CB_RESPONSE_FAIL response {format 0x%08" PRIx32 + " [%s] {local 0x%08" PRIx32 "} [%s]", + format->formatToRequest, + ClipboardGetFormatIdString(format->formatToRequest), format->localFormat, + format->formatName); + else + DEBUG_CLIPRDR("send CB_RESPONSE_FAIL response"); + } + else + { + WINPR_ASSERT(format); + DEBUG_CLIPRDR("send response format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 "} [%s]", + format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest), + format->localFormat, format->formatName); + } + /* Request handled, reset to invalid */ + clipboard->requestedFormatId = -1; + + response.common.msgFlags = (data) ? CB_RESPONSE_OK : CB_RESPONSE_FAIL; + + WINPR_ASSERT(size <= UINT32_MAX); + response.common.dataLen = (UINT32)size; + response.requestedFormatData = data; + + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatDataResponse); + return clipboard->context->ClientFormatDataResponse(clipboard->context, &response); +} + +static wStream* xf_cliprdr_serialize_server_format_list(xfClipboard* clipboard) +{ + UINT32 formatCount = 0; + wStream* s = NULL; + + WINPR_ASSERT(clipboard); + + /* Typical MS Word format list is about 80 bytes long. */ + if (!(s = Stream_New(NULL, 128))) + { + WLog_ERR(TAG, "failed to allocate serialized format list"); + goto error; + } + + /* If present, the last format is always synthetic CF_RAW. Do not include it. */ + formatCount = (clipboard->numServerFormats > 0) ? clipboard->numServerFormats - 1 : 0; + Stream_Write_UINT32(s, formatCount); + + for (UINT32 i = 0; i < formatCount; i++) + { + CLIPRDR_FORMAT* format = &clipboard->serverFormats[i]; + size_t name_length = format->formatName ? strlen(format->formatName) : 0; + + DEBUG_CLIPRDR("server announced 0x%08" PRIx32 " [%s][%s]", format->formatId, + ClipboardGetFormatIdString(format->formatId), format->formatName); + if (!Stream_EnsureRemainingCapacity(s, sizeof(UINT32) + name_length + 1)) + { + WLog_ERR(TAG, "failed to expand serialized format list"); + goto error; + } + + Stream_Write_UINT32(s, format->formatId); + + if (format->formatName) + Stream_Write(s, format->formatName, name_length); + + Stream_Write_UINT8(s, '\0'); + } + + Stream_SealLength(s); + return s; +error: + Stream_Free(s, TRUE); + return NULL; +} + +static CLIPRDR_FORMAT* xf_cliprdr_parse_server_format_list(BYTE* data, size_t length, + UINT32* numFormats) +{ + wStream* s = NULL; + CLIPRDR_FORMAT* formats = NULL; + + WINPR_ASSERT(data || (length == 0)); + WINPR_ASSERT(numFormats); + + if (!(s = Stream_New(data, length))) + { + WLog_ERR(TAG, "failed to allocate stream for parsing serialized format list"); + goto error; + } + + if (!Stream_CheckAndLogRequiredLength(TAG, s, sizeof(UINT32))) + goto error; + + Stream_Read_UINT32(s, *numFormats); + + if (*numFormats > MAX_CLIPBOARD_FORMATS) + { + WLog_ERR(TAG, "unexpectedly large number of formats: %" PRIu32 "", *numFormats); + goto error; + } + + if (!(formats = (CLIPRDR_FORMAT*)calloc(*numFormats, sizeof(CLIPRDR_FORMAT)))) + { + WLog_ERR(TAG, "failed to allocate format list"); + goto error; + } + + for (UINT32 i = 0; i < *numFormats; i++) + { + const char* formatName = NULL; + size_t formatNameLength = 0; + + if (!Stream_CheckAndLogRequiredLength(TAG, s, sizeof(UINT32))) + goto error; + + Stream_Read_UINT32(s, formats[i].formatId); + formatName = (const char*)Stream_Pointer(s); + formatNameLength = strnlen(formatName, Stream_GetRemainingLength(s)); + + if (formatNameLength == Stream_GetRemainingLength(s)) + { + WLog_ERR(TAG, "missing terminating null byte, %" PRIuz " bytes left to read", + formatNameLength); + goto error; + } + + formats[i].formatName = strndup(formatName, formatNameLength); + Stream_Seek(s, formatNameLength + 1); + } + + Stream_Free(s, FALSE); + return formats; +error: + Stream_Free(s, FALSE); + free(formats); + *numFormats = 0; + return NULL; +} + +static void xf_cliprdr_free_formats(CLIPRDR_FORMAT* formats, UINT32 numFormats) +{ + WINPR_ASSERT(formats || (numFormats == 0)); + + for (UINT32 i = 0; i < numFormats; i++) + { + free(formats[i].formatName); + } + + free(formats); +} + +static CLIPRDR_FORMAT* xf_cliprdr_get_raw_server_formats(xfClipboard* clipboard, UINT32* numFormats) +{ + Atom type = None; + int format = 0; + unsigned long length = 0; + unsigned long remaining = 0; + BYTE* data = NULL; + CLIPRDR_FORMAT* formats = NULL; + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(numFormats); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + *numFormats = 0; + + Window owner = XGetSelectionOwner(xfc->display, clipboard->clipboard_atom); + LogTagAndXGetWindowProperty(TAG, xfc->display, owner, clipboard->raw_format_list_atom, 0, 4096, + False, clipboard->raw_format_list_atom, &type, &format, &length, + &remaining, &data); + + if (data && length > 0 && format == 8 && type == clipboard->raw_format_list_atom) + { + formats = xf_cliprdr_parse_server_format_list(data, length, numFormats); + } + else + { + WLog_ERR(TAG, + "failed to retrieve raw format list: data=%p, length=%lu, format=%d, type=%lu " + "(expected=%lu)", + (void*)data, length, format, (unsigned long)type, + (unsigned long)clipboard->raw_format_list_atom); + } + + if (data) + XFree(data); + + return formats; +} + +static BOOL xf_cliprdr_should_add_format(const CLIPRDR_FORMAT* formats, size_t count, + const xfCliprdrFormat* xformat) +{ + WINPR_ASSERT(formats); + + if (!xformat) + return FALSE; + + for (size_t x = 0; x < count; x++) + { + const CLIPRDR_FORMAT* format = &formats[x]; + if (format->formatId == xformat->formatToRequest) + return FALSE; + } + return TRUE; +} + +static CLIPRDR_FORMAT* xf_cliprdr_get_formats_from_targets(xfClipboard* clipboard, + UINT32* numFormats) +{ + Atom atom = None; + BYTE* data = NULL; + int format_property = 0; + unsigned long length = 0; + unsigned long bytes_left = 0; + CLIPRDR_FORMAT* formats = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(numFormats); + + xfContext* xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + *numFormats = 0; + LogTagAndXGetWindowProperty(TAG, xfc->display, xfc->drawable, clipboard->property_atom, 0, 200, + 0, XA_ATOM, &atom, &format_property, &length, &bytes_left, &data); + + if (length > 0) + { + if (!data) + { + WLog_ERR(TAG, "XGetWindowProperty set length = %lu but data is NULL", length); + goto out; + } + + if (!(formats = (CLIPRDR_FORMAT*)calloc(length, sizeof(CLIPRDR_FORMAT)))) + { + WLog_ERR(TAG, "failed to allocate %lu CLIPRDR_FORMAT structs", length); + goto out; + } + } + + for (unsigned long i = 0; i < length; i++) + { + Atom tatom = ((Atom*)data)[i]; + const xfCliprdrFormat* format = xf_cliprdr_get_client_format_by_atom(clipboard, tatom); + + if (xf_cliprdr_should_add_format(formats, *numFormats, format)) + { + CLIPRDR_FORMAT* cformat = &formats[*numFormats]; + cformat->formatId = format->formatToRequest; + if (format->formatName) + { + cformat->formatName = _strdup(format->formatName); + WINPR_ASSERT(cformat->formatName); + } + else + cformat->formatName = NULL; + + *numFormats += 1; + } + } + +out: + + if (data) + XFree(data); + + return formats; +} + +static CLIPRDR_FORMAT* xf_cliprdr_get_client_formats(xfClipboard* clipboard, UINT32* numFormats) +{ + CLIPRDR_FORMAT* formats = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(numFormats); + + *numFormats = 0; + + if (xf_cliprdr_is_raw_transfer_available(clipboard)) + { + formats = xf_cliprdr_get_raw_server_formats(clipboard, numFormats); + } + + if (*numFormats == 0) + { + xf_cliprdr_free_formats(formats, *numFormats); + formats = xf_cliprdr_get_formats_from_targets(clipboard, numFormats); + } + + return formats; +} + +static void xf_cliprdr_provide_server_format_list(xfClipboard* clipboard) +{ + wStream* formats = NULL; + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + formats = xf_cliprdr_serialize_server_format_list(clipboard); + + if (formats) + { + const size_t len = Stream_Length(formats); + WINPR_ASSERT(len <= INT32_MAX); + LogTagAndXChangeProperty(TAG, xfc->display, xfc->drawable, clipboard->raw_format_list_atom, + clipboard->raw_format_list_atom, 8, PropModeReplace, + Stream_Buffer(formats), (int)len); + } + else + { + LogTagAndXDeleteProperty(TAG, xfc->display, xfc->drawable, clipboard->raw_format_list_atom); + } + + Stream_Free(formats, TRUE); +} + +static BOOL xf_clipboard_format_equal(const CLIPRDR_FORMAT* a, const CLIPRDR_FORMAT* b) +{ + WINPR_ASSERT(a); + WINPR_ASSERT(b); + + if (a->formatId != b->formatId) + return FALSE; + if (!a->formatName && !b->formatName) + return TRUE; + if (!a->formatName || !b->formatName) + return FALSE; + return strcmp(a->formatName, b->formatName) == 0; +} + +static BOOL xf_clipboard_changed(xfClipboard* clipboard, const CLIPRDR_FORMAT* formats, + UINT32 numFormats) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(formats || (numFormats == 0)); + + if (clipboard->lastSentNumFormats != numFormats) + return TRUE; + + for (UINT32 x = 0; x < numFormats; x++) + { + const CLIPRDR_FORMAT* cur = &clipboard->lastSentFormats[x]; + BOOL contained = FALSE; + for (UINT32 y = 0; y < numFormats; y++) + { + if (xf_clipboard_format_equal(cur, &formats[y])) + { + contained = TRUE; + break; + } + } + if (!contained) + return TRUE; + } + + return FALSE; +} + +static void xf_clipboard_formats_free(xfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + xf_cliprdr_free_formats(clipboard->lastSentFormats, clipboard->lastSentNumFormats); + clipboard->lastSentFormats = NULL; + clipboard->lastSentNumFormats = 0; +} + +static BOOL xf_clipboard_copy_formats(xfClipboard* clipboard, const CLIPRDR_FORMAT* formats, + UINT32 numFormats) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(formats || (numFormats == 0)); + + xf_clipboard_formats_free(clipboard); + if (numFormats > 0) + clipboard->lastSentFormats = calloc(numFormats, sizeof(CLIPRDR_FORMAT)); + if (!clipboard->lastSentFormats) + return FALSE; + clipboard->lastSentNumFormats = numFormats; + for (UINT32 x = 0; x < numFormats; x++) + { + CLIPRDR_FORMAT* lcur = &clipboard->lastSentFormats[x]; + const CLIPRDR_FORMAT* cur = &formats[x]; + *lcur = *cur; + if (cur->formatName) + lcur->formatName = _strdup(cur->formatName); + } + return FALSE; +} + +static UINT xf_cliprdr_send_format_list(xfClipboard* clipboard, const CLIPRDR_FORMAT* formats, + UINT32 numFormats, BOOL force) +{ + union + { + const CLIPRDR_FORMAT* cpv; + CLIPRDR_FORMAT* pv; + } cnv = { .cpv = formats }; + const CLIPRDR_FORMAT_LIST formatList = { .common.msgFlags = 0, + .numFormats = numFormats, + .formats = cnv.pv, + .common.msgType = CB_FORMAT_LIST }; + UINT ret = 0; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(formats || (numFormats == 0)); + + if (!force && !xf_clipboard_changed(clipboard, formats, numFormats)) + return CHANNEL_RC_OK; + +#if defined(WITH_DEBUG_CLIPRDR) + for (UINT32 x = 0; x < numFormats; x++) + { + const CLIPRDR_FORMAT* format = &formats[x]; + DEBUG_CLIPRDR("announcing format 0x%08" PRIx32 " [%s] [%s]", format->formatId, + ClipboardGetFormatIdString(format->formatId), format->formatName); + } +#endif + + xf_clipboard_copy_formats(clipboard, formats, numFormats); + /* Ensure all pending requests are answered. */ + xf_cliprdr_send_data_response(clipboard, NULL, NULL, 0); + + xf_cliprdr_clear_cached_data(clipboard); + + ret = cliprdr_file_context_notify_new_client_format_list(clipboard->file); + if (ret) + return ret; + + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatList); + return clipboard->context->ClientFormatList(clipboard->context, &formatList); +} + +static void xf_cliprdr_get_requested_targets(xfClipboard* clipboard) +{ + UINT32 numFormats = 0; + CLIPRDR_FORMAT* formats = xf_cliprdr_get_client_formats(clipboard, &numFormats); + xf_cliprdr_send_format_list(clipboard, formats, numFormats, FALSE); + xf_cliprdr_free_formats(formats, numFormats); +} + +static void xf_cliprdr_process_requested_data(xfClipboard* clipboard, BOOL hasData, + const BYTE* data, size_t size) +{ + BOOL bSuccess = 0; + UINT32 SrcSize = 0; + UINT32 DstSize = 0; + INT64 srcFormatId = -1; + BYTE* pDstData = NULL; + const xfCliprdrFormat* format = NULL; + + WINPR_ASSERT(clipboard); + + if (clipboard->incr_starts && hasData) + return; + + /* Reset incr_data_length, as we've reached the end of a possible incremental update. + * this ensures on next event that the buffer is not reused. */ + clipboard->incr_data_length = 0; + + format = xf_cliprdr_get_client_format_by_id( + clipboard, WINPR_ASSERTING_INT_CAST(uint32_t, clipboard->requestedFormatId)); + + if (!hasData || !data || !format) + { + xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + return; + } + + switch (format->formatToRequest) + { + case CF_RAW: + srcFormatId = CF_RAW; + break; + + case CF_TEXT: + case CF_OEMTEXT: + case CF_UNICODETEXT: + srcFormatId = format->localFormat; + break; + + default: + srcFormatId = format->localFormat; + break; + } + + if (srcFormatId < 0) + { + xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + return; + } + + ClipboardLock(clipboard->system); + SrcSize = (UINT32)size; + bSuccess = ClipboardSetData(clipboard->system, (UINT32)srcFormatId, data, SrcSize); + + if (bSuccess) + { + DstSize = 0; + pDstData = (BYTE*)ClipboardGetData(clipboard->system, format->formatToRequest, &DstSize); + } + ClipboardUnlock(clipboard->system); + + if (!pDstData) + { + xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + return; + } + + /* + * File lists require a bit of postprocessing to convert them from WinPR's FILDESCRIPTOR + * format to CLIPRDR_FILELIST expected by the server. + * + * We check for "FileGroupDescriptorW" format being registered (i.e., nonzero) in order + * to not process CF_RAW as a file list in case WinPR does not support file transfers. + */ + ClipboardLock(clipboard->system); + if (format->formatToRequest && + (format->formatToRequest == + ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW))) + { + UINT error = NO_ERROR; + FILEDESCRIPTORW* file_array = (FILEDESCRIPTORW*)pDstData; + UINT32 file_count = DstSize / sizeof(FILEDESCRIPTORW); + pDstData = NULL; + DstSize = 0; + + const UINT32 flags = cliprdr_file_context_remote_get_flags(clipboard->file); + error = cliprdr_serialize_file_list_ex(flags, file_array, file_count, &pDstData, &DstSize); + + if (error) + WLog_ERR(TAG, "failed to serialize CLIPRDR_FILELIST: 0x%08X", error); + else + { + UINT32 formatId = ClipboardGetFormatId(clipboard->system, mime_uri_list); + UINT32 url_size = 0; + + char* url = ClipboardGetData(clipboard->system, formatId, &url_size); + cliprdr_file_context_update_client_data(clipboard->file, url, url_size); + free(url); + } + + free(file_array); + } + ClipboardUnlock(clipboard->system); + + xf_cliprdr_send_data_response(clipboard, format, pDstData, DstSize); + free(pDstData); +} + +static BOOL xf_restore_input_flags(xfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + xfContext* xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (clipboard->event_mask != 0) + { + XSelectInput(xfc->display, xfc->drawable, clipboard->event_mask); + clipboard->event_mask = 0; + } + return TRUE; +} + +static BOOL append(xfClipboard* clipboard, const void* sdata, size_t length) +{ + WINPR_ASSERT(clipboard); + + const size_t size = length + clipboard->incr_data_length + 2; + BYTE* data = realloc(clipboard->incr_data, size); + if (!data) + return FALSE; + clipboard->incr_data = data; + memcpy(&data[clipboard->incr_data_length], sdata, length); + clipboard->incr_data_length += length; + clipboard->incr_data[clipboard->incr_data_length + 0] = '\0'; + clipboard->incr_data[clipboard->incr_data_length + 1] = '\0'; + return TRUE; +} + +static BOOL xf_cliprdr_stop_incr(xfClipboard* clipboard) +{ + clipboard->incr_starts = FALSE; + clipboard->incr_data_length = 0; + return xf_restore_input_flags(clipboard); +} + +static BOOL xf_cliprdr_get_requested_data(xfClipboard* clipboard, Atom target) +{ + WINPR_ASSERT(clipboard); + + xfContext* xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + const xfCliprdrFormat* format = xf_cliprdr_get_client_format_by_id( + clipboard, WINPR_ASSERTING_INT_CAST(uint32_t, clipboard->requestedFormatId)); + + if (!format || (format->atom != target)) + { + xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + return FALSE; + } + + Atom type = 0; + BOOL has_data = FALSE; + int format_property = 0; + unsigned long length = 0; + unsigned long total_bytes = 0; + BYTE* property_data = NULL; + const int rc = LogTagAndXGetWindowProperty( + TAG, xfc->display, xfc->drawable, clipboard->property_atom, 0, 0, False, target, &type, + &format_property, &length, &total_bytes, &property_data); + if (rc != Success) + { + xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + return FALSE; + } + + size_t len = 0; + + /* No data, empty return */ + if ((total_bytes <= 0) && !clipboard->incr_starts) + { + xf_cliprdr_stop_incr(clipboard); + } + /* We have to read incremental updates */ + else if (type == clipboard->incr_atom) + { + xf_cliprdr_stop_incr(clipboard); + clipboard->incr_starts = TRUE; + has_data = TRUE; /* data will follow in PropertyNotify event */ + } + else + { + BYTE* incremental_data = NULL; + unsigned long incremental_len = 0; + + /* Incremental updates completed, pass data */ + len = clipboard->incr_data_length; + if (total_bytes <= 0) + { + xf_cliprdr_stop_incr(clipboard); + has_data = TRUE; + } + /* Read incremental data batch */ + else if (LogTagAndXGetWindowProperty( + TAG, xfc->display, xfc->drawable, clipboard->property_atom, 0, + WINPR_ASSERTING_INT_CAST(int32_t, total_bytes), False, target, &type, + &format_property, &incremental_len, &length, &incremental_data) == Success) + { + has_data = append(clipboard, incremental_data, incremental_len); + len = clipboard->incr_data_length; + } + + if (incremental_data) + XFree(incremental_data); + } + + LogTagAndXDeleteProperty(TAG, xfc->display, xfc->drawable, clipboard->property_atom); + xf_cliprdr_process_requested_data(clipboard, has_data, clipboard->incr_data, len); + + return TRUE; +} + +static void xf_cliprdr_append_target(xfClipboard* clipboard, Atom target) +{ + WINPR_ASSERT(clipboard); + + if (clipboard->numTargets >= ARRAYSIZE(clipboard->targets)) + return; + + for (size_t i = 0; i < clipboard->numTargets; i++) + { + if (clipboard->targets[i] == target) + return; + } + + clipboard->targets[clipboard->numTargets++] = target; +} + +static void xf_cliprdr_provide_targets(xfClipboard* clipboard, const XSelectionEvent* respond) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (respond->property != None) + { + WINPR_ASSERT(clipboard->numTargets <= INT32_MAX); + LogTagAndXChangeProperty(TAG, xfc->display, respond->requestor, respond->property, XA_ATOM, + 32, PropModeReplace, (BYTE*)clipboard->targets, + (int)clipboard->numTargets); + } +} + +static void xf_cliprdr_provide_timestamp(xfClipboard* clipboard, const XSelectionEvent* respond) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (respond->property != None) + { + LogTagAndXChangeProperty(TAG, xfc->display, respond->requestor, respond->property, + XA_INTEGER, 32, PropModeReplace, + (BYTE*)&clipboard->selection_ownership_timestamp, 1); + } +} + +static void xf_cliprdr_provide_data(xfClipboard* clipboard, const XSelectionEvent* respond, + const BYTE* data, UINT32 size) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (respond->property != None) + { + LogTagAndXChangeProperty(TAG, xfc->display, respond->requestor, respond->property, + respond->target, 8, PropModeReplace, data, + WINPR_ASSERTING_INT_CAST(int32_t, size)); + } +} + +static void log_selection_event(xfContext* xfc, const XEvent* event) +{ + const DWORD level = WLOG_TRACE; + static wLog* _log_cached_ptr = NULL; + if (!_log_cached_ptr) + _log_cached_ptr = WLog_Get(TAG); + if (WLog_IsLevelActive(_log_cached_ptr, level)) + { + + switch (event->type) + { + case SelectionClear: + { + const XSelectionClearEvent* xevent = &event->xselectionclear; + char* selection = + Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection); + WLog_Print(_log_cached_ptr, level, "got event %s [selection %s]", + x11_event_string(event->type), selection); + XFree(selection); + } + break; + case SelectionNotify: + { + const XSelectionEvent* xevent = &event->xselection; + char* selection = + Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection); + char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target); + char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property); + WLog_Print(_log_cached_ptr, level, + "got event %s [selection %s, target %s, property %s]", + x11_event_string(event->type), selection, target, property); + XFree(selection); + XFree(target); + XFree(property); + } + break; + case SelectionRequest: + { + const XSelectionRequestEvent* xevent = &event->xselectionrequest; + char* selection = + Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection); + char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target); + char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property); + WLog_Print(_log_cached_ptr, level, + "got event %s [selection %s, target %s, property %s]", + x11_event_string(event->type), selection, target, property); + XFree(selection); + XFree(target); + XFree(property); + } + break; + case PropertyNotify: + { + const XPropertyEvent* xevent = &event->xproperty; + char* atom = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->atom); + WLog_Print(_log_cached_ptr, level, "got event %s [atom %s]", + x11_event_string(event->type), atom); + XFree(atom); + } + break; + default: + break; + } + } +} + +static BOOL xf_cliprdr_process_selection_notify(xfClipboard* clipboard, + const XSelectionEvent* xevent) +{ + WINPR_ASSERT(clipboard); + WINPR_ASSERT(xevent); + + if (xevent->target == clipboard->targets[1]) + { + if (xevent->property == None) + { + xf_cliprdr_send_client_format_list(clipboard, FALSE); + } + else + { + xf_cliprdr_get_requested_targets(clipboard); + } + + return TRUE; + } + else + { + return xf_cliprdr_get_requested_data(clipboard, xevent->target); + } +} + +void xf_cliprdr_clear_cached_data(xfClipboard* clipboard) +{ + WINPR_ASSERT(clipboard); + + ClipboardLock(clipboard->system); + ClipboardEmpty(clipboard->system); + + HashTable_Clear(clipboard->cachedData); + HashTable_Clear(clipboard->cachedRawData); + + cliprdr_file_context_clear(clipboard->file); + + xf_cliprdr_stop_incr(clipboard); + ClipboardUnlock(clipboard->system); +} + +static void* format_to_cache_slot(UINT32 format) +{ + union + { + uintptr_t uptr; + void* vptr; + } cnv; + cnv.uptr = 0x100000000ULL + format; + return cnv.vptr; +} + +static UINT32 get_dst_format_id_for_local_request(xfClipboard* clipboard, + const xfCliprdrFormat* format) +{ + UINT32 dstFormatId = 0; + + WINPR_ASSERT(format); + + if (!format->formatName) + return format->localFormat; + + ClipboardLock(clipboard->system); + if (strcmp(format->formatName, type_HtmlFormat) == 0) + dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html); + ClipboardUnlock(clipboard->system); + + if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0) + dstFormatId = format->localFormat; + + return dstFormatId; +} + +static void get_src_format_info_for_local_request(xfClipboard* clipboard, + const xfCliprdrFormat* format, + UINT32* srcFormatId, BOOL* nullTerminated) +{ + *srcFormatId = 0; + *nullTerminated = FALSE; + + if (format->formatName) + { + ClipboardLock(clipboard->system); + if (strcmp(format->formatName, type_HtmlFormat) == 0) + { + *srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat); + *nullTerminated = TRUE; + } + else if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0) + { + *srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + *nullTerminated = TRUE; + } + ClipboardUnlock(clipboard->system); + } + else + { + *srcFormatId = format->formatToRequest; + switch (format->formatToRequest) + { + case CF_TEXT: + case CF_OEMTEXT: + case CF_UNICODETEXT: + *nullTerminated = TRUE; + break; + case CF_DIB: + *srcFormatId = CF_DIB; + break; + case CF_TIFF: + *srcFormatId = CF_TIFF; + break; + default: + break; + } + } +} + +static xfCachedData* convert_data_from_existing_raw_data(xfClipboard* clipboard, + xfCachedData* cached_raw_data, + UINT32 srcFormatId, BOOL nullTerminated, + UINT32 dstFormatId) +{ + xfCachedData* cached_data = NULL; + BOOL success = 0; + BYTE* dst_data = NULL; + UINT32 dst_size = 0; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(cached_raw_data); + WINPR_ASSERT(cached_raw_data->data); + + ClipboardLock(clipboard->system); + success = ClipboardSetData(clipboard->system, srcFormatId, cached_raw_data->data, + cached_raw_data->data_length); + if (!success) + { + WLog_WARN(TAG, "Failed to set clipboard data (formatId: %u, data: %p, data_length: %u)", + srcFormatId, cached_raw_data->data, cached_raw_data->data_length); + ClipboardUnlock(clipboard->system); + return NULL; + } + + dst_data = ClipboardGetData(clipboard->system, dstFormatId, &dst_size); + if (!dst_data) + { + WLog_WARN(TAG, "Failed to get converted clipboard data"); + ClipboardUnlock(clipboard->system); + return NULL; + } + ClipboardUnlock(clipboard->system); + + if (nullTerminated) + { + BYTE* nullTerminator = memchr(dst_data, '\0', dst_size); + if (nullTerminator) + { + const intptr_t diff = nullTerminator - dst_data; + WINPR_ASSERT(diff >= 0); + WINPR_ASSERT(diff <= UINT32_MAX); + dst_size = (UINT32)diff; + } + } + + cached_data = xf_cached_data_new(dst_data, dst_size); + if (!cached_data) + { + WLog_WARN(TAG, "Failed to allocate cache entry"); + free(dst_data); + return NULL; + } + + if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId), cached_data)) + { + WLog_WARN(TAG, "Failed to cache clipboard data"); + xf_cached_data_free(cached_data); + return NULL; + } + + return cached_data; +} + +static BOOL xf_cliprdr_process_selection_request(xfClipboard* clipboard, + const XSelectionRequestEvent* xevent) +{ + int fmt = 0; + Atom type = 0; + UINT32 formatId = 0; + XSelectionEvent* respond = NULL; + BYTE* data = NULL; + BOOL delayRespond = 0; + BOOL rawTransfer = 0; + unsigned long length = 0; + unsigned long bytes_left = 0; + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(xevent); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + if (xevent->owner != xfc->drawable) + return FALSE; + + delayRespond = FALSE; + + if (!(respond = (XSelectionEvent*)calloc(1, sizeof(XSelectionEvent)))) + { + WLog_ERR(TAG, "failed to allocate XEvent data"); + return FALSE; + } + + respond->property = None; + respond->type = SelectionNotify; + respond->display = xevent->display; + respond->requestor = xevent->requestor; + respond->selection = xevent->selection; + respond->target = xevent->target; + respond->time = xevent->time; + + if (xevent->target == clipboard->targets[0]) /* TIMESTAMP */ + { + /* Someone else requests the selection's timestamp */ + respond->property = xevent->property; + xf_cliprdr_provide_timestamp(clipboard, respond); + } + else if (xevent->target == clipboard->targets[1]) /* TARGETS */ + { + /* Someone else requests our available formats */ + respond->property = xevent->property; + xf_cliprdr_provide_targets(clipboard, respond); + } + else + { + const CLIPRDR_FORMAT* format = + xf_cliprdr_get_server_format_by_atom(clipboard, xevent->target); + const xfCliprdrFormat* cformat = + xf_cliprdr_get_client_format_by_atom(clipboard, xevent->target); + + if (format && (xevent->requestor != xfc->drawable)) + { + formatId = format->formatId; + rawTransfer = FALSE; + xfCachedData* cached_data = NULL; + UINT32 dstFormatId = 0; + + if (formatId == CF_RAW) + { + if (LogTagAndXGetWindowProperty( + TAG, xfc->display, xevent->requestor, clipboard->property_atom, 0, 4, 0, + XA_INTEGER, &type, &fmt, &length, &bytes_left, &data) != Success) + { + } + + if (data) + { + rawTransfer = TRUE; + CopyMemory(&formatId, data, 4); + XFree(data); + } + } + + dstFormatId = get_dst_format_id_for_local_request(clipboard, cformat); + DEBUG_CLIPRDR("formatId: %u, dstFormatId: %u", formatId, dstFormatId); + + if (!rawTransfer) + cached_data = HashTable_GetItemValue(clipboard->cachedData, + format_to_cache_slot(dstFormatId)); + else + cached_data = HashTable_GetItemValue(clipboard->cachedRawData, + format_to_cache_slot(formatId)); + + DEBUG_CLIPRDR("hasCachedData: %u, rawTransfer: %u", cached_data ? 1 : 0, rawTransfer); + + if (!cached_data && !rawTransfer) + { + UINT32 srcFormatId = 0; + BOOL nullTerminated = FALSE; + xfCachedData* cached_raw_data = NULL; + + get_src_format_info_for_local_request(clipboard, cformat, &srcFormatId, + &nullTerminated); + cached_raw_data = + HashTable_GetItemValue(clipboard->cachedRawData, (void*)(UINT_PTR)srcFormatId); + + DEBUG_CLIPRDR("hasCachedRawData: %u, rawDataLength: %u", cached_raw_data ? 1 : 0, + cached_raw_data ? cached_raw_data->data_length : 0); + + if (cached_raw_data && cached_raw_data->data_length != 0) + cached_data = convert_data_from_existing_raw_data( + clipboard, cached_raw_data, srcFormatId, nullTerminated, dstFormatId); + } + + DEBUG_CLIPRDR("hasCachedData: %u", cached_data ? 1 : 0); + + if (cached_data) + { + /* Cached clipboard data available. Send it now */ + respond->property = xevent->property; + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + xf_cliprdr_provide_data(clipboard, respond, cached_data->data, + cached_data->data_length); + } + else if (clipboard->respond) + { + /* duplicate request */ + } + else + { + WINPR_ASSERT(cformat); + + /** + * Send clipboard data request to the server. + * Response will be postponed after receiving the data + */ + respond->property = xevent->property; + clipboard->respond = respond; + requested_format_replace(&clipboard->requestedFormat, formatId, + cformat->formatName); + clipboard->data_raw_format = rawTransfer; + delayRespond = TRUE; + xf_cliprdr_send_data_request(clipboard, formatId, cformat); + } + } + } + + if (!delayRespond) + { + union + { + XEvent* ev; + XSelectionEvent* sev; + } conv; + + conv.sev = respond; + XSendEvent(xfc->display, xevent->requestor, 0, 0, conv.ev); + XFlush(xfc->display); + free(respond); + } + + return TRUE; +} + +static BOOL xf_cliprdr_process_selection_clear(xfClipboard* clipboard, + const XSelectionClearEvent* xevent) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(xevent); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + WINPR_UNUSED(xevent); + + if (xf_cliprdr_is_self_owned(clipboard)) + return FALSE; + + LogTagAndXDeleteProperty(TAG, xfc->display, clipboard->root_window, clipboard->property_atom); + return TRUE; +} + +static BOOL xf_cliprdr_process_property_notify(xfClipboard* clipboard, const XPropertyEvent* xevent) +{ + const xfCliprdrFormat* format = NULL; + xfContext* xfc = NULL; + + if (!clipboard) + return TRUE; + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xevent); + + if (xevent->atom == clipboard->timestamp_property_atom) + { + /* This is the response to the property change we did + * in xf_cliprdr_prepare_to_set_selection_owner. Now + * we can set ourselves as the selection owner. (See + * comments in those functions below.) */ + xf_cliprdr_set_selection_owner(xfc, clipboard, xevent->time); + return TRUE; + } + + if (xevent->atom != clipboard->property_atom) + return FALSE; /* Not cliprdr-related */ + + if (xevent->window == clipboard->root_window) + { + xf_cliprdr_send_client_format_list(clipboard, FALSE); + } + else if ((xevent->window == xfc->drawable) && (xevent->state == PropertyNewValue) && + clipboard->incr_starts) + { + format = xf_cliprdr_get_client_format_by_id( + clipboard, WINPR_ASSERTING_INT_CAST(uint32_t, clipboard->requestedFormatId)); + + if (format) + xf_cliprdr_get_requested_data(clipboard, format->atom); + } + + return TRUE; +} + +void xf_cliprdr_handle_xevent(xfContext* xfc, const XEvent* event) +{ + xfClipboard* clipboard = NULL; + + if (!xfc || !event) + return; + + clipboard = xfc->clipboard; + + if (!clipboard) + return; + +#ifdef WITH_XFIXES + + if (clipboard->xfixes_supported && + event->type == XFixesSelectionNotify + clipboard->xfixes_event_base) + { + const XFixesSelectionNotifyEvent* se = (const XFixesSelectionNotifyEvent*)event; + + if (se->subtype == XFixesSetSelectionOwnerNotify) + { + if (se->selection != clipboard->clipboard_atom) + return; + + if (XGetSelectionOwner(xfc->display, se->selection) == xfc->drawable) + return; + + clipboard->owner = None; + xf_cliprdr_check_owner(clipboard); + } + + return; + } + +#endif + + switch (event->type) + { + case SelectionNotify: + log_selection_event(xfc, event); + xf_cliprdr_process_selection_notify(clipboard, &event->xselection); + break; + + case SelectionRequest: + log_selection_event(xfc, event); + xf_cliprdr_process_selection_request(clipboard, &event->xselectionrequest); + break; + + case SelectionClear: + log_selection_event(xfc, event); + xf_cliprdr_process_selection_clear(clipboard, &event->xselectionclear); + break; + + case PropertyNotify: + log_selection_event(xfc, event); + xf_cliprdr_process_property_notify(clipboard, &event->xproperty); + break; + + case FocusIn: + if (!clipboard->xfixes_supported) + { + xf_cliprdr_check_owner(clipboard); + } + + break; + default: + break; + } +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_send_client_capabilities(xfClipboard* clipboard) +{ + CLIPRDR_CAPABILITIES capabilities = { 0 }; + CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet = { 0 }; + + WINPR_ASSERT(clipboard); + + capabilities.cCapabilitiesSets = 1; + capabilities.capabilitySets = (CLIPRDR_CAPABILITY_SET*)&(generalCapabilitySet); + generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL; + generalCapabilitySet.capabilitySetLength = 12; + generalCapabilitySet.version = CB_CAPS_VERSION_2; + generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES; + + WINPR_ASSERT(clipboard); + generalCapabilitySet.generalFlags |= cliprdr_file_context_current_flags(clipboard->file); + + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientCapabilities); + return clipboard->context->ClientCapabilities(clipboard->context, &capabilities); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_send_client_format_list(xfClipboard* clipboard, BOOL force) +{ + WINPR_ASSERT(clipboard); + + xfContext* xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + UINT32 numFormats = 0; + CLIPRDR_FORMAT* formats = xf_cliprdr_get_client_formats(clipboard, &numFormats); + + const UINT ret = xf_cliprdr_send_format_list(clipboard, formats, numFormats, force); + + if (clipboard->owner && clipboard->owner != xfc->drawable) + { + /* Request the owner for TARGETS, and wait for SelectionNotify event */ + LogTagAndXConvertSelection(TAG, xfc->display, clipboard->clipboard_atom, + clipboard->targets[1], clipboard->property_atom, xfc->drawable, + CurrentTime); + } + + xf_cliprdr_free_formats(formats, numFormats); + + return ret; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_send_client_format_list_response(xfClipboard* clipboard, BOOL status) +{ + CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse = { 0 }; + + formatListResponse.common.msgType = CB_FORMAT_LIST_RESPONSE; + formatListResponse.common.msgFlags = status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL; + formatListResponse.common.dataLen = 0; + + WINPR_ASSERT(clipboard); + WINPR_ASSERT(clipboard->context); + WINPR_ASSERT(clipboard->context->ClientFormatListResponse); + return clipboard->context->ClientFormatListResponse(clipboard->context, &formatListResponse); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_monitor_ready(CliprdrClientContext* context, + const CLIPRDR_MONITOR_READY* monitorReady) +{ + UINT ret = 0; + xfClipboard* clipboard = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(monitorReady); + + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + WINPR_UNUSED(monitorReady); + + if ((ret = xf_cliprdr_send_client_capabilities(clipboard)) != CHANNEL_RC_OK) + return ret; + + xf_clipboard_formats_free(clipboard); + + if ((ret = xf_cliprdr_send_client_format_list(clipboard, TRUE)) != CHANNEL_RC_OK) + return ret; + + clipboard->sync = TRUE; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_server_capabilities(CliprdrClientContext* context, + const CLIPRDR_CAPABILITIES* capabilities) +{ + const CLIPRDR_GENERAL_CAPABILITY_SET* generalCaps = NULL; + const BYTE* capsPtr = NULL; + xfClipboard* clipboard = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(capabilities); + + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + capsPtr = (const BYTE*)capabilities->capabilitySets; + WINPR_ASSERT(capsPtr); + + cliprdr_file_context_remote_set_flags(clipboard->file, 0); + + for (UINT32 i = 0; i < capabilities->cCapabilitiesSets; i++) + { + const CLIPRDR_CAPABILITY_SET* caps = (const CLIPRDR_CAPABILITY_SET*)capsPtr; + + if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL) + { + generalCaps = (const CLIPRDR_GENERAL_CAPABILITY_SET*)caps; + + cliprdr_file_context_remote_set_flags(clipboard->file, generalCaps->generalFlags); + } + + capsPtr += caps->capabilitySetLength; + } + + return CHANNEL_RC_OK; +} + +static void xf_cliprdr_prepare_to_set_selection_owner(xfContext* xfc, xfClipboard* clipboard) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(clipboard); + /* + * When you're writing to the selection in response to a + * normal X event like a mouse click or keyboard action, you + * get the selection timestamp by copying the time field out + * of that X event. Here, we're doing it on our own + * initiative, so we have to _request_ the X server time. + * + * There isn't a GetServerTime request in the X protocol, so I + * work around it by setting a property on our own window, and + * waiting for a PropertyNotify event to come back telling me + * it's been done - which will have a timestamp we can use. + */ + + /* We have to set the property to some value, but it doesn't + * matter what. Set it to its own name, which we have here + * anyway! */ + Atom value = clipboard->timestamp_property_atom; + + LogTagAndXChangeProperty(TAG, xfc->display, xfc->drawable, clipboard->timestamp_property_atom, + XA_ATOM, 32, PropModeReplace, (BYTE*)&value, 1); + XFlush(xfc->display); +} + +static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(clipboard); + /* + * Actually set ourselves up as the selection owner, now that + * we have a timestamp to use. + */ + + clipboard->selection_ownership_timestamp = timestamp; + XSetSelectionOwner(xfc->display, clipboard->clipboard_atom, xfc->drawable, timestamp); + XFlush(xfc->display); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_cliprdr_server_format_list(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST* formatList) +{ + xfContext* xfc = NULL; + UINT ret = 0; + xfClipboard* clipboard = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(formatList); + + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + xf_lock_x11(xfc); + + /* Clear the active SelectionRequest, as it is now invalid */ + free(clipboard->respond); + clipboard->respond = NULL; + + xf_clipboard_formats_free(clipboard); + xf_cliprdr_clear_cached_data(clipboard); + requested_format_free(&clipboard->requestedFormat); + + xf_clipboard_free_server_formats(clipboard); + + clipboard->numServerFormats = formatList->numFormats + 1; /* +1 for CF_RAW */ + + if (!(clipboard->serverFormats = + (CLIPRDR_FORMAT*)calloc(clipboard->numServerFormats, sizeof(CLIPRDR_FORMAT)))) + { + WLog_ERR(TAG, "failed to allocate %d CLIPRDR_FORMAT structs", clipboard->numServerFormats); + ret = CHANNEL_RC_NO_MEMORY; + goto out; + } + + for (size_t i = 0; i < formatList->numFormats; i++) + { + const CLIPRDR_FORMAT* format = &formatList->formats[i]; + CLIPRDR_FORMAT* srvFormat = &clipboard->serverFormats[i]; + + srvFormat->formatId = format->formatId; + + if (format->formatName) + { + srvFormat->formatName = _strdup(format->formatName); + + if (!srvFormat->formatName) + { + for (UINT32 k = 0; k < i; k++) + free(clipboard->serverFormats[k].formatName); + + clipboard->numServerFormats = 0; + free(clipboard->serverFormats); + clipboard->serverFormats = NULL; + ret = CHANNEL_RC_NO_MEMORY; + goto out; + } + } + } + + ret = cliprdr_file_context_notify_new_server_format_list(clipboard->file); + if (ret) + goto out; + + /* CF_RAW is always implicitly supported by the server */ + { + CLIPRDR_FORMAT* format = &clipboard->serverFormats[formatList->numFormats]; + format->formatId = CF_RAW; + format->formatName = NULL; + } + xf_cliprdr_provide_server_format_list(clipboard); + clipboard->numTargets = 2; + + for (size_t i = 0; i < formatList->numFormats; i++) + { + const CLIPRDR_FORMAT* format = &formatList->formats[i]; + + for (size_t j = 0; j < clipboard->numClientFormats; j++) + { + const xfCliprdrFormat* clientFormat = &clipboard->clientFormats[j]; + if (xf_cliprdr_formats_equal(format, clientFormat)) + { + if ((clientFormat->formatName != NULL) && + (strcmp(type_FileGroupDescriptorW, clientFormat->formatName) == 0)) + { + if (!cliprdr_file_context_has_local_support(clipboard->file)) + continue; + } + xf_cliprdr_append_target(clipboard, clientFormat->atom); + } + } + } + + ret = xf_cliprdr_send_client_format_list_response(clipboard, TRUE); + if (xfc->remote_app) + xf_cliprdr_set_selection_owner(xfc, clipboard, CurrentTime); + else + xf_cliprdr_prepare_to_set_selection_owner(xfc, clipboard); + +out: + xf_unlock_x11(xfc); + + return ret; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +xf_cliprdr_server_format_list_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(formatListResponse); + // xfClipboard* clipboard = (xfClipboard*) context->custom; + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +xf_cliprdr_server_format_data_request(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest) +{ + BOOL rawTransfer = 0; + const xfCliprdrFormat* format = NULL; + UINT32 formatId = 0; + xfContext* xfc = NULL; + xfClipboard* clipboard = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(formatDataRequest); + + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + formatId = formatDataRequest->requestedFormatId; + + rawTransfer = xf_cliprdr_is_raw_transfer_available(clipboard); + + if (rawTransfer) + { + format = xf_cliprdr_get_client_format_by_id(clipboard, CF_RAW); + LogTagAndXChangeProperty(TAG, xfc->display, xfc->drawable, clipboard->property_atom, + XA_INTEGER, 32, PropModeReplace, (BYTE*)&formatId, 1); + } + else + format = xf_cliprdr_get_client_format_by_id(clipboard, formatId); + + clipboard->requestedFormatId = rawTransfer ? CF_RAW : WINPR_ASSERTING_INT_CAST(int, formatId); + if (!format) + return xf_cliprdr_send_data_response(clipboard, format, NULL, 0); + + DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 "} [%s]", + format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest), + format->localFormat, format->formatName); + LogTagAndXConvertSelection(TAG, xfc->display, clipboard->clipboard_atom, format->atom, + clipboard->property_atom, xfc->drawable, CurrentTime); + XFlush(xfc->display); + /* After this point, we expect a SelectionNotify event from the clipboard owner. */ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT +xf_cliprdr_server_format_data_response(CliprdrClientContext* context, + const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse) +{ + BOOL bSuccess = 0; + BYTE* pDstData = NULL; + UINT32 DstSize = 0; + UINT32 SrcSize = 0; + UINT32 srcFormatId = 0; + UINT32 dstFormatId = 0; + BOOL nullTerminated = FALSE; + UINT32 size = 0; + const BYTE* data = NULL; + xfContext* xfc = NULL; + xfClipboard* clipboard = NULL; + xfCachedData* cached_data = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(formatDataResponse); + + clipboard = cliprdr_file_context_get_context(context->custom); + WINPR_ASSERT(clipboard); + + xfc = clipboard->xfc; + WINPR_ASSERT(xfc); + + size = formatDataResponse->common.dataLen; + data = formatDataResponse->requestedFormatData; + + if (formatDataResponse->common.msgFlags == CB_RESPONSE_FAIL) + { + WLog_WARN(TAG, "Format Data Response PDU msgFlags is CB_RESPONSE_FAIL"); + free(clipboard->respond); + clipboard->respond = NULL; + return CHANNEL_RC_OK; + } + + if (!clipboard->respond) + return CHANNEL_RC_OK; + + pDstData = NULL; + DstSize = 0; + srcFormatId = 0; + dstFormatId = 0; + + const RequestedFormat* format = clipboard->requestedFormat; + if (clipboard->data_raw_format) + { + srcFormatId = CF_RAW; + dstFormatId = CF_RAW; + } + else if (!format) + return ERROR_INTERNAL_ERROR; + else if (format->formatName) + { + ClipboardLock(clipboard->system); + if (strcmp(format->formatName, type_HtmlFormat) == 0) + { + srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat); + dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html); + nullTerminated = TRUE; + } + + if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0) + { + if (!cliprdr_file_context_update_server_data(clipboard->file, clipboard->system, data, + size)) + WLog_WARN(TAG, "failed to update file descriptors"); + + srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + const xfCliprdrFormat* dstTargetFormat = + xf_cliprdr_get_client_format_by_atom(clipboard, clipboard->respond->target); + if (!dstTargetFormat) + { + dstFormatId = ClipboardGetFormatId(clipboard->system, mime_uri_list); + } + else + { + dstFormatId = dstTargetFormat->localFormat; + } + + nullTerminated = TRUE; + } + ClipboardUnlock(clipboard->system); + } + else + { + srcFormatId = format->formatToRequest; + dstFormatId = format->localFormat; + switch (format->formatToRequest) + { + case CF_TEXT: + nullTerminated = TRUE; + break; + + case CF_OEMTEXT: + nullTerminated = TRUE; + break; + + case CF_UNICODETEXT: + nullTerminated = TRUE; + break; + + case CF_DIB: + srcFormatId = CF_DIB; + break; + + case CF_TIFF: + srcFormatId = CF_TIFF; + break; + + default: + break; + } + } + + DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 "} [%s]", + format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest), + format->localFormat, format->formatName); + SrcSize = size; + + DEBUG_CLIPRDR("srcFormatId: %u, dstFormatId: %u", srcFormatId, dstFormatId); + + ClipboardLock(clipboard->system); + bSuccess = ClipboardSetData(clipboard->system, srcFormatId, data, SrcSize); + + BOOL willQuit = FALSE; + if (bSuccess) + { + if (SrcSize == 0) + { + WLog_DBG(TAG, "skipping, empty data detected!"); + free(clipboard->respond); + clipboard->respond = NULL; + willQuit = TRUE; + } + else + { + pDstData = (BYTE*)ClipboardGetData(clipboard->system, dstFormatId, &DstSize); + + if (!pDstData) + { + WLog_WARN(TAG, "failed to get clipboard data in format %s [source format %s]", + ClipboardGetFormatName(clipboard->system, dstFormatId), + ClipboardGetFormatName(clipboard->system, srcFormatId)); + } + + if (nullTerminated && pDstData) + { + BYTE* nullTerminator = memchr(pDstData, '\0', DstSize); + if (nullTerminator) + { + const intptr_t diff = nullTerminator - pDstData; + WINPR_ASSERT(diff >= 0); + WINPR_ASSERT(diff <= UINT32_MAX); + DstSize = (UINT32)diff; + } + } + } + } + ClipboardUnlock(clipboard->system); + if (willQuit) + return CHANNEL_RC_OK; + + /* Cache converted and original data to avoid doing a possibly costly + * conversion again on subsequent requests */ + if (pDstData) + { + cached_data = xf_cached_data_new(pDstData, DstSize); + if (!cached_data) + { + WLog_WARN(TAG, "Failed to allocate cache entry"); + free(pDstData); + return CHANNEL_RC_OK; + } + if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId), + cached_data)) + { + WLog_WARN(TAG, "Failed to cache clipboard data"); + xf_cached_data_free(cached_data); + return CHANNEL_RC_OK; + } + } + + /* We have to copy the original data again, as pSrcData is now owned + * by clipboard->system. Memory allocation failure is not fatal here + * as this is only a cached value. */ + { + // clipboard->cachedData owns cached_data + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc + xfCachedData* cached_raw_data = xf_cached_data_new_copy(data, size); + if (!cached_raw_data) + WLog_WARN(TAG, "Failed to allocate cache entry"); + else + { + if (!HashTable_Insert(clipboard->cachedRawData, (void*)(UINT_PTR)srcFormatId, + cached_raw_data)) + { + WLog_WARN(TAG, "Failed to cache clipboard data"); + xf_cached_data_free(cached_raw_data); + } + } + } + + // clipboard->cachedRawData owns cached_raw_data + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + xf_cliprdr_provide_data(clipboard, clipboard->respond, pDstData, DstSize); + { + union + { + XEvent* ev; + XSelectionEvent* sev; + } conv; + + conv.sev = clipboard->respond; + + XSendEvent(xfc->display, clipboard->respond->requestor, 0, 0, conv.ev); + XFlush(xfc->display); + } + free(clipboard->respond); + clipboard->respond = NULL; + return CHANNEL_RC_OK; +} + +static BOOL xf_cliprdr_is_valid_unix_filename(LPCWSTR filename) +{ + if (!filename) + return FALSE; + + if (filename[0] == L'\0') + return FALSE; + + /* Reserved characters */ + for (const WCHAR* c = filename; *c; ++c) + { + if (*c == L'/') + return FALSE; + } + + return TRUE; +} + +xfClipboard* xf_clipboard_new(xfContext* xfc, BOOL relieveFilenameRestriction) +{ + int n = 0; + rdpChannels* channels = NULL; + xfClipboard* clipboard = NULL; + const char* selectionAtom = NULL; + xfCliprdrFormat* clientFormat = NULL; + wObject* obj = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->common.context.settings); + + if (!(clipboard = (xfClipboard*)calloc(1, sizeof(xfClipboard)))) + { + WLog_ERR(TAG, "failed to allocate xfClipboard data"); + return NULL; + } + + clipboard->file = cliprdr_file_context_new(clipboard); + if (!clipboard->file) + goto fail; + + xfc->clipboard = clipboard; + clipboard->xfc = xfc; + channels = xfc->common.context.channels; + clipboard->channels = channels; + clipboard->system = ClipboardCreate(); + clipboard->requestedFormatId = -1; + clipboard->root_window = DefaultRootWindow(xfc->display); + + selectionAtom = + freerdp_settings_get_string(xfc->common.context.settings, FreeRDP_ClipboardUseSelection); + if (!selectionAtom) + selectionAtom = "CLIPBOARD"; + + clipboard->clipboard_atom = Logging_XInternAtom(xfc->log, xfc->display, selectionAtom, FALSE); + + if (clipboard->clipboard_atom == None) + { + WLog_ERR(TAG, "unable to get %s atom", selectionAtom); + goto fail; + } + + clipboard->timestamp_property_atom = + Logging_XInternAtom(xfc->log, xfc->display, "_FREERDP_TIMESTAMP_PROPERTY", FALSE); + clipboard->property_atom = + Logging_XInternAtom(xfc->log, xfc->display, "_FREERDP_CLIPRDR", FALSE); + clipboard->raw_transfer_atom = + Logging_XInternAtom(xfc->log, xfc->display, "_FREERDP_CLIPRDR_RAW", FALSE); + clipboard->raw_format_list_atom = + Logging_XInternAtom(xfc->log, xfc->display, "_FREERDP_CLIPRDR_FORMATS", FALSE); + xf_cliprdr_set_raw_transfer_enabled(clipboard, TRUE); + XSelectInput(xfc->display, clipboard->root_window, PropertyChangeMask); +#ifdef WITH_XFIXES + + if (XFixesQueryExtension(xfc->display, &clipboard->xfixes_event_base, + &clipboard->xfixes_error_base)) + { + int xfmajor = 0; + int xfminor = 0; + + if (XFixesQueryVersion(xfc->display, &xfmajor, &xfminor)) + { + XFixesSelectSelectionInput(xfc->display, clipboard->root_window, + clipboard->clipboard_atom, + XFixesSetSelectionOwnerNotifyMask); + clipboard->xfixes_supported = TRUE; + } + else + { + WLog_ERR(TAG, "Error querying X Fixes extension version"); + } + } + else + { + WLog_ERR(TAG, "Error loading X Fixes extension"); + } + +#else + WLog_ERR( + TAG, + "Warning: Using clipboard redirection without XFIXES extension is strongly discouraged!"); +#endif + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, "_FREERDP_RAW", False); + clientFormat->localFormat = clientFormat->formatToRequest = CF_RAW; + + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, "UTF8_STRING", False); + clientFormat->formatToRequest = CF_UNICODETEXT; + clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain); + + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->atom = XA_STRING; + clientFormat->formatToRequest = CF_TEXT; + clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain); + + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, mime_tiff, False); + clientFormat->formatToRequest = clientFormat->localFormat = CF_TIFF; + + for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++) + { + const char* mime_bmp = mime_bitmap[x]; + const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp); + if (format == 0) + { + WLog_DBG(TAG, "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp); + continue; + } + + WLog_DBG(TAG, "register local bitmap format %s [0x%08" PRIx32 "]", mime_bmp, format); + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->localFormat = format; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, mime_bmp, False); + clientFormat->formatToRequest = CF_DIB; + } + + for (size_t x = 0; x < ARRAYSIZE(mime_images); x++) + { + const char* mime_bmp = mime_images[x]; + const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp); + if (format == 0) + { + WLog_DBG(TAG, "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp); + continue; + } + + WLog_DBG(TAG, "register local bitmap format %s [0x%08" PRIx32 "]", mime_bmp, format); + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->localFormat = format; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, mime_bmp, False); + clientFormat->formatToRequest = CF_DIB; + } + + clientFormat = &clipboard->clientFormats[n++]; + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, mime_html, False); + clientFormat->formatToRequest = ClipboardGetFormatId(xfc->clipboard->system, type_HtmlFormat); + clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_html); + clientFormat->formatName = _strdup(type_HtmlFormat); + + if (!clientFormat->formatName) + goto fail; + + clientFormat = &clipboard->clientFormats[n++]; + + /* + * Existence of registered format IDs for file formats does not guarantee that they are + * in fact supported by wClipboard (as further initialization may have failed after format + * registration). However, they are definitely not supported if there are no registered + * formats. In this case we should not list file formats in TARGETS. + */ + const UINT32 fgid = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW); + const UINT32 uid = ClipboardGetFormatId(clipboard->system, mime_uri_list); + if (uid) + { + cliprdr_file_context_set_locally_available(clipboard->file, TRUE); + clientFormat->atom = Logging_XInternAtom(xfc->log, xfc->display, mime_uri_list, False); + clientFormat->localFormat = uid; + clientFormat->formatToRequest = fgid; + clientFormat->formatName = _strdup(type_FileGroupDescriptorW); + + if (!clientFormat->formatName) + goto fail; + + clientFormat = &clipboard->clientFormats[n++]; + } + + const UINT32 gid = ClipboardGetFormatId(clipboard->system, mime_gnome_copied_files); + if (gid != 0) + { + cliprdr_file_context_set_locally_available(clipboard->file, TRUE); + clientFormat->atom = + Logging_XInternAtom(xfc->log, xfc->display, mime_gnome_copied_files, False); + clientFormat->localFormat = gid; + clientFormat->formatToRequest = fgid; + clientFormat->formatName = _strdup(type_FileGroupDescriptorW); + + if (!clientFormat->formatName) + goto fail; + + clientFormat = &clipboard->clientFormats[n++]; + } + + const UINT32 mid = ClipboardGetFormatId(clipboard->system, mime_mate_copied_files); + if (mid != 0) + { + cliprdr_file_context_set_locally_available(clipboard->file, TRUE); + clientFormat->atom = + Logging_XInternAtom(xfc->log, xfc->display, mime_mate_copied_files, False); + clientFormat->localFormat = mid; + clientFormat->formatToRequest = fgid; + clientFormat->formatName = _strdup(type_FileGroupDescriptorW); + + if (!clientFormat->formatName) + goto fail; + } + + clipboard->numClientFormats = WINPR_ASSERTING_INT_CAST(uint32_t, n); + clipboard->targets[0] = Logging_XInternAtom(xfc->log, xfc->display, "TIMESTAMP", FALSE); + clipboard->targets[1] = Logging_XInternAtom(xfc->log, xfc->display, "TARGETS", FALSE); + clipboard->numTargets = 2; + clipboard->incr_atom = Logging_XInternAtom(xfc->log, xfc->display, "INCR", FALSE); + + if (relieveFilenameRestriction) + { + WLog_DBG(TAG, "Relieving CLIPRDR filename restriction"); + ClipboardGetDelegate(clipboard->system)->IsFileNameComponentValid = + xf_cliprdr_is_valid_unix_filename; + } + + clipboard->cachedData = HashTable_New(TRUE); + if (!clipboard->cachedData) + goto fail; + + obj = HashTable_ValueObject(clipboard->cachedData); + obj->fnObjectFree = xf_cached_data_free; + + clipboard->cachedRawData = HashTable_New(TRUE); + if (!clipboard->cachedRawData) + goto fail; + + obj = HashTable_ValueObject(clipboard->cachedRawData); + obj->fnObjectFree = xf_cached_data_free; + + return clipboard; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + xf_clipboard_free(clipboard); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +void xf_clipboard_free(xfClipboard* clipboard) +{ + if (!clipboard) + return; + + xf_clipboard_free_server_formats(clipboard); + + if (clipboard->numClientFormats) + { + for (UINT32 i = 0; i < clipboard->numClientFormats; i++) + { + xfCliprdrFormat* format = &clipboard->clientFormats[i]; + free(format->formatName); + } + } + + cliprdr_file_context_free(clipboard->file); + + ClipboardDestroy(clipboard->system); + xf_clipboard_formats_free(clipboard); + HashTable_Free(clipboard->cachedRawData); + HashTable_Free(clipboard->cachedData); + requested_format_free(&clipboard->requestedFormat); + free(clipboard->respond); + free(clipboard->incr_data); + free(clipboard); +} + +void xf_cliprdr_init(xfContext* xfc, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(cliprdr); + + xfc->cliprdr = cliprdr; + xfc->clipboard->context = cliprdr; + + cliprdr->MonitorReady = xf_cliprdr_monitor_ready; + cliprdr->ServerCapabilities = xf_cliprdr_server_capabilities; + cliprdr->ServerFormatList = xf_cliprdr_server_format_list; + cliprdr->ServerFormatListResponse = xf_cliprdr_server_format_list_response; + cliprdr->ServerFormatDataRequest = xf_cliprdr_server_format_data_request; + cliprdr->ServerFormatDataResponse = xf_cliprdr_server_format_data_response; + + cliprdr_file_context_init(xfc->clipboard->file, cliprdr); +} + +void xf_cliprdr_uninit(xfContext* xfc, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(cliprdr); + + xfc->cliprdr = NULL; + + if (xfc->clipboard) + { + cliprdr_file_context_uninit(xfc->clipboard->file, cliprdr); + xfc->clipboard->context = NULL; + } +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.h new file mode 100644 index 0000000000000000000000000000000000000000..33d75c822269fb067f3e059618acab68fb3e286c --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_cliprdr.h @@ -0,0 +1,38 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Clipboard Redirection + * + * Copyright 2010-2011 Vic Lee + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_CLIPRDR_H +#define FREERDP_CLIENT_X11_CLIPRDR_H + +#include "xf_client.h" +#include "xfreerdp.h" + +#include + +void xf_clipboard_free(xfClipboard* clipboard); + +WINPR_ATTR_MALLOC(xf_clipboard_free, 1) +xfClipboard* xf_clipboard_new(xfContext* xfc, BOOL relieveFilenameRestriction); + +void xf_cliprdr_init(xfContext* xfc, CliprdrClientContext* cliprdr); +void xf_cliprdr_uninit(xfContext* xfc, CliprdrClientContext* cliprdr); + +void xf_cliprdr_handle_xevent(xfContext* xfc, const XEvent* event); + +#endif /* FREERDP_CLIENT_X11_CLIPRDR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.c new file mode 100644 index 0000000000000000000000000000000000000000..28223a543cb9e8191a3ff40c70c00cb4f0224679 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.c @@ -0,0 +1,555 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Display Control channel + * + * Copyright 2017 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#ifdef WITH_XRANDR +#include +#include + +#if (RANDR_MAJOR * 100 + RANDR_MINOR) >= 105 +#define USABLE_XRANDR +#endif + +#endif + +#include "xf_disp.h" +#include "xf_monitor.h" + +#include +#define TAG CLIENT_TAG("x11disp") +#define RESIZE_MIN_DELAY 200 /* minimum delay in ms between two resizes */ + +struct s_xfDispContext +{ + xfContext* xfc; + DispClientContext* disp; + BOOL haveXRandr; + int eventBase; + int errorBase; + UINT32 lastSentWidth; + UINT32 lastSentHeight; + BYTE reserved[4]; + UINT64 lastSentDate; + UINT32 targetWidth; + UINT32 targetHeight; + BOOL activated; + BOOL fullscreen; + UINT16 lastSentDesktopOrientation; + BYTE reserved2[2]; + UINT32 lastSentDesktopScaleFactor; + UINT32 lastSentDeviceScaleFactor; + BYTE reserved3[4]; +}; + +static UINT xf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, + UINT32 nmonitors); + +static BOOL xf_disp_settings_changed(xfDispContext* xfDisp) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfDisp); + WINPR_ASSERT(xfDisp->xfc); + + settings = xfDisp->xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (xfDisp->lastSentWidth != xfDisp->targetWidth) + return TRUE; + + if (xfDisp->lastSentHeight != xfDisp->targetHeight) + return TRUE; + + if (xfDisp->lastSentDesktopOrientation != + freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation)) + return TRUE; + + if (xfDisp->lastSentDesktopScaleFactor != + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor)) + return TRUE; + + if (xfDisp->lastSentDeviceScaleFactor != + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor)) + return TRUE; + + if (xfDisp->fullscreen != xfDisp->xfc->fullscreen) + return TRUE; + + return FALSE; +} + +static BOOL xf_update_last_sent(xfDispContext* xfDisp) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfDisp); + WINPR_ASSERT(xfDisp->xfc); + + settings = xfDisp->xfc->common.context.settings; + WINPR_ASSERT(settings); + + xfDisp->lastSentWidth = xfDisp->targetWidth; + xfDisp->lastSentHeight = xfDisp->targetHeight; + xfDisp->lastSentDesktopOrientation = + freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation); + xfDisp->lastSentDesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + xfDisp->lastSentDeviceScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + xfDisp->fullscreen = xfDisp->xfc->fullscreen; + return TRUE; +} + +static BOOL xf_disp_sendResize(xfDispContext* xfDisp) +{ + DISPLAY_CONTROL_MONITOR_LAYOUT layout = { 0 }; + xfContext* xfc = NULL; + rdpSettings* settings = NULL; + + if (!xfDisp || !xfDisp->xfc) + return FALSE; + + xfc = xfDisp->xfc; + settings = xfc->common.context.settings; + + if (!settings) + return FALSE; + + if (!xfDisp->activated || !xfDisp->disp) + return TRUE; + + if (GetTickCount64() - xfDisp->lastSentDate < RESIZE_MIN_DELAY) + return TRUE; + + if (!xf_disp_settings_changed(xfDisp)) + return TRUE; + + xfDisp->lastSentDate = GetTickCount64(); + + const UINT32 mcount = freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); + if (xfc->fullscreen && (mcount > 0)) + { + const rdpMonitor* monitors = + freerdp_settings_get_pointer(settings, FreeRDP_MonitorDefArray); + if (xf_disp_sendLayout(xfDisp->disp, monitors, mcount) != CHANNEL_RC_OK) + return FALSE; + } + else + { + layout.Flags = DISPLAY_CONTROL_MONITOR_PRIMARY; + layout.Top = layout.Left = 0; + layout.Width = xfDisp->targetWidth; + layout.Height = xfDisp->targetHeight; + layout.Orientation = freerdp_settings_get_uint16(settings, FreeRDP_DesktopOrientation); + layout.DesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + layout.DeviceScaleFactor = freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + + const double dw = xfDisp->targetWidth / 75.0 * 25.4; + const double dh = xfDisp->targetHeight / 75.0 * 25.4; + layout.PhysicalWidth = (UINT32)lround(dw); + layout.PhysicalHeight = (UINT32)lround(dh); + + if (IFCALLRESULT(CHANNEL_RC_OK, xfDisp->disp->SendMonitorLayout, xfDisp->disp, 1, + &layout) != CHANNEL_RC_OK) + return FALSE; + } + + return xf_update_last_sent(xfDisp); +} + +static BOOL xf_disp_queueResize(xfDispContext* xfDisp, UINT32 width, UINT32 height) +{ + if ((xfDisp->targetWidth == (INT64)width) && (xfDisp->targetHeight == (INT64)height)) + return TRUE; + xfDisp->targetWidth = width; + xfDisp->targetHeight = height; + xfDisp->lastSentDate = GetTickCount64(); + return xf_disp_sendResize(xfDisp); +} + +static BOOL xf_disp_set_window_resizable(xfDispContext* xfDisp) +{ + XSizeHints* size_hints = NULL; + + if (!(size_hints = XAllocSizeHints())) + return FALSE; + + size_hints->flags = PMinSize | PMaxSize | PWinGravity; + size_hints->win_gravity = NorthWestGravity; + size_hints->min_width = size_hints->min_height = 320; + size_hints->max_width = size_hints->max_height = 8192; + + if (xfDisp->xfc->window) + XSetWMNormalHints(xfDisp->xfc->display, xfDisp->xfc->window->handle, size_hints); + + XFree(size_hints); + return TRUE; +} + +static BOOL xf_disp_check_context(void* context, xfContext** ppXfc, xfDispContext** ppXfDisp, + rdpSettings** ppSettings) +{ + xfContext* xfc = NULL; + + if (!context) + return FALSE; + + xfc = (xfContext*)context; + + if (!(xfc->xfDisp)) + return FALSE; + + if (!xfc->common.context.settings) + return FALSE; + + *ppXfc = xfc; + *ppXfDisp = xfc->xfDisp; + *ppSettings = xfc->common.context.settings; + return TRUE; +} + +static void xf_disp_OnActivated(void* context, const ActivatedEventArgs* e) +{ + xfContext* xfc = NULL; + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + + if (!xf_disp_check_context(context, &xfc, &xfDisp, &settings)) + return; + + if (xfDisp->activated && !xfc->fullscreen) + { + xf_disp_set_window_resizable(xfDisp); + + if (e->firstActivation) + return; + + xf_disp_sendResize(xfDisp); + } +} + +static void xf_disp_OnGraphicsReset(void* context, const GraphicsResetEventArgs* e) +{ + xfContext* xfc = NULL; + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(e); + + if (!xf_disp_check_context(context, &xfc, &xfDisp, &settings)) + return; + + if (xfDisp->activated && !freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + xf_disp_set_window_resizable(xfDisp); + xf_disp_sendResize(xfDisp); + } +} + +static void xf_disp_OnTimer(void* context, const TimerEventArgs* e) +{ + xfContext* xfc = NULL; + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(e); + + if (!xf_disp_check_context(context, &xfc, &xfDisp, &settings)) + return; + + if (!xfDisp->activated || xfc->fullscreen) + return; + + xf_disp_sendResize(xfDisp); +} + +static void xf_disp_OnWindowStateChange(void* context, const WindowStateChangeEventArgs* e) +{ + xfContext* xfc = NULL; + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_UNUSED(e); + + if (!xf_disp_check_context(context, &xfc, &xfDisp, &settings)) + return; + + if (!xfDisp->activated || !xfc->fullscreen) + return; + + xf_disp_sendResize(xfDisp); +} + +xfDispContext* xf_disp_new(xfContext* xfc) +{ + xfDispContext* ret = NULL; + const rdpSettings* settings = NULL; + wPubSub* pubSub = NULL; + + WINPR_ASSERT(xfc); + + pubSub = xfc->common.context.pubSub; + WINPR_ASSERT(pubSub); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + ret = calloc(1, sizeof(xfDispContext)); + + if (!ret) + return NULL; + + ret->xfc = xfc; +#ifdef USABLE_XRANDR + + if (XRRQueryExtension(xfc->display, &ret->eventBase, &ret->errorBase)) + { + ret->haveXRandr = TRUE; + } + +#endif + ret->lastSentWidth = ret->targetWidth = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + ret->lastSentHeight = ret->targetHeight = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + PubSub_SubscribeActivated(pubSub, xf_disp_OnActivated); + PubSub_SubscribeGraphicsReset(pubSub, xf_disp_OnGraphicsReset); + PubSub_SubscribeTimer(pubSub, xf_disp_OnTimer); + PubSub_SubscribeWindowStateChange(pubSub, xf_disp_OnWindowStateChange); + return ret; +} + +void xf_disp_free(xfDispContext* disp) +{ + if (!disp) + return; + + if (disp->xfc) + { + wPubSub* pubSub = disp->xfc->common.context.pubSub; + PubSub_UnsubscribeActivated(pubSub, xf_disp_OnActivated); + PubSub_UnsubscribeGraphicsReset(pubSub, xf_disp_OnGraphicsReset); + PubSub_UnsubscribeTimer(pubSub, xf_disp_OnTimer); + PubSub_UnsubscribeWindowStateChange(pubSub, xf_disp_OnWindowStateChange); + } + + free(disp); +} + +UINT xf_disp_sendLayout(DispClientContext* disp, const rdpMonitor* monitors, UINT32 nmonitors) +{ + UINT ret = CHANNEL_RC_OK; + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + DISPLAY_CONTROL_MONITOR_LAYOUT* layouts = NULL; + + WINPR_ASSERT(disp); + WINPR_ASSERT(monitors); + WINPR_ASSERT(nmonitors > 0); + + xfDisp = (xfDispContext*)disp->custom; + WINPR_ASSERT(xfDisp); + WINPR_ASSERT(xfDisp->xfc); + + settings = xfDisp->xfc->common.context.settings; + WINPR_ASSERT(settings); + + layouts = calloc(nmonitors, sizeof(DISPLAY_CONTROL_MONITOR_LAYOUT)); + + if (!layouts) + return CHANNEL_RC_NO_MEMORY; + + for (UINT32 i = 0; i < nmonitors; i++) + { + const rdpMonitor* monitor = &monitors[i]; + DISPLAY_CONTROL_MONITOR_LAYOUT* layout = &layouts[i]; + + layout->Flags = (monitor->is_primary ? DISPLAY_CONTROL_MONITOR_PRIMARY : 0); + layout->Left = monitor->x; + layout->Top = monitor->y; + layout->Width = WINPR_ASSERTING_INT_CAST(uint32_t, monitor->width); + layout->Height = WINPR_ASSERTING_INT_CAST(uint32_t, monitor->height); + layout->Orientation = ORIENTATION_LANDSCAPE; + layout->PhysicalWidth = monitor->attributes.physicalWidth; + layout->PhysicalHeight = monitor->attributes.physicalHeight; + + switch (monitor->attributes.orientation) + { + case 90: + layout->Orientation = ORIENTATION_PORTRAIT; + break; + + case 180: + layout->Orientation = ORIENTATION_LANDSCAPE_FLIPPED; + break; + + case 270: + layout->Orientation = ORIENTATION_PORTRAIT_FLIPPED; + break; + + case 0: + default: + /* MS-RDPEDISP - 2.2.2.2.1: + * Orientation (4 bytes): A 32-bit unsigned integer that specifies the + * orientation of the monitor in degrees. Valid values are 0, 90, 180 + * or 270 + * + * So we default to ORIENTATION_LANDSCAPE + */ + layout->Orientation = ORIENTATION_LANDSCAPE; + break; + } + + layout->DesktopScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DesktopScaleFactor); + layout->DeviceScaleFactor = + freerdp_settings_get_uint32(settings, FreeRDP_DeviceScaleFactor); + } + + ret = IFCALLRESULT(CHANNEL_RC_OK, disp->SendMonitorLayout, disp, nmonitors, layouts); + free(layouts); + return ret; +} + +BOOL xf_disp_handle_xevent(xfContext* xfc, const XEvent* event) +{ + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + UINT32 maxWidth = 0; + UINT32 maxHeight = 0; + + if (!xfc || !event) + return FALSE; + + xfDisp = xfc->xfDisp; + + if (!xfDisp) + return FALSE; + + settings = xfc->common.context.settings; + + if (!settings) + return FALSE; + + if (!xfDisp->haveXRandr || !xfDisp->disp) + return TRUE; + +#ifdef USABLE_XRANDR + + if (event->type != xfDisp->eventBase + RRScreenChangeNotify) + return TRUE; + +#endif + xf_detect_monitors(xfc, &maxWidth, &maxHeight); + const rdpMonitor* monitors = freerdp_settings_get_pointer(settings, FreeRDP_MonitorDefArray); + const UINT32 mcount = freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); + return xf_disp_sendLayout(xfDisp->disp, monitors, mcount) == CHANNEL_RC_OK; +} + +BOOL xf_disp_handle_configureNotify(xfContext* xfc, int width, int height) +{ + xfDispContext* xfDisp = NULL; + + if (!xfc) + return FALSE; + + xfDisp = xfc->xfDisp; + + if (!xfDisp) + return FALSE; + + return xf_disp_queueResize(xfDisp, WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, height)); +} + +static UINT xf_DisplayControlCaps(DispClientContext* disp, UINT32 maxNumMonitors, + UINT32 maxMonitorAreaFactorA, UINT32 maxMonitorAreaFactorB) +{ + /* we're called only if dynamic resolution update is activated */ + xfDispContext* xfDisp = NULL; + rdpSettings* settings = NULL; + + WINPR_ASSERT(disp); + + xfDisp = (xfDispContext*)disp->custom; + WINPR_ASSERT(xfDisp); + WINPR_ASSERT(xfDisp->xfc); + + settings = xfDisp->xfc->common.context.settings; + WINPR_ASSERT(settings); + + WLog_DBG(TAG, + "DisplayControlCapsPdu: MaxNumMonitors: %" PRIu32 " MaxMonitorAreaFactorA: %" PRIu32 + " MaxMonitorAreaFactorB: %" PRIu32 "", + maxNumMonitors, maxMonitorAreaFactorA, maxMonitorAreaFactorB); + xfDisp->activated = TRUE; + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + return CHANNEL_RC_OK; + + WLog_DBG(TAG, "DisplayControlCapsPdu: setting the window as resizable"); + return xf_disp_set_window_resizable(xfDisp) ? CHANNEL_RC_OK : CHANNEL_RC_NO_MEMORY; +} + +BOOL xf_disp_init(xfDispContext* xfDisp, DispClientContext* disp) +{ + rdpSettings* settings = NULL; + + if (!xfDisp || !xfDisp->xfc || !disp) + return FALSE; + + settings = xfDisp->xfc->common.context.settings; + + if (!settings) + return FALSE; + + xfDisp->disp = disp; + disp->custom = (void*)xfDisp; + + if (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) + { + disp->DisplayControlCaps = xf_DisplayControlCaps; +#ifdef USABLE_XRANDR + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + /* ask X11 to notify us of screen changes */ + XRRSelectInput(xfDisp->xfc->display, DefaultRootWindow(xfDisp->xfc->display), + RRScreenChangeNotifyMask); + } + +#endif + } + + return TRUE; +} + +BOOL xf_disp_uninit(xfDispContext* xfDisp, DispClientContext* disp) +{ + if (!xfDisp || !disp) + return FALSE; + + xfDisp->disp = NULL; + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.h new file mode 100644 index 0000000000000000000000000000000000000000..c3c87926a0c0f45ee4f5c6749526a4a3b4ba5401 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_disp.h @@ -0,0 +1,40 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Display Control channel + * + * Copyright 2017 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef FREERDP_CLIENT_X11_DISP_H +#define FREERDP_CLIENT_X11_DISP_H + +#include +#include + +#include "xf_client.h" +#include "xfreerdp.h" + +FREERDP_API BOOL xf_disp_init(xfDispContext* xfDisp, DispClientContext* disp); +FREERDP_API BOOL xf_disp_uninit(xfDispContext* xfDisp, DispClientContext* disp); + +void xf_disp_free(xfDispContext* disp); + +WINPR_ATTR_MALLOC(xf_disp_free, 1) +xfDispContext* xf_disp_new(xfContext* xfc); + +BOOL xf_disp_handle_xevent(xfContext* xfc, const XEvent* event); +BOOL xf_disp_handle_configureNotify(xfContext* xfc, int width, int height); +void xf_disp_resized(xfDispContext* disp); + +#endif /* FREERDP_CLIENT_X11_DISP_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.c new file mode 100644 index 0000000000000000000000000000000000000000..fdd927ff945582cb352c7956d96e508c07c3f23f --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.c @@ -0,0 +1,1383 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Event Handling + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2023 HP Development Company, L.P. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include "xf_rail.h" +#include "xf_window.h" +#include "xf_cliprdr.h" +#include "xf_disp.h" +#include "xf_input.h" +#include "xf_gfx.h" +#include "xf_graphics.h" +#include "xf_utils.h" + +#include "xf_event.h" + +#define TAG CLIENT_TAG("x11") + +#define CLAMP_COORDINATES(x, y) \ + do \ + { \ + if ((x) < 0) \ + (x) = 0; \ + if ((y) < 0) \ + (y) = 0; \ + } while (0) + +const char* x11_event_string(int event) +{ + switch (event) + { + case KeyPress: + return "KeyPress"; + + case KeyRelease: + return "KeyRelease"; + + case ButtonPress: + return "ButtonPress"; + + case ButtonRelease: + return "ButtonRelease"; + + case MotionNotify: + return "MotionNotify"; + + case EnterNotify: + return "EnterNotify"; + + case LeaveNotify: + return "LeaveNotify"; + + case FocusIn: + return "FocusIn"; + + case FocusOut: + return "FocusOut"; + + case KeymapNotify: + return "KeymapNotify"; + + case Expose: + return "Expose"; + + case GraphicsExpose: + return "GraphicsExpose"; + + case NoExpose: + return "NoExpose"; + + case VisibilityNotify: + return "VisibilityNotify"; + + case CreateNotify: + return "CreateNotify"; + + case DestroyNotify: + return "DestroyNotify"; + + case UnmapNotify: + return "UnmapNotify"; + + case MapNotify: + return "MapNotify"; + + case MapRequest: + return "MapRequest"; + + case ReparentNotify: + return "ReparentNotify"; + + case ConfigureNotify: + return "ConfigureNotify"; + + case ConfigureRequest: + return "ConfigureRequest"; + + case GravityNotify: + return "GravityNotify"; + + case ResizeRequest: + return "ResizeRequest"; + + case CirculateNotify: + return "CirculateNotify"; + + case CirculateRequest: + return "CirculateRequest"; + + case PropertyNotify: + return "PropertyNotify"; + + case SelectionClear: + return "SelectionClear"; + + case SelectionRequest: + return "SelectionRequest"; + + case SelectionNotify: + return "SelectionNotify"; + + case ColormapNotify: + return "ColormapNotify"; + + case ClientMessage: + return "ClientMessage"; + + case MappingNotify: + return "MappingNotify"; + + case GenericEvent: + return "GenericEvent"; + + default: + return "UNKNOWN"; + } +} + +#ifdef WITH_DEBUG_X11 +#define DEBUG_X11(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_X11(...) \ + do \ + { \ + } while (0) +#endif + +static BOOL xf_action_script_append(xfContext* xfc, const char* buffer, size_t size, void* user, + const char* what, const char* arg) +{ + WINPR_ASSERT(xfc); + WINPR_UNUSED(what); + WINPR_UNUSED(arg); + + if (buffer || (size == 0)) + return TRUE; + + if (!ArrayList_Append(xfc->xevents, buffer)) + { + ArrayList_Clear(xfc->xevents); + return FALSE; + } + return TRUE; +} + +BOOL xf_event_action_script_init(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + xf_event_action_script_free(xfc); + + xfc->xevents = ArrayList_New(TRUE); + + if (!xfc->xevents) + return FALSE; + + wObject* obj = ArrayList_Object(xfc->xevents); + WINPR_ASSERT(obj); + obj->fnObjectNew = winpr_ObjectStringClone; + obj->fnObjectFree = winpr_ObjectStringFree; + + if (!run_action_script(xfc, "xevent", NULL, xf_action_script_append, NULL)) + return FALSE; + + return TRUE; +} + +void xf_event_action_script_free(xfContext* xfc) +{ + if (xfc->xevents) + { + ArrayList_Free(xfc->xevents); + xfc->xevents = NULL; + } +} + +static BOOL action_script_run(xfContext* xfc, const char* buffer, size_t size, void* user, + const char* what, const char* arg) +{ + WINPR_UNUSED(xfc); + WINPR_UNUSED(what); + WINPR_UNUSED(arg); + WINPR_ASSERT(user); + int* pstatus = user; + + if (size == 0) + { + WLog_WARN(TAG, "ActionScript xevent: script did not return data"); + return FALSE; + } + + if (winpr_PathFileExists(buffer)) + { + char* cmd = NULL; + size_t cmdlen = 0; + winpr_asprintf(&cmd, &cmdlen, "%s %s %s", buffer, what, arg); + if (!cmd) + return FALSE; + + FILE* fp = popen(cmd, "w"); + free(cmd); + if (!fp) + { + WLog_ERR(TAG, "Failed to execute '%s'", buffer); + return FALSE; + } + + *pstatus = pclose(fp); + if (*pstatus < 0) + { + WLog_ERR(TAG, "Command '%s' returned %d", buffer, *pstatus); + return FALSE; + } + } + else + { + WLog_WARN(TAG, "ActionScript xevent: No such file '%s'", buffer); + return FALSE; + } + + return TRUE; +} + +static BOOL xf_event_execute_action_script(xfContext* xfc, const XEvent* event) +{ + size_t count = 0; + char* name = NULL; + BOOL match = FALSE; + const char* xeventName = NULL; + + if (!xfc->actionScriptExists || !xfc->xevents || !xfc->window) + return FALSE; + + if (event->type > LASTEvent) + return FALSE; + + xeventName = x11_event_string(event->type); + count = ArrayList_Count(xfc->xevents); + + for (size_t index = 0; index < count; index++) + { + name = (char*)ArrayList_GetItem(xfc->xevents, index); + + if (_stricmp(name, xeventName) == 0) + { + match = TRUE; + break; + } + } + + if (!match) + return FALSE; + + char command[2048] = { 0 }; + char arg[2048] = { 0 }; + (void)_snprintf(command, sizeof(command), "xevent %s", xeventName); + (void)_snprintf(arg, sizeof(arg), "%lu", (unsigned long)xfc->window->handle); + if (!run_action_script(xfc, command, arg, action_script_run, NULL)) + return FALSE; + return TRUE; +} + +void xf_adjust_coordinates_to_screen(xfContext* xfc, UINT32* x, UINT32* y) +{ + if (!xfc || !xfc->common.context.settings || !y || !x) + return; + + rdpSettings* settings = xfc->common.context.settings; + INT64 tx = *x; + INT64 ty = *y; + if (!xfc->remote_app) + { +#ifdef WITH_XRENDER + + if (xf_picture_transform_required(xfc)) + { + const double dw = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + const double dh = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + double xScalingFactor = xfc->scaledWidth / dw; + double yScalingFactor = xfc->scaledHeight / dh; + tx = (INT64)lround((1.0 * (*x) + xfc->offset_x) * xScalingFactor); + ty = (INT64)lround((1.0 * (*y) + xfc->offset_y) * yScalingFactor); + } + +#endif + } + + CLAMP_COORDINATES(tx, ty); + *x = (UINT32)tx; + *y = (UINT32)ty; +} + +void xf_event_adjust_coordinates(xfContext* xfc, int* x, int* y) +{ + if (!xfc || !xfc->common.context.settings || !y || !x) + return; + + if (!xfc->remote_app) + { +#ifdef WITH_XRENDER + rdpSettings* settings = xfc->common.context.settings; + if (xf_picture_transform_required(xfc)) + { + double xScalingFactor = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) / + (double)xfc->scaledWidth; + double yScalingFactor = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) / + (double)xfc->scaledHeight; + *x = (int)((*x - xfc->offset_x) * xScalingFactor); + *y = (int)((*y - xfc->offset_y) * yScalingFactor); + } + +#endif + } + + CLAMP_COORDINATES(*x, *y); +} + +static BOOL xf_event_Expose(xfContext* xfc, const XExposeEvent* event, BOOL app) +{ + int x = 0; + int y = 0; + int w = 0; + int h = 0; + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (!app && (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures))) + { + x = 0; + y = 0; + w = WINPR_ASSERTING_INT_CAST(int, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + h = WINPR_ASSERTING_INT_CAST(int, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + } + else + { + x = event->x; + y = event->y; + w = event->width; + h = event->height; + } + + if (!app) + { + if (xfc->common.context.gdi->gfx) + { + xf_OutputExpose( + xfc, WINPR_ASSERTING_INT_CAST(uint32_t, x), WINPR_ASSERTING_INT_CAST(uint32_t, y), + WINPR_ASSERTING_INT_CAST(uint32_t, w), WINPR_ASSERTING_INT_CAST(uint32_t, h)); + return TRUE; + } + xf_draw_screen(xfc, x, y, w, h); + } + else + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + if (appWindow) + { + xf_UpdateWindowArea(xfc, appWindow, x, y, w, h); + } + } + + return TRUE; +} + +static BOOL xf_event_VisibilityNotify(xfContext* xfc, const XVisibilityEvent* event, BOOL app) +{ + WINPR_UNUSED(app); + xfc->unobscured = event->state == VisibilityUnobscured; + return TRUE; +} + +BOOL xf_generic_MotionNotify(xfContext* xfc, int x, int y, int state, Window window, BOOL app) +{ + Window childWindow = None; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->common.context.settings); + + if (!freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_MouseMotion)) + { + if ((state & (Button1Mask | Button2Mask | Button3Mask)) == 0) + return TRUE; + } + + if (app) + { + /* make sure window exists */ + if (!xf_AppWindowFromX11Window(xfc, window)) + return TRUE; + + /* Translate to desktop coordinates */ + XTranslateCoordinates(xfc->display, window, RootWindowOfScreen(xfc->screen), x, y, &x, &y, + &childWindow); + } + + xf_event_adjust_coordinates(xfc, &x, &y); + freerdp_client_send_button_event(&xfc->common, FALSE, PTR_FLAGS_MOVE, x, y); + + if (xfc->fullscreen && !app) + { + XSetInputFocus(xfc->display, xfc->window->handle, RevertToPointerRoot, CurrentTime); + } + + return TRUE; +} + +BOOL xf_generic_RawMotionNotify(xfContext* xfc, int x, int y, Window window, BOOL app) +{ + WINPR_ASSERT(xfc); + + if (app) + { + WLog_ERR(TAG, "Relative mouse input is not supported with remoate app mode!"); + return FALSE; + } + + return freerdp_client_send_button_event(&xfc->common, TRUE, PTR_FLAGS_MOVE, x, y); +} + +static BOOL xf_event_MotionNotify(xfContext* xfc, const XMotionEvent* event, BOOL app) +{ + WINPR_ASSERT(xfc); + + if (xfc->window) + xf_floatbar_set_root_y(xfc->window->floatbar, event->y); + + if (xfc->xi_event || + (xfc->common.mouse_grabbed && freerdp_client_use_relative_mouse_events(&xfc->common))) + return TRUE; + + return xf_generic_MotionNotify(xfc, event->x, event->y, + WINPR_ASSERTING_INT_CAST(int, event->state), event->window, app); +} + +BOOL xf_generic_ButtonEvent(xfContext* xfc, int x, int y, int button, Window window, BOOL app, + BOOL down) +{ + UINT16 flags = 0; + Window childWindow = None; + + WINPR_ASSERT(xfc); + if (button < 0) + return FALSE; + + for (size_t i = 0; i < ARRAYSIZE(xfc->button_map); i++) + { + const button_map* cur = &xfc->button_map[i]; + + if (cur->button == (UINT32)button) + { + flags = cur->flags; + break; + } + } + + if (flags != 0) + { + if (flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL)) + { + if (down) + freerdp_client_send_wheel_event(&xfc->common, flags); + } + else + { + BOOL extended = FALSE; + + if (flags & (PTR_XFLAGS_BUTTON1 | PTR_XFLAGS_BUTTON2)) + { + extended = TRUE; + + if (down) + flags |= PTR_XFLAGS_DOWN; + } + else if (flags & (PTR_FLAGS_BUTTON1 | PTR_FLAGS_BUTTON2 | PTR_FLAGS_BUTTON3)) + { + if (down) + flags |= PTR_FLAGS_DOWN; + } + + if (app) + { + /* make sure window exists */ + if (!xf_AppWindowFromX11Window(xfc, window)) + return TRUE; + + /* Translate to desktop coordinates */ + XTranslateCoordinates(xfc->display, window, RootWindowOfScreen(xfc->screen), x, y, + &x, &y, &childWindow); + } + + xf_event_adjust_coordinates(xfc, &x, &y); + + if (extended) + freerdp_client_send_extended_button_event(&xfc->common, FALSE, flags, x, y); + else + freerdp_client_send_button_event(&xfc->common, FALSE, flags, x, y); + } + } + + return TRUE; +} + +static BOOL xf_grab_mouse(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + if (!xfc->window) + return FALSE; + + if (freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_GrabMouse)) + { + XGrabPointer(xfc->display, xfc->window->handle, False, + ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask | + EnterWindowMask | LeaveWindowMask, + GrabModeAsync, GrabModeAsync, xfc->window->handle, None, CurrentTime); + xfc->common.mouse_grabbed = TRUE; + } + return TRUE; +} + +static BOOL xf_grab_kbd(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + if (!xfc->window) + return FALSE; + + XGrabKeyboard(xfc->display, xfc->window->handle, TRUE, GrabModeAsync, GrabModeAsync, + CurrentTime); + return TRUE; +} + +static BOOL xf_event_ButtonPress(xfContext* xfc, const XButtonEvent* event, BOOL app) +{ + xf_grab_mouse(xfc); + + if (xfc->xi_event || + (xfc->common.mouse_grabbed && freerdp_client_use_relative_mouse_events(&xfc->common))) + return TRUE; + return xf_generic_ButtonEvent(xfc, event->x, event->y, + WINPR_ASSERTING_INT_CAST(int, event->button), event->window, app, + TRUE); +} + +static BOOL xf_event_ButtonRelease(xfContext* xfc, const XButtonEvent* event, BOOL app) +{ + xf_grab_mouse(xfc); + + if (xfc->xi_event || + (xfc->common.mouse_grabbed && freerdp_client_use_relative_mouse_events(&xfc->common))) + return TRUE; + return xf_generic_ButtonEvent(xfc, event->x, event->y, + WINPR_ASSERTING_INT_CAST(int, event->button), event->window, app, + FALSE); +} + +static BOOL xf_event_KeyPress(xfContext* xfc, const XKeyEvent* event, BOOL app) +{ + KeySym keysym = 0; + char str[256] = { 0 }; + union + { + const XKeyEvent* cev; + XKeyEvent* ev; + } cnv; + cnv.cev = event; + WINPR_UNUSED(app); + XLookupString(cnv.ev, str, sizeof(str), &keysym, NULL); + xf_keyboard_key_press(xfc, event, keysym); + return TRUE; +} + +static BOOL xf_event_KeyRelease(xfContext* xfc, const XKeyEvent* event, BOOL app) +{ + KeySym keysym = 0; + char str[256] = { 0 }; + union + { + const XKeyEvent* cev; + XKeyEvent* ev; + } cnv; + cnv.cev = event; + + WINPR_UNUSED(app); + XLookupString(cnv.ev, str, sizeof(str), &keysym, NULL); + xf_keyboard_key_release(xfc, event, keysym); + return TRUE; +} + +/* Release a key, but ignore the event in case of autorepeat. + */ +static BOOL xf_event_KeyReleaseOrIgnore(xfContext* xfc, const XKeyEvent* event, BOOL app) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + if ((event->type == KeyRelease) && XEventsQueued(xfc->display, QueuedAfterReading)) + { + XEvent nev = { 0 }; + XPeekEvent(xfc->display, &nev); + + if ((nev.type == KeyPress) && (nev.xkey.time == event->time) && + (nev.xkey.keycode == event->keycode)) + { + /* Key wasn’t actually released */ + return TRUE; + } + } + + return xf_event_KeyRelease(xfc, event, app); +} + +static BOOL xf_event_FocusIn(xfContext* xfc, const XFocusInEvent* event, BOOL app) +{ + if (event->mode == NotifyGrab) + return TRUE; + + xfc->focused = TRUE; + + if (xfc->mouse_active && !app) + { + xf_grab_mouse(xfc); + if (!xf_grab_kbd(xfc)) + return FALSE; + } + + /* Release all keys, should already be done at FocusOut but might be missed + * if the WM decided to use an alternate event order */ + if (!app) + xf_keyboard_release_all_keypress(xfc); + else + xf_rail_send_activate(xfc, event->window, TRUE); + + xf_pointer_update_scale(xfc); + + if (app) + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + /* Update the server with any window changes that occurred while the window was not focused. + */ + if (appWindow) + xf_rail_adjust_position(xfc, appWindow); + } + + xf_keyboard_focus_in(xfc); + return TRUE; +} + +static BOOL xf_event_FocusOut(xfContext* xfc, const XFocusOutEvent* event, BOOL app) +{ + if (event->mode == NotifyUngrab) + return TRUE; + + xfc->focused = FALSE; + + if (event->mode == NotifyWhileGrabbed) + XUngrabKeyboard(xfc->display, CurrentTime); + + xf_keyboard_release_all_keypress(xfc); + if (app) + xf_rail_send_activate(xfc, event->window, FALSE); + + return TRUE; +} + +static BOOL xf_event_MappingNotify(xfContext* xfc, const XMappingEvent* event, BOOL app) +{ + WINPR_UNUSED(app); + + switch (event->request) + { + case MappingModifier: + return xf_keyboard_update_modifier_map(xfc); + case MappingKeyboard: + WLog_VRB(TAG, "[%d] MappingKeyboard", event->request); + return xf_keyboard_init(xfc); + case MappingPointer: + WLog_VRB(TAG, "[%d] MappingPointer", event->request); + xf_button_map_init(xfc); + return TRUE; + default: + WLog_WARN(TAG, + "[%d] Unsupported MappingNotify::request, must be one " + "of[MappingModifier(%d), MappingKeyboard(%d), MappingPointer(%d)]", + event->request, MappingModifier, MappingKeyboard, MappingPointer); + return FALSE; + } +} + +static BOOL xf_event_ClientMessage(xfContext* xfc, const XClientMessageEvent* event, BOOL app) +{ + if ((event->message_type == xfc->WM_PROTOCOLS) && + ((Atom)event->data.l[0] == xfc->WM_DELETE_WINDOW)) + { + if (app) + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + if (appWindow) + return xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_CLOSE); + + return TRUE; + } + else + { + DEBUG_X11("Main window closed"); + return FALSE; + } + } + + return TRUE; +} + +static BOOL xf_event_EnterNotify(xfContext* xfc, const XEnterWindowEvent* event, BOOL app) +{ + if (!app) + { + if (!xfc->window) + return FALSE; + + xfc->mouse_active = TRUE; + + if (xfc->fullscreen) + XSetInputFocus(xfc->display, xfc->window->handle, RevertToPointerRoot, CurrentTime); + + if (xfc->focused) + xf_grab_kbd(xfc); + } + else + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + /* keep track of which window has focus so that we can apply pointer updates */ + xfc->appWindow = appWindow; + } + + return TRUE; +} + +static BOOL xf_event_LeaveNotify(xfContext* xfc, const XLeaveWindowEvent* event, BOOL app) +{ + if (event->mode == NotifyGrab || event->mode == NotifyUngrab) + return TRUE; + if (!app) + { + xfc->mouse_active = FALSE; + XUngrabKeyboard(xfc->display, CurrentTime); + } + else + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + /* keep track of which window has focus so that we can apply pointer updates */ + if (xfc->appWindow == appWindow) + xfc->appWindow = NULL; + } + return TRUE; +} + +static BOOL xf_event_ConfigureNotify(xfContext* xfc, const XConfigureEvent* event, BOOL app) +{ + Window childWindow = None; + xfAppWindow* appWindow = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + const rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + WLog_DBG(TAG, "x=%" PRId32 ", y=%" PRId32 ", w=%" PRId32 ", h=%" PRId32, event->x, event->y, + event->width, event->height); + + if (!app) + { + if (!xfc->window) + return FALSE; + + if (xfc->window->left != event->x) + xfc->window->left = event->x; + + if (xfc->window->top != event->y) + xfc->window->top = event->y; + + if (xfc->window->width != event->width || xfc->window->height != event->height) + { + xfc->window->width = event->width; + xfc->window->height = event->height; +#ifdef WITH_XRENDER + xfc->offset_x = 0; + xfc->offset_y = 0; + + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures)) + { + xfc->scaledWidth = xfc->window->width; + xfc->scaledHeight = xfc->window->height; + xf_draw_screen( + xfc, 0, 0, + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)), + WINPR_ASSERTING_INT_CAST( + int32_t, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))); + } + else + { + xfc->scaledWidth = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth)); + xfc->scaledHeight = WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + } + +#endif + } + + if (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) + { + int alignedWidth = 0; + int alignedHeight = 0; + alignedWidth = (xfc->window->width / 2) * 2; + alignedHeight = (xfc->window->height / 2) * 2; + /* ask the server to resize using the display channel */ + xf_disp_handle_configureNotify(xfc, alignedWidth, alignedHeight); + } + } + else + { + appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + if (appWindow) + { + /* + * ConfigureNotify coordinates are expressed relative to the window parent. + * Translate these to root window coordinates. + */ + XTranslateCoordinates(xfc->display, appWindow->handle, RootWindowOfScreen(xfc->screen), + 0, 0, &appWindow->x, &appWindow->y, &childWindow); + appWindow->width = event->width; + appWindow->height = event->height; + + xf_AppWindowResize(xfc, appWindow); + + /* + * Additional checks for not in a local move and not ignoring configure to send + * position update to server, also should the window not be focused then do not + * send to server yet (i.e. resizing using window decoration). + * The server will be updated when the window gets refocused. + */ + if (appWindow->decorations) + { + /* moving resizing using window decoration */ + xf_rail_adjust_position(xfc, appWindow); + } + else + { + if ((!event->send_event || appWindow->local_move.state == LMS_NOT_ACTIVE) && + !appWindow->rail_ignore_configure && xfc->focused) + xf_rail_adjust_position(xfc, appWindow); + } + } + } + return xf_pointer_update_scale(xfc); +} + +static BOOL xf_event_MapNotify(xfContext* xfc, const XMapEvent* event, BOOL app) +{ + WINPR_ASSERT(xfc); + if (!app) + gdi_send_suppress_output(xfc->common.context.gdi, FALSE); + else + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + if (appWindow) + { + /* local restore event */ + /* This is now handled as part of the PropertyNotify + * Doing this here would inhibit the ability to restore a maximized window + * that is minimized back to the maximized state + */ + // xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_RESTORE); + appWindow->is_mapped = TRUE; + } + } + + return TRUE; +} + +static BOOL xf_event_UnmapNotify(xfContext* xfc, const XUnmapEvent* event, BOOL app) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + if (!app) + xf_keyboard_release_all_keypress(xfc); + + if (!app) + gdi_send_suppress_output(xfc->common.context.gdi, TRUE); + else + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + if (appWindow) + appWindow->is_mapped = FALSE; + } + + return TRUE; +} + +static BOOL xf_event_PropertyNotify(xfContext* xfc, const XPropertyEvent* event, BOOL app) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + /* + * This section handles sending the appropriate commands to the rail server + * when the window has been minimized, maximized, restored locally + * ie. not using the buttons on the rail window itself + */ + if (((event->atom == xfc->_NET_WM_STATE) && (event->state != PropertyDelete)) || + ((event->atom == xfc->WM_STATE) && (event->state != PropertyDelete))) + { + BOOL status = FALSE; + BOOL minimized = FALSE; + BOOL minimizedChanged = FALSE; + unsigned long nitems = 0; + unsigned long bytes = 0; + unsigned char* prop = NULL; + xfAppWindow* appWindow = NULL; + + if (app) + { + appWindow = xf_AppWindowFromX11Window(xfc, event->window); + + if (!appWindow) + return TRUE; + } + + if (event->atom == xfc->_NET_WM_STATE) + { + status = xf_GetWindowProperty(xfc, event->window, xfc->_NET_WM_STATE, 12, &nitems, + &bytes, &prop); + + if (status) + { + if (appWindow) + { + appWindow->maxVert = FALSE; + appWindow->maxHorz = FALSE; + } + for (unsigned long i = 0; i < nitems; i++) + { + if ((Atom)((UINT16**)prop)[i] == + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_MAXIMIZED_VERT", + False)) + { + if (appWindow) + appWindow->maxVert = TRUE; + } + + if ((Atom)((UINT16**)prop)[i] == + Logging_XInternAtom(xfc->log, xfc->display, "_NET_WM_STATE_MAXIMIZED_HORZ", + False)) + { + if (appWindow) + appWindow->maxHorz = TRUE; + } + } + + XFree(prop); + } + } + + if (event->atom == xfc->WM_STATE) + { + status = + xf_GetWindowProperty(xfc, event->window, xfc->WM_STATE, 1, &nitems, &bytes, &prop); + + if (status) + { + /* If the window is in the iconic state */ + if (((UINT32)*prop == 3) && !IsGnome()) + { + minimized = TRUE; + if (appWindow) + appWindow->minimized = TRUE; + } + else + { + minimized = FALSE; + if (appWindow) + appWindow->minimized = FALSE; + } + + minimizedChanged = TRUE; + XFree(prop); + } + } + + if (app) + { + WINPR_ASSERT(appWindow); + if (appWindow->maxVert && appWindow->maxHorz && !appWindow->minimized) + { + if (appWindow->rail_state != WINDOW_SHOW_MAXIMIZED) + { + appWindow->rail_state = WINDOW_SHOW_MAXIMIZED; + return xf_rail_send_client_system_command(xfc, appWindow->windowId, + SC_MAXIMIZE); + } + } + else if (appWindow->minimized) + { + if (appWindow->rail_state != WINDOW_SHOW_MINIMIZED) + { + appWindow->rail_state = WINDOW_SHOW_MINIMIZED; + return xf_rail_send_client_system_command(xfc, appWindow->windowId, + SC_MINIMIZE); + } + } + else + { + if (appWindow->rail_state != WINDOW_SHOW && appWindow->rail_state != WINDOW_HIDE) + { + appWindow->rail_state = WINDOW_SHOW; + return xf_rail_send_client_system_command(xfc, appWindow->windowId, SC_RESTORE); + } + } + } + else if (minimizedChanged) + gdi_send_suppress_output(xfc->common.context.gdi, minimized); + } + + return TRUE; +} + +static BOOL xf_event_suppress_events(xfContext* xfc, xfAppWindow* appWindow, const XEvent* event) +{ + if (!xfc->remote_app) + return FALSE; + + switch (appWindow->local_move.state) + { + case LMS_NOT_ACTIVE: + + /* No local move in progress, nothing to do */ + + /* Prevent Configure from happening during indeterminant state of Horz or Vert Max only + */ + if ((event->type == ConfigureNotify) && appWindow->rail_ignore_configure) + { + appWindow->rail_ignore_configure = FALSE; + return TRUE; + } + + break; + + case LMS_STARTING: + + /* Local move initiated by RDP server, but we have not yet seen any updates from the X + * server */ + switch (event->type) + { + case ConfigureNotify: + /* Starting to see move events from the X server. Local move is now in progress. + */ + appWindow->local_move.state = LMS_ACTIVE; + /* Allow these events to be processed during move to keep our state up to date. + */ + break; + + case ButtonPress: + case ButtonRelease: + case KeyPress: + case KeyRelease: + case UnmapNotify: + /* + * A button release event means the X window server did not grab the + * mouse before the user released it. In this case we must cancel the + * local move. The event will be processed below as normal, below. + */ + break; + + case VisibilityNotify: + case PropertyNotify: + case Expose: + /* Allow these events to pass */ + break; + + default: + /* Eat any other events */ + return TRUE; + } + + break; + + case LMS_ACTIVE: + + /* Local move is in progress */ + switch (event->type) + { + case ConfigureNotify: + case VisibilityNotify: + case PropertyNotify: + case Expose: + case GravityNotify: + /* Keep us up to date on position */ + break; + + default: + /* Any other event terminates move */ + xf_rail_end_local_move(xfc, appWindow); + break; + } + + break; + + case LMS_TERMINATING: + /* Already sent RDP end move to server. Allow events to pass. */ + break; + default: + break; + } + + return FALSE; +} + +BOOL xf_event_process(freerdp* instance, const XEvent* event) +{ + BOOL status = TRUE; + + WINPR_ASSERT(instance); + WINPR_ASSERT(event); + + xfContext* xfc = (xfContext*)instance->context; + WINPR_ASSERT(xfc); + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (xfc->remote_app) + { + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, event->xany.window); + + if (appWindow) + { + /* Update "current" window for cursor change orders */ + xfc->appWindow = appWindow; + + if (xf_event_suppress_events(xfc, appWindow, event)) + return TRUE; + } + } + + if (xfc->window) + { + xfFloatbar* floatbar = xfc->window->floatbar; + if (xf_floatbar_check_event(floatbar, event)) + { + xf_floatbar_event_process(floatbar, event); + return TRUE; + } + + if (xf_floatbar_is_locked(floatbar)) + return TRUE; + } + + xf_event_execute_action_script(xfc, event); + + if (event->type != MotionNotify) + { + DEBUG_X11("%s Event(%d): wnd=0x%08lX", x11_event_string(event->type), event->type, + (unsigned long)event->xany.window); + } + + switch (event->type) + { + case Expose: + status = xf_event_Expose(xfc, &event->xexpose, xfc->remote_app); + break; + + case VisibilityNotify: + status = xf_event_VisibilityNotify(xfc, &event->xvisibility, xfc->remote_app); + break; + + case MotionNotify: + status = xf_event_MotionNotify(xfc, &event->xmotion, xfc->remote_app); + break; + + case ButtonPress: + status = xf_event_ButtonPress(xfc, &event->xbutton, xfc->remote_app); + break; + + case ButtonRelease: + status = xf_event_ButtonRelease(xfc, &event->xbutton, xfc->remote_app); + break; + + case KeyPress: + status = xf_event_KeyPress(xfc, &event->xkey, xfc->remote_app); + break; + + case KeyRelease: + status = xf_event_KeyReleaseOrIgnore(xfc, &event->xkey, xfc->remote_app); + break; + + case FocusIn: + status = xf_event_FocusIn(xfc, &event->xfocus, xfc->remote_app); + break; + + case FocusOut: + status = xf_event_FocusOut(xfc, &event->xfocus, xfc->remote_app); + break; + + case EnterNotify: + status = xf_event_EnterNotify(xfc, &event->xcrossing, xfc->remote_app); + break; + + case LeaveNotify: + status = xf_event_LeaveNotify(xfc, &event->xcrossing, xfc->remote_app); + break; + + case NoExpose: + break; + + case GraphicsExpose: + break; + + case ConfigureNotify: + status = xf_event_ConfigureNotify(xfc, &event->xconfigure, xfc->remote_app); + break; + + case MapNotify: + status = xf_event_MapNotify(xfc, &event->xmap, xfc->remote_app); + break; + + case UnmapNotify: + status = xf_event_UnmapNotify(xfc, &event->xunmap, xfc->remote_app); + break; + + case ReparentNotify: + break; + + case MappingNotify: + status = xf_event_MappingNotify(xfc, &event->xmapping, xfc->remote_app); + break; + + case ClientMessage: + status = xf_event_ClientMessage(xfc, &event->xclient, xfc->remote_app); + break; + + case PropertyNotify: + status = xf_event_PropertyNotify(xfc, &event->xproperty, xfc->remote_app); + break; + + default: + if (freerdp_settings_get_bool(settings, FreeRDP_SupportDisplayControl)) + xf_disp_handle_xevent(xfc, event); + + break; + } + + xfWindow* window = xfc->window; + xfFloatbar* floatbar = NULL; + if (window) + floatbar = window->floatbar; + + xf_cliprdr_handle_xevent(xfc, event); + if (!xf_floatbar_check_event(floatbar, event) && !xf_floatbar_is_locked(floatbar)) + xf_input_handle_event(xfc, event); + + XSync(xfc->display, FALSE); + return status; +} + +BOOL xf_generic_RawButtonEvent(xfContext* xfc, int button, BOOL app, BOOL down) +{ + UINT16 flags = 0; + + if (app || (button < 0)) + return FALSE; + + for (size_t i = 0; i < ARRAYSIZE(xfc->button_map); i++) + { + const button_map* cur = &xfc->button_map[i]; + + if (cur->button == (UINT32)button) + { + flags = cur->flags; + break; + } + } + + if (flags != 0) + { + if (flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL)) + { + if (down) + freerdp_client_send_wheel_event(&xfc->common, flags); + } + else + { + BOOL extended = FALSE; + + if (flags & (PTR_XFLAGS_BUTTON1 | PTR_XFLAGS_BUTTON2)) + { + extended = TRUE; + + if (down) + flags |= PTR_XFLAGS_DOWN; + } + else if (flags & (PTR_FLAGS_BUTTON1 | PTR_FLAGS_BUTTON2 | PTR_FLAGS_BUTTON3)) + { + if (down) + flags |= PTR_FLAGS_DOWN; + } + + if (extended) + freerdp_client_send_extended_button_event(&xfc->common, TRUE, flags, 0, 0); + else + freerdp_client_send_button_event(&xfc->common, TRUE, flags, 0, 0); + } + } + + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.h new file mode 100644 index 0000000000000000000000000000000000000000..2f4ab076c440241f0e49360692e5306bd9133017 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_event.h @@ -0,0 +1,46 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Event Handling + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_EVENT_H +#define FREERDP_CLIENT_X11_EVENT_H + +#include "xf_keyboard.h" + +#include "xf_client.h" +#include "xfreerdp.h" + +const char* x11_event_string(int event); + +BOOL xf_event_action_script_init(xfContext* xfc); +void xf_event_action_script_free(xfContext* xfc); + +BOOL xf_event_process(freerdp* instance, const XEvent* event); +void xf_event_SendClientEvent(xfContext* xfc, xfWindow* window, Atom atom, unsigned int numArgs, + ...); + +void xf_event_adjust_coordinates(xfContext* xfc, int* x, int* y); +void xf_adjust_coordinates_to_screen(xfContext* xfc, UINT32* x, UINT32* y); + +BOOL xf_generic_MotionNotify(xfContext* xfc, int x, int y, int state, Window window, BOOL app); +BOOL xf_generic_RawMotionNotify(xfContext* xfc, int x, int y, Window window, BOOL app); +BOOL xf_generic_ButtonEvent(xfContext* xfc, int x, int y, int button, Window window, BOOL app, + BOOL down); +BOOL xf_generic_RawButtonEvent(xfContext* xfc, int button, BOOL app, BOOL down); + +#endif /* FREERDP_CLIENT_X11_EVENT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.c new file mode 100644 index 0000000000000000000000000000000000000000..53776bb3f35e466cbcc84fbfd5288466938b91e8 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.c @@ -0,0 +1,932 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Windows + * + * Licensed under the Apache License, Version 2.0 (the "License");n + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "xf_floatbar.h" +#include "resource/close.xbm" +#include "resource/lock.xbm" +#include "resource/unlock.xbm" +#include "resource/minimize.xbm" +#include "resource/restore.xbm" + +#include +#define TAG CLIENT_TAG("x11") + +#define FLOATBAR_HEIGHT 26 +#define FLOATBAR_DEFAULT_WIDTH 576 +#define FLOATBAR_MIN_WIDTH 200 +#define FLOATBAR_BORDER 24 +#define FLOATBAR_BUTTON_WIDTH 24 +#define FLOATBAR_COLOR_BACKGROUND "RGB:31/6c/a9" +#define FLOATBAR_COLOR_BORDER "RGB:75/9a/c8" +#define FLOATBAR_COLOR_FOREGROUND "RGB:FF/FF/FF" + +#define XF_FLOATBAR_MODE_NONE 0 +#define XF_FLOATBAR_MODE_DRAGGING 1 +#define XF_FLOATBAR_MODE_RESIZE_LEFT 2 +#define XF_FLOATBAR_MODE_RESIZE_RIGHT 3 + +#define XF_FLOATBAR_BUTTON_CLOSE 1 +#define XF_FLOATBAR_BUTTON_RESTORE 2 +#define XF_FLOATBAR_BUTTON_MINIMIZE 3 +#define XF_FLOATBAR_BUTTON_LOCKED 4 + +typedef BOOL (*OnClick)(xfFloatbar*); + +typedef struct +{ + int x; + int y; + int type; + bool focus; + bool clicked; + OnClick onclick; + Window handle; +} xfFloatbarButton; + +struct xf_floatbar +{ + int x; + int y; + int width; + int height; + int mode; + int last_motion_x_root; + int last_motion_y_root; + BOOL locked; + xfFloatbarButton* buttons[4]; + Window handle; + BOOL hasCursor; + xfContext* xfc; + DWORD flags; + BOOL created; + Window root_window; + char* title; + XFontSet fontSet; +}; + +static xfFloatbarButton* xf_floatbar_new_button(xfFloatbar* floatbar, int type); + +static BOOL xf_floatbar_button_onclick_close(xfFloatbar* floatbar) +{ + if (!floatbar) + return FALSE; + + return freerdp_abort_connect_context(&floatbar->xfc->common.context); +} + +static BOOL xf_floatbar_button_onclick_minimize(xfFloatbar* floatbar) +{ + xfContext* xfc = NULL; + + if (!floatbar || !floatbar->xfc) + return FALSE; + + xfc = floatbar->xfc; + xf_SetWindowMinimized(xfc, xfc->window); + return TRUE; +} + +static BOOL xf_floatbar_button_onclick_restore(xfFloatbar* floatbar) +{ + if (!floatbar) + return FALSE; + + xf_toggle_fullscreen(floatbar->xfc); + return TRUE; +} + +static BOOL xf_floatbar_button_onclick_locked(xfFloatbar* floatbar) +{ + if (!floatbar) + return FALSE; + + floatbar->locked = (floatbar->locked) ? FALSE : TRUE; + return xf_floatbar_hide_and_show(floatbar); +} + +BOOL xf_floatbar_set_root_y(xfFloatbar* floatbar, int y) +{ + if (!floatbar) + return FALSE; + + floatbar->last_motion_y_root = y; + return TRUE; +} + +BOOL xf_floatbar_hide_and_show(xfFloatbar* floatbar) +{ + xfContext* xfc = NULL; + + if (!floatbar || !floatbar->xfc) + return FALSE; + + if (!floatbar->created) + return TRUE; + + xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + + if (!floatbar->locked) + { + if ((floatbar->mode == XF_FLOATBAR_MODE_NONE) && (floatbar->last_motion_y_root > 10) && + (floatbar->y > (FLOATBAR_HEIGHT * -1))) + { + floatbar->y = floatbar->y - 1; + XMoveWindow(xfc->display, floatbar->handle, floatbar->x, floatbar->y); + } + else if (floatbar->y < 0 && (floatbar->last_motion_y_root < 10)) + { + floatbar->y = floatbar->y + 1; + XMoveWindow(xfc->display, floatbar->handle, floatbar->x, floatbar->y); + } + } + + return TRUE; +} + +static BOOL create_floatbar(xfFloatbar* floatbar) +{ + xfContext* xfc = NULL; + Status status = 0; + XWindowAttributes attr = { 0 }; + + WINPR_ASSERT(floatbar); + if (floatbar->created) + return TRUE; + + xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + + status = XGetWindowAttributes(xfc->display, floatbar->root_window, &attr); + if (status == 0) + { + WLog_WARN(TAG, "XGetWindowAttributes failed"); + return FALSE; + } + floatbar->x = attr.x + attr.width / 2 - FLOATBAR_DEFAULT_WIDTH / 2; + floatbar->y = 0; + + if (((floatbar->flags & 0x0004) == 0) && !floatbar->locked) + floatbar->y = -FLOATBAR_HEIGHT + 1; + + floatbar->handle = + XCreateWindow(xfc->display, floatbar->root_window, floatbar->x, 0, FLOATBAR_DEFAULT_WIDTH, + FLOATBAR_HEIGHT, 0, CopyFromParent, InputOutput, CopyFromParent, 0, NULL); + floatbar->width = FLOATBAR_DEFAULT_WIDTH; + floatbar->height = FLOATBAR_HEIGHT; + floatbar->mode = XF_FLOATBAR_MODE_NONE; + floatbar->buttons[0] = xf_floatbar_new_button(floatbar, XF_FLOATBAR_BUTTON_CLOSE); + floatbar->buttons[1] = xf_floatbar_new_button(floatbar, XF_FLOATBAR_BUTTON_RESTORE); + floatbar->buttons[2] = xf_floatbar_new_button(floatbar, XF_FLOATBAR_BUTTON_MINIMIZE); + floatbar->buttons[3] = xf_floatbar_new_button(floatbar, XF_FLOATBAR_BUTTON_LOCKED); + XSelectInput(xfc->display, floatbar->handle, + ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | + FocusChangeMask | LeaveWindowMask | EnterWindowMask | StructureNotifyMask | + PropertyChangeMask); + floatbar->created = TRUE; + return TRUE; +} + +BOOL xf_floatbar_toggle_fullscreen(xfFloatbar* floatbar, bool fullscreen) +{ + int size = 0; + bool visible = False; + xfContext* xfc = NULL; + + if (!floatbar || !floatbar->xfc) + return FALSE; + + xfc = floatbar->xfc; + WINPR_ASSERT(xfc->display); + + /* Only visible if enabled */ + if (floatbar->flags & 0x0001) + { + /* Visible if fullscreen and flag visible in fullscreen mode */ + visible |= ((floatbar->flags & 0x0010) != 0) && fullscreen; + /* Visible if window and flag visible in window mode */ + visible |= ((floatbar->flags & 0x0020) != 0) && !fullscreen; + } + + if (visible) + { + if (!create_floatbar(floatbar)) + return FALSE; + + XMapWindow(xfc->display, floatbar->handle); + size = ARRAYSIZE(floatbar->buttons); + + for (int i = 0; i < size; i++) + { + xfFloatbarButton* button = floatbar->buttons[i]; + XMapWindow(xfc->display, button->handle); + } + + /* If default is hidden (and not sticky) don't show on fullscreen state changes */ + if (((floatbar->flags & 0x0004) == 0) && !floatbar->locked) + floatbar->y = -FLOATBAR_HEIGHT + 1; + + xf_floatbar_hide_and_show(floatbar); + } + else if (floatbar->created) + { + XUnmapSubwindows(xfc->display, floatbar->handle); + XUnmapWindow(xfc->display, floatbar->handle); + } + + return TRUE; +} + +xfFloatbarButton* xf_floatbar_new_button(xfFloatbar* floatbar, int type) +{ + xfFloatbarButton* button = NULL; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(floatbar->xfc); + WINPR_ASSERT(floatbar->xfc->display); + WINPR_ASSERT(floatbar->handle); + + button = (xfFloatbarButton*)calloc(1, sizeof(xfFloatbarButton)); + button->type = type; + + switch (type) + { + case XF_FLOATBAR_BUTTON_CLOSE: + button->x = floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * type; + button->onclick = xf_floatbar_button_onclick_close; + break; + + case XF_FLOATBAR_BUTTON_RESTORE: + button->x = floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * type; + button->onclick = xf_floatbar_button_onclick_restore; + break; + + case XF_FLOATBAR_BUTTON_MINIMIZE: + button->x = floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * type; + button->onclick = xf_floatbar_button_onclick_minimize; + break; + + case XF_FLOATBAR_BUTTON_LOCKED: + button->x = FLOATBAR_BORDER; + button->onclick = xf_floatbar_button_onclick_locked; + break; + + default: + break; + } + + button->y = 0; + button->focus = FALSE; + button->handle = XCreateWindow(floatbar->xfc->display, floatbar->handle, button->x, 0, + FLOATBAR_BUTTON_WIDTH, FLOATBAR_BUTTON_WIDTH, 0, CopyFromParent, + InputOutput, CopyFromParent, 0, NULL); + XSelectInput(floatbar->xfc->display, button->handle, + ExposureMask | ButtonPressMask | ButtonReleaseMask | FocusChangeMask | + LeaveWindowMask | EnterWindowMask | StructureNotifyMask); + return button; +} + +xfFloatbar* xf_floatbar_new(xfContext* xfc, Window window, const char* name, DWORD flags) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + WINPR_ASSERT(name); + + /* Floatbar not enabled */ + if ((flags & 0x0001) == 0) + return NULL; + + if (!xfc) + return NULL; + + /* Force disable with remote app */ + if (xfc->remote_app) + return NULL; + + xfFloatbar* floatbar = (xfFloatbar*)calloc(1, sizeof(xfFloatbar)); + + if (!floatbar) + return NULL; + + floatbar->title = _strdup(name); + + if (!floatbar->title) + goto fail; + + floatbar->root_window = window; + floatbar->flags = flags; + floatbar->xfc = xfc; + floatbar->locked = (flags & 0x0002) != 0 ? TRUE : FALSE; + xf_floatbar_toggle_fullscreen(floatbar, FALSE); + char** missingList = NULL; + int missingCount = 0; + char* defString = NULL; + floatbar->fontSet = XCreateFontSet(floatbar->xfc->display, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*", + &missingList, &missingCount, &defString); + if (floatbar->fontSet == NULL) + { + WLog_ERR(TAG, "Failed to create fontset"); + } + XFreeStringList(missingList); + return floatbar; +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + xf_floatbar_free(floatbar); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +static unsigned long xf_floatbar_get_color(xfFloatbar* floatbar, char* rgb_value) +{ + XColor color; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(floatbar->xfc); + + Display* display = floatbar->xfc->display; + WINPR_ASSERT(display); + + Colormap cmap = DefaultColormap(display, XDefaultScreen(display)); + XParseColor(display, cmap, rgb_value, &color); + XAllocColor(display, cmap, &color); + return color.pixel; +} + +static void xf_floatbar_event_expose(xfFloatbar* floatbar) +{ + GC gc = NULL; + GC shape_gc = NULL; + Pixmap pmap = 0; + XPoint shape[5] = { 0 }; + XPoint border[5] = { 0 }; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(floatbar->xfc); + + Display* display = floatbar->xfc->display; + WINPR_ASSERT(display); + + /* create the pixmap that we'll use for shaping the window */ + pmap = XCreatePixmap(display, floatbar->handle, + WINPR_ASSERTING_INT_CAST(uint32_t, floatbar->width), + WINPR_ASSERTING_INT_CAST(uint32_t, floatbar->height), 1); + gc = XCreateGC(display, floatbar->handle, 0, 0); + shape_gc = XCreateGC(display, pmap, 0, 0); + /* points for drawing the floatbar */ + shape[0].x = 0; + shape[0].y = 0; + shape[1].x = WINPR_ASSERTING_INT_CAST(short, floatbar->width); + shape[1].y = 0; + shape[2].x = WINPR_ASSERTING_INT_CAST(short, shape[1].x - FLOATBAR_BORDER); + shape[2].y = FLOATBAR_HEIGHT; + shape[3].x = WINPR_ASSERTING_INT_CAST(short, shape[0].x + FLOATBAR_BORDER); + shape[3].y = FLOATBAR_HEIGHT; + shape[4].x = shape[0].x; + shape[4].y = shape[0].y; + /* points for drawing the border of the floatbar */ + border[0].x = shape[0].x; + border[0].y = WINPR_ASSERTING_INT_CAST(short, shape[0].y - 1); + border[1].x = WINPR_ASSERTING_INT_CAST(short, shape[1].x - 1); + border[1].y = WINPR_ASSERTING_INT_CAST(short, shape[1].y - 1); + border[2].x = shape[2].x; + border[2].y = WINPR_ASSERTING_INT_CAST(short, shape[2].y - 1); + border[3].x = WINPR_ASSERTING_INT_CAST(short, shape[3].x - 1); + border[3].y = WINPR_ASSERTING_INT_CAST(short, shape[3].y - 1); + border[4].x = border[0].x; + border[4].y = border[0].y; + /* Fill all pixels with 0 */ + XSetForeground(display, shape_gc, 0); + XFillRectangle(display, pmap, shape_gc, 0, 0, + WINPR_ASSERTING_INT_CAST(uint32_t, floatbar->width), + WINPR_ASSERTING_INT_CAST(uint32_t, floatbar->height)); + /* Fill all pixels which should be shown with 1 */ + XSetForeground(display, shape_gc, 1); + XFillPolygon(display, pmap, shape_gc, shape, 5, 0, CoordModeOrigin); + XShapeCombineMask(display, floatbar->handle, ShapeBounding, 0, 0, pmap, ShapeSet); + /* draw the float bar */ + XSetForeground(display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_BACKGROUND)); + XFillPolygon(display, floatbar->handle, gc, shape, 4, 0, CoordModeOrigin); + /* draw an border for the floatbar */ + XSetForeground(display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_BORDER)); + XDrawLines(display, floatbar->handle, gc, border, 5, CoordModeOrigin); + /* draw the host name connected to (limit to maximum file name) */ + const size_t len = strnlen(floatbar->title, MAX_PATH); + XSetForeground(display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_FOREGROUND)); + + WINPR_ASSERT(len <= INT32_MAX / 2); + const int fx = floatbar->width / 2 - (int)len * 2; + if (floatbar->fontSet != NULL) + { + XmbDrawString(display, floatbar->handle, floatbar->fontSet, gc, fx, 15, floatbar->title, + (int)len); + } + else + { + XDrawString(display, floatbar->handle, gc, fx, 15, floatbar->title, (int)len); + } + XFreeGC(display, gc); + XFreeGC(display, shape_gc); +} + +static xfFloatbarButton* xf_floatbar_get_button(xfFloatbar* floatbar, Window window) +{ + WINPR_ASSERT(floatbar); + const size_t size = ARRAYSIZE(floatbar->buttons); + + for (size_t i = 0; i < size; i++) + { + xfFloatbarButton* button = floatbar->buttons[i]; + if (button->handle == window) + { + return button; + } + } + + return NULL; +} + +static void xf_floatbar_button_update_positon(xfFloatbar* floatbar) +{ + xfFloatbarButton* button = NULL; + WINPR_ASSERT(floatbar); + xfContext* xfc = floatbar->xfc; + const size_t size = ARRAYSIZE(floatbar->buttons); + + for (size_t i = 0; i < size; i++) + { + button = floatbar->buttons[i]; + + switch (button->type) + { + case XF_FLOATBAR_BUTTON_CLOSE: + button->x = + floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * button->type; + break; + + case XF_FLOATBAR_BUTTON_RESTORE: + button->x = + floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * button->type; + break; + + case XF_FLOATBAR_BUTTON_MINIMIZE: + button->x = + floatbar->width - FLOATBAR_BORDER - FLOATBAR_BUTTON_WIDTH * button->type; + break; + + default: + break; + } + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + XMoveWindow(xfc->display, button->handle, button->x, button->y); + xf_floatbar_event_expose(floatbar); + } +} + +static void xf_floatbar_button_event_expose(xfFloatbar* floatbar, Window window) +{ + xfFloatbarButton* button = xf_floatbar_get_button(floatbar, window); + static unsigned char* bits; + GC gc = NULL; + Pixmap pattern = 0; + xfContext* xfc = floatbar->xfc; + + if (!button) + return; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + WINPR_ASSERT(xfc->window); + + gc = XCreateGC(xfc->display, button->handle, 0, 0); + floatbar = xfc->window->floatbar; + WINPR_ASSERT(floatbar); + + switch (button->type) + { + case XF_FLOATBAR_BUTTON_CLOSE: + bits = close_bits; + break; + + case XF_FLOATBAR_BUTTON_RESTORE: + bits = restore_bits; + break; + + case XF_FLOATBAR_BUTTON_MINIMIZE: + bits = minimize_bits; + break; + + case XF_FLOATBAR_BUTTON_LOCKED: + if (floatbar->locked) + bits = lock_bits; + else + bits = unlock_bits; + + break; + + default: + break; + } + + pattern = XCreateBitmapFromData(xfc->display, button->handle, (const char*)bits, + FLOATBAR_BUTTON_WIDTH, FLOATBAR_BUTTON_WIDTH); + + if (!(button->focus)) + XSetForeground(xfc->display, gc, + xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_BACKGROUND)); + else + XSetForeground(xfc->display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_BORDER)); + + XSetBackground(xfc->display, gc, xf_floatbar_get_color(floatbar, FLOATBAR_COLOR_FOREGROUND)); + XCopyPlane(xfc->display, pattern, button->handle, gc, 0, 0, FLOATBAR_BUTTON_WIDTH, + FLOATBAR_BUTTON_WIDTH, 0, 0, 1); + XFreePixmap(xfc->display, pattern); + XFreeGC(xfc->display, gc); +} + +static void xf_floatbar_button_event_buttonpress(xfFloatbar* floatbar, const XButtonEvent* event) +{ + WINPR_ASSERT(event); + xfFloatbarButton* button = xf_floatbar_get_button(floatbar, event->window); + + if (button) + button->clicked = TRUE; +} + +static void xf_floatbar_button_event_buttonrelease(xfFloatbar* floatbar, const XButtonEvent* event) +{ + xfFloatbarButton* button = NULL; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + button = xf_floatbar_get_button(floatbar, event->window); + + if (button) + { + if (button->clicked) + button->onclick(floatbar); + button->clicked = FALSE; + } +} + +static void xf_floatbar_event_buttonpress(xfFloatbar* floatbar, const XButtonEvent* event) +{ + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + switch (event->button) + { + case Button1: + if (event->x <= FLOATBAR_BORDER) + floatbar->mode = XF_FLOATBAR_MODE_RESIZE_LEFT; + else if (event->x >= (floatbar->width - FLOATBAR_BORDER)) + floatbar->mode = XF_FLOATBAR_MODE_RESIZE_RIGHT; + else + floatbar->mode = XF_FLOATBAR_MODE_DRAGGING; + + break; + + default: + break; + } +} + +static void xf_floatbar_event_buttonrelease(xfFloatbar* floatbar, const XButtonEvent* event) +{ + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + switch (event->button) + { + case Button1: + floatbar->mode = XF_FLOATBAR_MODE_NONE; + break; + + default: + break; + } +} + +static void xf_floatbar_resize(xfFloatbar* floatbar, const XMotionEvent* event) +{ + int x = 0; + int width = 0; + int movement = 0; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + xfContext* xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + + /* calculate movement which happened on the root window */ + movement = event->x_root - floatbar->last_motion_x_root; + + /* set x and width depending if movement happens on the left or right */ + if (floatbar->mode == XF_FLOATBAR_MODE_RESIZE_LEFT) + { + x = floatbar->x + movement; + width = floatbar->width + movement * -1; + } + else + { + x = floatbar->x; + width = floatbar->width + movement; + } + + /* only resize and move window if still above minimum width */ + if (FLOATBAR_MIN_WIDTH < width) + { + XMoveResizeWindow(xfc->display, floatbar->handle, x, 0, + WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, floatbar->height)); + floatbar->x = x; + floatbar->width = width; + } +} + +static void xf_floatbar_dragging(xfFloatbar* floatbar, const XMotionEvent* event) +{ + int x = 0; + int movement = 0; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + xfContext* xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->window); + WINPR_ASSERT(xfc->display); + + /* calculate movement and new x position */ + movement = event->x_root - floatbar->last_motion_x_root; + x = floatbar->x + movement; + + /* do nothing if floatbar would be moved out of the window */ + if (x < 0 || (x + floatbar->width) > xfc->window->width) + return; + + /* move window to new x position */ + XMoveWindow(xfc->display, floatbar->handle, x, 0); + /* update struct values for the next event */ + floatbar->last_motion_x_root = floatbar->last_motion_x_root + movement; + floatbar->x = x; +} + +static void xf_floatbar_event_motionnotify(xfFloatbar* floatbar, const XMotionEvent* event) +{ + int mode = 0; + Cursor cursor = 0; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + xfContext* xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + + mode = floatbar->mode; + cursor = XCreateFontCursor(xfc->display, XC_arrow); + + if ((event->state & Button1Mask) && (mode > XF_FLOATBAR_MODE_DRAGGING)) + { + xf_floatbar_resize(floatbar, event); + } + else if ((event->state & Button1Mask) && (mode == XF_FLOATBAR_MODE_DRAGGING)) + { + xf_floatbar_dragging(floatbar, event); + } + else + { + if (event->x <= FLOATBAR_BORDER || event->x >= floatbar->width - FLOATBAR_BORDER) + cursor = XCreateFontCursor(xfc->display, XC_sb_h_double_arrow); + } + + XDefineCursor(xfc->display, xfc->window->handle, cursor); + XFreeCursor(xfc->display, cursor); + floatbar->last_motion_x_root = event->x_root; +} + +static void xf_floatbar_button_event_focusin(xfFloatbar* floatbar, const XAnyEvent* event) +{ + xfFloatbarButton* button = NULL; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + button = xf_floatbar_get_button(floatbar, event->window); + + if (button) + { + button->focus = TRUE; + xf_floatbar_button_event_expose(floatbar, event->window); + } +} + +static void xf_floatbar_button_event_focusout(xfFloatbar* floatbar, const XAnyEvent* event) +{ + xfFloatbarButton* button = NULL; + + WINPR_ASSERT(floatbar); + WINPR_ASSERT(event); + + button = xf_floatbar_get_button(floatbar, event->window); + + if (button) + { + button->focus = FALSE; + xf_floatbar_button_event_expose(floatbar, event->window); + } +} + +static void xf_floatbar_event_focusout(xfFloatbar* floatbar) +{ + WINPR_ASSERT(floatbar); + xfContext* xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + + if (xfc->pointer) + { + WINPR_ASSERT(xfc->window); + WINPR_ASSERT(xfc->pointer); + XDefineCursor(xfc->display, xfc->window->handle, xfc->pointer->cursor); + } +} + +BOOL xf_floatbar_check_event(xfFloatbar* floatbar, const XEvent* event) +{ + if (!floatbar || !floatbar->xfc || !event) + return FALSE; + + if (!floatbar->created) + return FALSE; + + if (event->xany.window == floatbar->handle) + return TRUE; + + size_t size = ARRAYSIZE(floatbar->buttons); + + for (size_t i = 0; i < size; i++) + { + const xfFloatbarButton* button = floatbar->buttons[i]; + + if (event->xany.window == button->handle) + return TRUE; + } + + return FALSE; +} + +BOOL xf_floatbar_event_process(xfFloatbar* floatbar, const XEvent* event) +{ + if (!floatbar || !floatbar->xfc || !event) + return FALSE; + + if (!floatbar->created) + return FALSE; + + switch (event->type) + { + case Expose: + if (event->xexpose.window == floatbar->handle) + xf_floatbar_event_expose(floatbar); + else + xf_floatbar_button_event_expose(floatbar, event->xexpose.window); + + break; + + case MotionNotify: + xf_floatbar_event_motionnotify(floatbar, &event->xmotion); + break; + + case ButtonPress: + if (event->xany.window == floatbar->handle) + xf_floatbar_event_buttonpress(floatbar, &event->xbutton); + else + xf_floatbar_button_event_buttonpress(floatbar, &event->xbutton); + + break; + + case ButtonRelease: + if (event->xany.window == floatbar->handle) + xf_floatbar_event_buttonrelease(floatbar, &event->xbutton); + else + xf_floatbar_button_event_buttonrelease(floatbar, &event->xbutton); + + break; + + case EnterNotify: + case FocusIn: + if (event->xany.window != floatbar->handle) + xf_floatbar_button_event_focusin(floatbar, &event->xany); + + break; + + case LeaveNotify: + case FocusOut: + if (event->xany.window == floatbar->handle) + xf_floatbar_event_focusout(floatbar); + else + xf_floatbar_button_event_focusout(floatbar, &event->xany); + + break; + + case ConfigureNotify: + if (event->xany.window == floatbar->handle) + xf_floatbar_button_update_positon(floatbar); + + break; + + case PropertyNotify: + if (event->xany.window == floatbar->handle) + xf_floatbar_button_update_positon(floatbar); + + break; + + default: + break; + } + + return floatbar->handle == event->xany.window; +} + +static void xf_floatbar_button_free(xfContext* xfc, xfFloatbarButton* button) +{ + if (!button) + return; + + if (button->handle) + { + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->display); + XUnmapWindow(xfc->display, button->handle); + XDestroyWindow(xfc->display, button->handle); + } + + free(button); +} + +void xf_floatbar_free(xfFloatbar* floatbar) +{ + size_t size = 0; + xfContext* xfc = NULL; + + if (!floatbar) + return; + + free(floatbar->title); + xfc = floatbar->xfc; + WINPR_ASSERT(xfc); + + size = ARRAYSIZE(floatbar->buttons); + + for (size_t i = 0; i < size; i++) + { + xf_floatbar_button_free(xfc, floatbar->buttons[i]); + floatbar->buttons[i] = NULL; + } + + if (floatbar->handle) + { + WINPR_ASSERT(xfc->display); + XUnmapWindow(xfc->display, floatbar->handle); + XDestroyWindow(xfc->display, floatbar->handle); + } + + free(floatbar); +} + +BOOL xf_floatbar_is_locked(xfFloatbar* floatbar) +{ + if (!floatbar) + return FALSE; + return floatbar->mode != XF_FLOATBAR_MODE_NONE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.h new file mode 100644 index 0000000000000000000000000000000000000000..f2e262ec7e0b4e36a53bc8ea50fa819bd718735f --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_floatbar.h @@ -0,0 +1,37 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Windows + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_FLOATBAR_H +#define FREERDP_CLIENT_X11_FLOATBAR_H + +typedef struct xf_floatbar xfFloatbar; + +#include "xfreerdp.h" + +void xf_floatbar_free(xfFloatbar* floatbar); + +WINPR_ATTR_MALLOC(xf_floatbar_free, 1) +xfFloatbar* xf_floatbar_new(xfContext* xfc, Window window, const char* title, DWORD flags); + +BOOL xf_floatbar_is_locked(xfFloatbar* floatbar); +BOOL xf_floatbar_event_process(xfFloatbar* floatbar, const XEvent* event); +BOOL xf_floatbar_check_event(xfFloatbar* floatbar, const XEvent* event); +BOOL xf_floatbar_toggle_fullscreen(xfFloatbar* floatbar, bool fullscreen); +BOOL xf_floatbar_hide_and_show(xfFloatbar* floatbar); +BOOL xf_floatbar_set_root_y(xfFloatbar* floatbar, int y); + +#endif /* FREERDP_CLIENT_X11_FLOATBAR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.c new file mode 100644 index 0000000000000000000000000000000000000000..bbd49c72681d06a69f856f602356e54ffeee71a0 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.c @@ -0,0 +1,491 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Graphics Pipeline + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2016 Armin Novak + * Copyright 2016 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include +#include "xf_gfx.h" +#include "xf_rail.h" + +#include + +#define TAG CLIENT_TAG("x11") + +static UINT xf_OutputUpdate(xfContext* xfc, xfGfxSurface* surface) +{ + UINT rc = ERROR_INTERNAL_ERROR; + UINT32 surfaceX = 0; + UINT32 surfaceY = 0; + RECTANGLE_16 surfaceRect = { 0 }; + UINT32 nbRects = 0; + const RECTANGLE_16* rects = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(surface); + + rdpGdi* gdi = xfc->common.context.gdi; + WINPR_ASSERT(gdi); + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + surfaceX = surface->gdi.outputOriginX; + surfaceY = surface->gdi.outputOriginY; + surfaceRect.left = 0; + surfaceRect.top = 0; + surfaceRect.right = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.mappedWidth); + surfaceRect.bottom = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.mappedHeight); + XSetClipMask(xfc->display, xfc->gc, None); + XSetFunction(xfc->display, xfc->gc, GXcopy); + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + region16_intersect_rect(&(surface->gdi.invalidRegion), &(surface->gdi.invalidRegion), + &surfaceRect); + + WINPR_ASSERT(surface->gdi.mappedWidth); + WINPR_ASSERT(surface->gdi.mappedHeight); + const double sx = 1.0 * surface->gdi.outputTargetWidth / (double)surface->gdi.mappedWidth; + const double sy = 1.0 * surface->gdi.outputTargetHeight / (double)surface->gdi.mappedHeight; + + if (!(rects = region16_rects(&surface->gdi.invalidRegion, &nbRects))) + return CHANNEL_RC_OK; + + for (UINT32 x = 0; x < nbRects; x++) + { + const RECTANGLE_16* rect = &rects[x]; + const UINT32 nXSrc = rect->left; + const UINT32 nYSrc = rect->top; + const UINT32 swidth = rect->right - nXSrc; + const UINT32 sheight = rect->bottom - nYSrc; + const UINT32 nXDst = (UINT32)lround(1.0 * surfaceX + nXSrc * sx); + const UINT32 nYDst = (UINT32)lround(1.0 * surfaceY + nYSrc * sy); + const UINT32 dwidth = (UINT32)lround(1.0 * swidth * sx); + const UINT32 dheight = (UINT32)lround(1.0 * sheight * sy); + + if (surface->stage) + { + if (!freerdp_image_scale(surface->stage, gdi->dstFormat, surface->stageScanline, nXSrc, + nYSrc, dwidth, dheight, surface->gdi.data, surface->gdi.format, + surface->gdi.scanline, nXSrc, nYSrc, swidth, sheight)) + goto fail; + } + + if (xfc->remote_app) + { + XPutImage(xfc->display, xfc->primary, xfc->gc, surface->image, + WINPR_ASSERTING_INT_CAST(int, nXSrc), WINPR_ASSERTING_INT_CAST(int, nYSrc), + WINPR_ASSERTING_INT_CAST(int, nXDst), WINPR_ASSERTING_INT_CAST(int, nYDst), + dwidth, dheight); + xf_lock_x11(xfc); + xf_rail_paint_surface(xfc, surface->gdi.windowId, rect); + xf_unlock_x11(xfc); + } + else +#ifdef WITH_XRENDER + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures)) + { + XPutImage(xfc->display, xfc->primary, xfc->gc, surface->image, + WINPR_ASSERTING_INT_CAST(int, nXSrc), WINPR_ASSERTING_INT_CAST(int, nYSrc), + WINPR_ASSERTING_INT_CAST(int, nXDst), WINPR_ASSERTING_INT_CAST(int, nYDst), + dwidth, dheight); + xf_draw_screen(xfc, WINPR_ASSERTING_INT_CAST(int32_t, nXDst), + WINPR_ASSERTING_INT_CAST(int32_t, nYDst), + WINPR_ASSERTING_INT_CAST(int32_t, dwidth), + WINPR_ASSERTING_INT_CAST(int32_t, dheight)); + } + else +#endif + { + XPutImage(xfc->display, xfc->drawable, xfc->gc, surface->image, + WINPR_ASSERTING_INT_CAST(int, nXSrc), WINPR_ASSERTING_INT_CAST(int, nYSrc), + WINPR_ASSERTING_INT_CAST(int, nXDst), WINPR_ASSERTING_INT_CAST(int, nYDst), + dwidth, dheight); + } + } + + rc = CHANNEL_RC_OK; +fail: + region16_clear(&surface->gdi.invalidRegion); + XSetClipMask(xfc->display, xfc->gc, None); + XSync(xfc->display, False); + return rc; +} + +static UINT xf_WindowUpdate(RdpgfxClientContext* context, xfGfxSurface* surface) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(surface); + return IFCALLRESULT(CHANNEL_RC_OK, context->UpdateWindowFromSurface, context, &surface->gdi); +} + +static UINT xf_UpdateSurfaces(RdpgfxClientContext* context) +{ + UINT16 count = 0; + UINT status = CHANNEL_RC_OK; + UINT16* pSurfaceIds = NULL; + rdpGdi* gdi = (rdpGdi*)context->custom; + xfContext* xfc = NULL; + + if (!gdi) + return status; + + if (gdi->suppressOutput) + return CHANNEL_RC_OK; + + xfc = (xfContext*)gdi->context; + EnterCriticalSection(&context->mux); + context->GetSurfaceIds(context, &pSurfaceIds, &count); + + for (UINT32 index = 0; index < count; index++) + { + xfGfxSurface* surface = (xfGfxSurface*)context->GetSurfaceData(context, pSurfaceIds[index]); + + if (!surface) + continue; + + /* If UpdateSurfaceArea callback is available, the output has already been updated. */ + if (context->UpdateSurfaceArea) + { + if (surface->gdi.handleInUpdateSurfaceArea) + continue; + } + + if (surface->gdi.outputMapped) + status = xf_OutputUpdate(xfc, surface); + else if (surface->gdi.windowMapped) + status = xf_WindowUpdate(context, surface); + + if (status != CHANNEL_RC_OK) + break; + } + + free(pSurfaceIds); + LeaveCriticalSection(&context->mux); + return status; +} + +UINT xf_OutputExpose(xfContext* xfc, UINT32 x, UINT32 y, UINT32 width, UINT32 height) +{ + UINT16 count = 0; + UINT status = ERROR_INTERNAL_ERROR; + RECTANGLE_16 invalidRect = { 0 }; + RECTANGLE_16 intersection = { 0 }; + UINT16* pSurfaceIds = NULL; + RdpgfxClientContext* context = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->common.context.gdi); + + context = xfc->common.context.gdi->gfx; + WINPR_ASSERT(context); + + invalidRect.left = WINPR_ASSERTING_INT_CAST(UINT16, x); + invalidRect.top = WINPR_ASSERTING_INT_CAST(UINT16, y); + invalidRect.right = WINPR_ASSERTING_INT_CAST(UINT16, x + width); + invalidRect.bottom = WINPR_ASSERTING_INT_CAST(UINT16, y + height); + status = context->GetSurfaceIds(context, &pSurfaceIds, &count); + + if (status != CHANNEL_RC_OK) + goto fail; + + if (!TryEnterCriticalSection(&context->mux)) + { + free(pSurfaceIds); + return CHANNEL_RC_OK; + } + for (UINT32 index = 0; index < count; index++) + { + RECTANGLE_16 surfaceRect = { 0 }; + xfGfxSurface* surface = (xfGfxSurface*)context->GetSurfaceData(context, pSurfaceIds[index]); + + if (!surface || (!surface->gdi.outputMapped && !surface->gdi.windowMapped)) + continue; + + surfaceRect.left = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.outputOriginX); + surfaceRect.top = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.outputOriginY); + surfaceRect.right = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.outputOriginX + + surface->gdi.outputTargetWidth); + surfaceRect.bottom = WINPR_ASSERTING_INT_CAST(UINT16, surface->gdi.outputOriginY + + surface->gdi.outputTargetHeight); + + if (rectangles_intersection(&invalidRect, &surfaceRect, &intersection)) + { + /* Invalid rects are specified relative to surface origin */ + intersection.left -= surfaceRect.left; + intersection.top -= surfaceRect.top; + intersection.right -= surfaceRect.left; + intersection.bottom -= surfaceRect.top; + region16_union_rect(&surface->gdi.invalidRegion, &surface->gdi.invalidRegion, + &intersection); + } + } + + free(pSurfaceIds); + LeaveCriticalSection(&context->mux); + IFCALLRET(context->UpdateSurfaces, status, context); + + if (status != CHANNEL_RC_OK) + goto fail; + +fail: + return status; +} + +static UINT32 x11_pad_scanline(UINT32 scanline, UINT32 inPad) +{ + /* Ensure X11 alignment is met */ + if (inPad > 0) + { + const UINT32 align = inPad / 8; + const UINT32 pad = align - scanline % align; + + if (align != pad) + scanline += pad; + } + + /* 16 byte alignment is required for ASM optimized code */ + if (scanline % 16) + scanline += 16 - scanline % 16; + + return scanline; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_CreateSurface(RdpgfxClientContext* context, + const RDPGFX_CREATE_SURFACE_PDU* createSurface) +{ + UINT ret = CHANNEL_RC_NO_MEMORY; + size_t size = 0; + xfGfxSurface* surface = NULL; + rdpGdi* gdi = (rdpGdi*)context->custom; + xfContext* xfc = (xfContext*)gdi->context; + surface = (xfGfxSurface*)calloc(1, sizeof(xfGfxSurface)); + + if (!surface) + return CHANNEL_RC_NO_MEMORY; + + surface->gdi.codecs = context->codecs; + + if (!surface->gdi.codecs) + { + WLog_ERR(TAG, "global GDI codecs aren't set"); + goto out_free; + } + + surface->gdi.surfaceId = createSurface->surfaceId; + surface->gdi.width = x11_pad_scanline(createSurface->width, 0); + surface->gdi.height = x11_pad_scanline(createSurface->height, 0); + surface->gdi.mappedWidth = createSurface->width; + surface->gdi.mappedHeight = createSurface->height; + surface->gdi.outputTargetWidth = createSurface->width; + surface->gdi.outputTargetHeight = createSurface->height; + + switch (createSurface->pixelFormat) + { + case GFX_PIXEL_FORMAT_ARGB_8888: + surface->gdi.format = PIXEL_FORMAT_BGRA32; + break; + + case GFX_PIXEL_FORMAT_XRGB_8888: + surface->gdi.format = PIXEL_FORMAT_BGRX32; + break; + + default: + WLog_ERR(TAG, "unknown pixelFormat 0x%" PRIx32 "", createSurface->pixelFormat); + ret = ERROR_INTERNAL_ERROR; + goto out_free; + } + + surface->gdi.scanline = surface->gdi.width * FreeRDPGetBytesPerPixel(surface->gdi.format); + surface->gdi.scanline = x11_pad_scanline(surface->gdi.scanline, + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->scanline_pad)); + size = 1ull * surface->gdi.scanline * surface->gdi.height; + surface->gdi.data = (BYTE*)winpr_aligned_malloc(size, 16); + + if (!surface->gdi.data) + { + WLog_ERR(TAG, "unable to allocate GDI data"); + goto out_free; + } + + ZeroMemory(surface->gdi.data, size); + + if (FreeRDPAreColorFormatsEqualNoAlpha(gdi->dstFormat, surface->gdi.format)) + { + WINPR_ASSERT(xfc->depth != 0); + surface->image = XCreateImage( + xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), ZPixmap, 0, + (char*)surface->gdi.data, surface->gdi.mappedWidth, surface->gdi.mappedHeight, + xfc->scanline_pad, WINPR_ASSERTING_INT_CAST(int, surface->gdi.scanline)); + } + else + { + UINT32 width = surface->gdi.width; + UINT32 bytes = FreeRDPGetBytesPerPixel(gdi->dstFormat); + surface->stageScanline = width * bytes; + surface->stageScanline = x11_pad_scanline( + surface->stageScanline, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->scanline_pad)); + size = 1ull * surface->stageScanline * surface->gdi.height; + surface->stage = (BYTE*)winpr_aligned_malloc(size, 16); + + if (!surface->stage) + { + WLog_ERR(TAG, "unable to allocate stage buffer"); + goto out_free_gdidata; + } + + ZeroMemory(surface->stage, size); + WINPR_ASSERT(xfc->depth != 0); + surface->image = XCreateImage( + xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), ZPixmap, 0, + (char*)surface->stage, surface->gdi.mappedWidth, surface->gdi.mappedHeight, + xfc->scanline_pad, WINPR_ASSERTING_INT_CAST(int, surface->stageScanline)); + } + + if (!surface->image) + { + WLog_ERR(TAG, "an error occurred when creating the XImage"); + goto error_surface_image; + } + + surface->image->byte_order = LSBFirst; + surface->image->bitmap_bit_order = LSBFirst; + + region16_init(&surface->gdi.invalidRegion); + + if (context->SetSurfaceData(context, surface->gdi.surfaceId, (void*)surface) != CHANNEL_RC_OK) + { + WLog_ERR(TAG, "an error occurred during SetSurfaceData"); + goto error_set_surface_data; + } + + return CHANNEL_RC_OK; +error_set_surface_data: + surface->image->data = NULL; + XDestroyImage(surface->image); +error_surface_image: + winpr_aligned_free(surface->stage); +out_free_gdidata: + winpr_aligned_free(surface->gdi.data); +out_free: + free(surface); + return ret; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_DeleteSurface(RdpgfxClientContext* context, + const RDPGFX_DELETE_SURFACE_PDU* deleteSurface) +{ + rdpCodecs* codecs = NULL; + xfGfxSurface* surface = NULL; + UINT status = 0; + EnterCriticalSection(&context->mux); + surface = (xfGfxSurface*)context->GetSurfaceData(context, deleteSurface->surfaceId); + + if (surface) + { + if (surface->gdi.windowMapped) + IFCALL(context->UnmapWindowForSurface, context, surface->gdi.windowId); + +#ifdef WITH_GFX_H264 + h264_context_free(surface->gdi.h264); +#endif + surface->image->data = NULL; + XDestroyImage(surface->image); + winpr_aligned_free(surface->gdi.data); + winpr_aligned_free(surface->stage); + region16_uninit(&surface->gdi.invalidRegion); + codecs = surface->gdi.codecs; + free(surface); + } + + status = context->SetSurfaceData(context, deleteSurface->surfaceId, NULL); + + if (codecs && codecs->progressive) + progressive_delete_surface_context(codecs->progressive, deleteSurface->surfaceId); + + LeaveCriticalSection(&context->mux); + return status; +} + +static UINT xf_UpdateWindowFromSurface(RdpgfxClientContext* context, gdiGfxSurface* surface) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(surface); + + rdpGdi* gdi = (rdpGdi*)context->custom; + WINPR_ASSERT(gdi); + + xfContext* xfc = (xfContext*)gdi->context; + WINPR_ASSERT(gdi->context); + + if (freerdp_settings_get_bool(gdi->context->settings, FreeRDP_RemoteApplicationMode)) + return xf_AppUpdateWindowFromSurface(xfc, surface); + + WLog_WARN(TAG, "function not implemented"); + return CHANNEL_RC_OK; +} + +void xf_graphics_pipeline_init(xfContext* xfc, RdpgfxClientContext* gfx) +{ + rdpGdi* gdi = NULL; + const rdpSettings* settings = NULL; + WINPR_ASSERT(xfc); + WINPR_ASSERT(gfx); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + gdi = xfc->common.context.gdi; + + gdi_graphics_pipeline_init(gdi, gfx); + + if (!freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)) + { + gfx->UpdateSurfaces = xf_UpdateSurfaces; + gfx->CreateSurface = xf_CreateSurface; + gfx->DeleteSurface = xf_DeleteSurface; + } + gfx->UpdateWindowFromSurface = xf_UpdateWindowFromSurface; +} + +void xf_graphics_pipeline_uninit(xfContext* xfc, RdpgfxClientContext* gfx) +{ + rdpGdi* gdi = NULL; + + WINPR_ASSERT(xfc); + + gdi = xfc->common.context.gdi; + gdi_graphics_pipeline_uninit(gdi, gfx); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.h new file mode 100644 index 0000000000000000000000000000000000000000..934e85a0b52eb965cba7c5c5604dae365dbb5755 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_gfx.h @@ -0,0 +1,45 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Graphics Pipeline + * + * Copyright 2014 Marc-Andre Moreau + * Copyright 2016 Thincast Technologies GmbH + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_GFX_H +#define FREERDP_CLIENT_X11_GFX_H + +#include "xf_client.h" +#include "xfreerdp.h" + +#include + +struct xf_gfx_surface +{ + gdiGfxSurface gdi; + BYTE* stage; + UINT32 stageScanline; + XImage* image; +}; +typedef struct xf_gfx_surface xfGfxSurface; + +UINT xf_OutputExpose(xfContext* xfc, UINT32 x, UINT32 y, UINT32 width, UINT32 height); + +void xf_graphics_pipeline_init(xfContext* xfc, RdpgfxClientContext* gfx); + +void xf_graphics_pipeline_uninit(xfContext* xfc, RdpgfxClientContext* gfx); + +#endif /* FREERDP_CLIENT_X11_GFX_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.c new file mode 100644 index 0000000000000000000000000000000000000000..658b73430f8e577747a89f91f539b19a0c6ec5c6 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.c @@ -0,0 +1,534 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Graphical Objects + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2016 Thincast Technologies GmbH + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#ifdef WITH_XCURSOR +#include +#endif + +#include +#include + +#include +#include + +#include +#include + +#include "xf_graphics.h" +#include "xf_event.h" + +#include +#define TAG CLIENT_TAG("x11") + +static BOOL xf_Pointer_Set(rdpContext* context, rdpPointer* pointer); + +BOOL xf_decode_color(xfContext* xfc, const UINT32 srcColor, XColor* color) +{ + UINT32 SrcFormat = 0; + BYTE r = 0; + BYTE g = 0; + BYTE b = 0; + BYTE a = 0; + + if (!xfc || !color) + return FALSE; + + rdpGdi* gdi = xfc->common.context.gdi; + + if (!gdi) + return FALSE; + + rdpSettings* settings = xfc->common.context.settings; + + if (!settings) + return FALSE; + + switch (freerdp_settings_get_uint32(settings, FreeRDP_ColorDepth)) + { + case 32: + case 24: + SrcFormat = PIXEL_FORMAT_BGR24; + break; + + case 16: + SrcFormat = PIXEL_FORMAT_RGB16; + break; + + case 15: + SrcFormat = PIXEL_FORMAT_RGB15; + break; + + case 8: + SrcFormat = PIXEL_FORMAT_RGB8; + break; + + default: + return FALSE; + } + + FreeRDPSplitColor(srcColor, SrcFormat, &r, &g, &b, &a, &gdi->palette); + color->blue = (unsigned short)(b << 8); + color->green = (unsigned short)(g << 8); + color->red = (unsigned short)(r << 8); + color->flags = DoRed | DoGreen | DoBlue; + + if (XAllocColor(xfc->display, xfc->colormap, color) == 0) + return FALSE; + + return TRUE; +} + +static BOOL xf_Pointer_GetCursorForCurrentScale(rdpContext* context, rdpPointer* pointer, + Cursor* cursor) +{ +#if defined(WITH_XCURSOR) && defined(WITH_XRENDER) + xfContext* xfc = (xfContext*)context; + xfPointer* xpointer = (xfPointer*)pointer; + XcursorImage ci = { 0 }; + int cursorIndex = -1; + + if (!context || !pointer || !context->gdi) + return FALSE; + + rdpSettings* settings = xfc->common.context.settings; + + if (!settings) + return FALSE; + + const double dw = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + const double xscale = + (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) ? 1.0 * xfc->scaledWidth / dw + : 1); + const double dh = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + const double yscale = + (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) ? 1.0 * xfc->scaledHeight / dh + : 1); + const UINT32 xTargetSize = MAX(1, (UINT32)lround(1.0 * pointer->width * xscale)); + const UINT32 yTargetSize = MAX(1, (UINT32)lround(1.0 * pointer->height * yscale)); + + WLog_DBG(TAG, "scaled: %" PRIu32 "x%" PRIu32 ", desktop: %" PRIu32 "x%" PRIu32, + xfc->scaledWidth, xfc->scaledHeight, + freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth), + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)); + for (UINT32 i = 0; i < xpointer->nCursors; i++) + { + if ((xpointer->cursorWidths[i] == xTargetSize) && + (xpointer->cursorHeights[i] == yTargetSize)) + { + cursorIndex = WINPR_ASSERTING_INT_CAST(int, i); + } + } + + if (cursorIndex == -1) + { + UINT32 CursorFormat = 0; + xf_lock_x11(xfc); + + if (!xfc->invert) + CursorFormat = (!xfc->big_endian) ? PIXEL_FORMAT_RGBA32 : PIXEL_FORMAT_ABGR32; + else + CursorFormat = (!xfc->big_endian) ? PIXEL_FORMAT_BGRA32 : PIXEL_FORMAT_ARGB32; + + if (xpointer->nCursors == xpointer->mCursors) + { + void* tmp2 = NULL; + xpointer->mCursors = (xpointer->mCursors == 0 ? 1 : xpointer->mCursors * 2); + + tmp2 = realloc(xpointer->cursorWidths, sizeof(UINT32) * xpointer->mCursors); + if (!tmp2) + { + xf_unlock_x11(xfc); + return FALSE; + } + xpointer->cursorWidths = tmp2; + + tmp2 = realloc(xpointer->cursorHeights, sizeof(UINT32) * xpointer->mCursors); + if (!tmp2) + { + xf_unlock_x11(xfc); + return FALSE; + } + xpointer->cursorHeights = (UINT32*)tmp2; + + tmp2 = realloc(xpointer->cursors, sizeof(Cursor) * xpointer->mCursors); + if (!tmp2) + { + xf_unlock_x11(xfc); + return FALSE; + } + xpointer->cursors = (Cursor*)tmp2; + } + + ci.version = XCURSOR_IMAGE_VERSION; + ci.size = sizeof(ci); + ci.width = xTargetSize; + ci.height = yTargetSize; + ci.xhot = (XcursorDim)lround(1.0 * pointer->xPos * xscale); + ci.yhot = (XcursorDim)lround(1.0 * pointer->yPos * yscale); + const size_t size = 1ull * ci.height * ci.width * FreeRDPGetBytesPerPixel(CursorFormat); + + void* tmp = winpr_aligned_malloc(size, 16); + if (!tmp) + { + xf_unlock_x11(xfc); + return FALSE; + } + ci.pixels = (XcursorPixel*)tmp; + + const double xs = fabs(fabs(xscale) - 1.0); + const double ys = fabs(fabs(yscale) - 1.0); + + WLog_DBG(TAG, + "cursorIndex %" PRId32 " scaling pointer %" PRIu32 "x%" PRIu32 " --> %" PRIu32 + "x%" PRIu32 " [%lfx%lf]", + cursorIndex, pointer->width, pointer->height, ci.width, ci.height, xscale, yscale); + if ((xs > DBL_EPSILON) || (ys > DBL_EPSILON)) + { + if (!freerdp_image_scale((BYTE*)ci.pixels, CursorFormat, 0, 0, 0, ci.width, ci.height, + (BYTE*)xpointer->cursorPixels, CursorFormat, 0, 0, 0, + pointer->width, pointer->height)) + { + winpr_aligned_free(tmp); + xf_unlock_x11(xfc); + return FALSE; + } + } + else + { + ci.pixels = xpointer->cursorPixels; + } + + const size_t idx = xpointer->nCursors; + xpointer->cursorWidths[idx] = ci.width; + xpointer->cursorHeights[idx] = ci.height; + xpointer->cursors[idx] = XcursorImageLoadCursor(xfc->display, &ci); + cursorIndex = WINPR_ASSERTING_INT_CAST(int, idx); + xpointer->nCursors += 1; + + winpr_aligned_free(tmp); + + xf_unlock_x11(xfc); + } + else + { + WLog_DBG(TAG, "using cached cursor %" PRId32, cursorIndex); + } + + cursor[0] = xpointer->cursors[cursorIndex]; +#endif + return TRUE; +} + +/* Pointer Class */ +static Window xf_Pointer_get_window(xfContext* xfc) +{ + if (!xfc) + { + WLog_WARN(TAG, "xf_Pointer: Invalid context"); + return 0; + } + if (xfc->remote_app) + { + if (!xfc->appWindow) + { + WLog_WARN(TAG, "xf_Pointer: Invalid appWindow"); + return 0; + } + return xfc->appWindow->handle; + } + else + { + if (!xfc->window) + { + WLog_WARN(TAG, "xf_Pointer: Invalid window"); + return 0; + } + return xfc->window->handle; + } +} + +BOOL xf_pointer_update_scale(xfContext* xfc) +{ + xfPointer* pointer = NULL; + WINPR_ASSERT(xfc); + + pointer = xfc->pointer; + if (!pointer) + return TRUE; + + return xf_Pointer_Set(&xfc->common.context, &xfc->pointer->pointer); +} + +static BOOL xf_Pointer_New(rdpContext* context, rdpPointer* pointer) +{ + BOOL rc = FALSE; + +#ifdef WITH_XCURSOR + UINT32 CursorFormat = 0; + size_t size = 0; + xfContext* xfc = (xfContext*)context; + xfPointer* xpointer = (xfPointer*)pointer; + + if (!context || !pointer || !context->gdi) + goto fail; + + if (!xfc->invert) + CursorFormat = (!xfc->big_endian) ? PIXEL_FORMAT_RGBA32 : PIXEL_FORMAT_ABGR32; + else + CursorFormat = (!xfc->big_endian) ? PIXEL_FORMAT_BGRA32 : PIXEL_FORMAT_ARGB32; + + xpointer->nCursors = 0; + xpointer->mCursors = 0; + + size = 1ull * pointer->height * pointer->width * FreeRDPGetBytesPerPixel(CursorFormat); + + if (!(xpointer->cursorPixels = (XcursorPixel*)winpr_aligned_malloc(size, 16))) + goto fail; + + if (!freerdp_image_copy_from_pointer_data( + (BYTE*)xpointer->cursorPixels, CursorFormat, 0, 0, 0, pointer->width, pointer->height, + pointer->xorMaskData, pointer->lengthXorMask, pointer->andMaskData, + pointer->lengthAndMask, pointer->xorBpp, &context->gdi->palette)) + { + winpr_aligned_free(xpointer->cursorPixels); + goto fail; + } + +#endif + + rc = TRUE; + +fail: + WLog_DBG(TAG, "%p", rc ? pointer : NULL); + return rc; +} + +static void xf_Pointer_Free(rdpContext* context, rdpPointer* pointer) +{ + WLog_DBG(TAG, "%p", pointer); + +#ifdef WITH_XCURSOR + xfContext* xfc = (xfContext*)context; + xfPointer* xpointer = (xfPointer*)pointer; + + xf_lock_x11(xfc); + + winpr_aligned_free(xpointer->cursorPixels); + free(xpointer->cursorWidths); + free(xpointer->cursorHeights); + + for (UINT32 i = 0; i < xpointer->nCursors; i++) + { + XFreeCursor(xfc->display, xpointer->cursors[i]); + } + + free(xpointer->cursors); + xpointer->nCursors = 0; + xpointer->mCursors = 0; + + xf_unlock_x11(xfc); +#endif +} + +static BOOL xf_Pointer_Set(rdpContext* context, rdpPointer* pointer) +{ + WLog_DBG(TAG, "%p", pointer); +#ifdef WITH_XCURSOR + xfContext* xfc = (xfContext*)context; + Window handle = xf_Pointer_get_window(xfc); + + WINPR_ASSERT(xfc); + WINPR_ASSERT(pointer); + + xfc->pointer = (xfPointer*)pointer; + + /* in RemoteApp mode, window can be null if none has had focus */ + + if (handle) + { + if (!xf_Pointer_GetCursorForCurrentScale(context, pointer, &(xfc->pointer->cursor))) + return FALSE; + xf_lock_x11(xfc); + XDefineCursor(xfc->display, handle, xfc->pointer->cursor); + xf_unlock_x11(xfc); + } + else + { + WLog_WARN(TAG, "handle=%ld", handle); + } +#endif + return TRUE; +} + +static BOOL xf_Pointer_SetNull(rdpContext* context) +{ + WLog_DBG(TAG, "called"); +#ifdef WITH_XCURSOR + xfContext* xfc = (xfContext*)context; + static Cursor nullcursor = None; + Window handle = xf_Pointer_get_window(xfc); + xf_lock_x11(xfc); + + if (nullcursor == None) + { + XcursorImage ci = { 0 }; + XcursorPixel xp = 0; + + ci.version = XCURSOR_IMAGE_VERSION; + ci.size = sizeof(ci); + ci.width = ci.height = 1; + ci.xhot = ci.yhot = 0; + ci.pixels = &xp; + nullcursor = XcursorImageLoadCursor(xfc->display, &ci); + } + + xfc->pointer = NULL; + + if ((handle) && (nullcursor != None)) + XDefineCursor(xfc->display, handle, nullcursor); + + xf_unlock_x11(xfc); +#endif + return TRUE; +} + +static BOOL xf_Pointer_SetDefault(rdpContext* context) +{ + WLog_DBG(TAG, "called"); +#ifdef WITH_XCURSOR + xfContext* xfc = (xfContext*)context; + Window handle = xf_Pointer_get_window(xfc); + xf_lock_x11(xfc); + xfc->pointer = NULL; + + if (handle) + XUndefineCursor(xfc->display, handle); + + xf_unlock_x11(xfc); +#endif + return TRUE; +} + +static BOOL xf_Pointer_SetPosition(rdpContext* context, UINT32 x, UINT32 y) +{ + xfContext* xfc = (xfContext*)context; + XWindowAttributes current = { 0 }; + XSetWindowAttributes tmp = { 0 }; + BOOL ret = FALSE; + Status rc = 0; + Window handle = xf_Pointer_get_window(xfc); + + if (!handle) + { + WLog_WARN(TAG, "focus %d, handle%lu", xfc->focused, handle); + return TRUE; + } + + WLog_DBG(TAG, "%" PRIu32 "x%" PRIu32, x, y); + if (!xfc->focused) + return TRUE; + + xf_adjust_coordinates_to_screen(xfc, &x, &y); + + xf_lock_x11(xfc); + + rc = XGetWindowAttributes(xfc->display, handle, ¤t); + if (rc == 0) + { + WLog_WARN(TAG, "XGetWindowAttributes==%d", rc); + goto out; + } + + tmp.event_mask = (current.your_event_mask & ~(PointerMotionMask)); + + rc = XChangeWindowAttributes(xfc->display, handle, CWEventMask, &tmp); + if (rc == 0) + { + WLog_WARN(TAG, "XChangeWindowAttributes==%d", rc); + goto out; + } + + rc = XWarpPointer(xfc->display, handle, handle, 0, 0, 0, 0, WINPR_ASSERTING_INT_CAST(int, x), + WINPR_ASSERTING_INT_CAST(int, y)); + if (rc == 0) + WLog_WARN(TAG, "XWarpPointer==%d", rc); + tmp.event_mask = current.your_event_mask; + rc = XChangeWindowAttributes(xfc->display, handle, CWEventMask, &tmp); + if (rc == 0) + WLog_WARN(TAG, "2.try XChangeWindowAttributes==%d", rc); + ret = TRUE; +out: + xf_unlock_x11(xfc); + return ret; +} + +/* Graphics Module */ +BOOL xf_register_pointer(rdpGraphics* graphics) +{ + rdpPointer pointer = { 0 }; + + pointer.size = sizeof(xfPointer); + pointer.New = xf_Pointer_New; + pointer.Free = xf_Pointer_Free; + pointer.Set = xf_Pointer_Set; + pointer.SetNull = xf_Pointer_SetNull; + pointer.SetDefault = xf_Pointer_SetDefault; + pointer.SetPosition = xf_Pointer_SetPosition; + graphics_register_pointer(graphics, &pointer); + return TRUE; +} + +UINT32 xf_get_local_color_format(xfContext* xfc, BOOL aligned) +{ + UINT32 DstFormat = 0; + BOOL invert = FALSE; + + if (!xfc) + return 0; + + invert = xfc->invert; + + WINPR_ASSERT(xfc->depth != 0); + if (xfc->depth == 32) + DstFormat = (!invert) ? PIXEL_FORMAT_RGBA32 : PIXEL_FORMAT_BGRA32; + else if (xfc->depth == 30) + DstFormat = (!invert) ? PIXEL_FORMAT_RGBX32_DEPTH30 : PIXEL_FORMAT_BGRX32_DEPTH30; + else if (xfc->depth == 24) + { + if (aligned) + DstFormat = (!invert) ? PIXEL_FORMAT_RGBX32 : PIXEL_FORMAT_BGRX32; + else + DstFormat = (!invert) ? PIXEL_FORMAT_RGB24 : PIXEL_FORMAT_BGR24; + } + else if (xfc->depth == 16) + DstFormat = PIXEL_FORMAT_RGB16; + else if (xfc->depth == 15) + DstFormat = PIXEL_FORMAT_RGB15; + else + DstFormat = (!invert) ? PIXEL_FORMAT_RGBX32 : PIXEL_FORMAT_BGRX32; + + return DstFormat; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.h new file mode 100644 index 0000000000000000000000000000000000000000..a194f43b2b93a4c6b336d886c22a2d16836828ad --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_graphics.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Graphical Objects + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_GRAPHICS_H +#define FREERDP_CLIENT_X11_GRAPHICS_H + +#include "xf_client.h" +#include "xfreerdp.h" + +BOOL xf_register_pointer(rdpGraphics* graphics); + +BOOL xf_decode_color(xfContext* xfc, const UINT32 srcColor, XColor* color); +UINT32 xf_get_local_color_format(xfContext* xfc, BOOL aligned); + +BOOL xf_pointer_update_scale(xfContext* xfc); + +#endif /* FREERDP_CLIENT_X11_GRAPHICS_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.c new file mode 100644 index 0000000000000000000000000000000000000000..7849c4f74fbe36fd92ba0d433efd7d824321241b --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.c @@ -0,0 +1,944 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Input + * + * Copyright 2013 Corey Clayton + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#ifdef WITH_XCURSOR +#include +#endif + +#ifdef WITH_XI +#include +#endif + +#include +#include +#include + +#include "xf_event.h" +#include "xf_input.h" +#include "xf_utils.h" + +#include +#include +#include +#define TAG CLIENT_TAG("x11") + +#ifdef WITH_XI + +#define PAN_THRESHOLD 50 +#define ZOOM_THRESHOLD 10 + +#define MIN_FINGER_DIST 5 + +static int xf_input_event(xfContext* xfc, const XEvent* xevent, XIDeviceEvent* event, int evtype); + +#ifdef DEBUG_XINPUT +static const char* xf_input_get_class_string(int class) +{ + if (class == XIKeyClass) + return "XIKeyClass"; + else if (class == XIButtonClass) + return "XIButtonClass"; + else if (class == XIValuatorClass) + return "XIValuatorClass"; + else if (class == XIScrollClass) + return "XIScrollClass"; + else if (class == XITouchClass) + return "XITouchClass"; + + return "XIUnknownClass"; +} +#endif + +static BOOL register_input_events(xfContext* xfc, Window window) +{ +#define MAX_NR_MASKS 64 + int ndevices = 0; + int nmasks = 0; + XIEventMask evmasks[MAX_NR_MASKS] = { 0 }; + BYTE masks[MAX_NR_MASKS][XIMaskLen(XI_LASTEVENT)] = { 0 }; + + WINPR_ASSERT(xfc); + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + XIDeviceInfo* info = XIQueryDevice(xfc->display, XIAllDevices, &ndevices); + + for (int i = 0; i < MIN(ndevices, MAX_NR_MASKS); i++) + { + BOOL used = FALSE; + XIDeviceInfo* dev = &info[i]; + + evmasks[nmasks].mask = masks[nmasks]; + evmasks[nmasks].mask_len = sizeof(masks[0]); + evmasks[nmasks].deviceid = dev->deviceid; + + /* Ignore virtual core pointer */ + if (strcmp(dev->name, "Virtual core pointer") == 0) + continue; + + for (int j = 0; j < dev->num_classes; j++) + { + const XIAnyClassInfo* class = dev->classes[j]; + + switch (class->type) + { + case XITouchClass: + if (freerdp_settings_get_bool(settings, FreeRDP_MultiTouchInput)) + { + const XITouchClassInfo* t = (const XITouchClassInfo*)class; + if (t->mode == XIDirectTouch) + { + WLog_DBG( + TAG, + "%s %s touch device (id: %d, mode: %d), supporting %d touches.", + dev->name, (t->mode == XIDirectTouch) ? "direct" : "dependent", + dev->deviceid, t->mode, t->num_touches); + XISetMask(masks[nmasks], XI_TouchBegin); + XISetMask(masks[nmasks], XI_TouchUpdate); + XISetMask(masks[nmasks], XI_TouchEnd); + } + } + break; + case XIButtonClass: + { + const XIButtonClassInfo* t = (const XIButtonClassInfo*)class; + WLog_DBG(TAG, "%s button device (id: %d, mode: %d)", dev->name, dev->deviceid, + t->num_buttons); + XISetMask(masks[nmasks], XI_ButtonPress); + XISetMask(masks[nmasks], XI_ButtonRelease); + XISetMask(masks[nmasks], XI_Motion); + used = TRUE; + break; + } + case XIValuatorClass: + { + static wLog* log = NULL; + if (!log) + log = WLog_Get(TAG); + + const XIValuatorClassInfo* t = (const XIValuatorClassInfo*)class; + char* name = t->label ? Safe_XGetAtomName(log, xfc->display, t->label) : NULL; + + WLog_Print(log, WLOG_DEBUG, + "%s device (id: %d) valuator %d label %s range %f - %f", dev->name, + dev->deviceid, t->number, name ? name : "None", t->min, t->max); + free(name); + + if (t->number == 2) + { + double max_pressure = t->max; + + char devName[200] = { 0 }; + strncpy(devName, dev->name, ARRAYSIZE(devName) - 1); + CharLowerBuffA(devName, ARRAYSIZE(devName)); + + if (strstr(devName, "eraser") != NULL) + { + if (freerdp_client_handle_pen(&xfc->common, + FREERDP_PEN_REGISTER | + FREERDP_PEN_IS_INVERTED | + FREERDP_PEN_HAS_PRESSURE, + dev->deviceid, max_pressure)) + WLog_DBG(TAG, "registered eraser"); + } + else if (strstr(devName, "stylus") != NULL || + strstr(devName, "pen") != NULL) + { + if (freerdp_client_handle_pen( + &xfc->common, FREERDP_PEN_REGISTER | FREERDP_PEN_HAS_PRESSURE, + dev->deviceid, max_pressure)) + WLog_DBG(TAG, "registered pen"); + } + } + break; + } + default: + break; + } + } + if (used) + nmasks++; + } + + XIFreeDeviceInfo(info); + + if (nmasks > 0) + { + Status xstatus = XISelectEvents(xfc->display, window, evmasks, nmasks); + if (xstatus != 0) + WLog_WARN(TAG, "XISelectEvents returned %d", xstatus); + } + + return TRUE; +} + +static BOOL register_raw_events(xfContext* xfc, Window window) +{ + XIEventMask mask; + unsigned char mask_bytes[XIMaskLen(XI_LASTEVENT)] = { 0 }; + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (freerdp_settings_get_bool(settings, FreeRDP_MouseUseRelativeMove)) + { + XISetMask(mask_bytes, XI_RawMotion); + XISetMask(mask_bytes, XI_RawButtonPress); + XISetMask(mask_bytes, XI_RawButtonRelease); + + mask.deviceid = XIAllMasterDevices; + mask.mask_len = sizeof(mask_bytes); + mask.mask = mask_bytes; + + XISelectEvents(xfc->display, window, &mask, 1); + } + + return TRUE; +} + +static BOOL register_device_events(xfContext* xfc, Window window) +{ + XIEventMask mask = { 0 }; + unsigned char mask_bytes[XIMaskLen(XI_LASTEVENT)] = { 0 }; + + WINPR_ASSERT(xfc); + + XISetMask(mask_bytes, XI_DeviceChanged); + XISetMask(mask_bytes, XI_HierarchyChanged); + + mask.deviceid = XIAllDevices; + mask.mask_len = sizeof(mask_bytes); + mask.mask = mask_bytes; + + XISelectEvents(xfc->display, window, &mask, 1); + + return TRUE; +} + +int xf_input_init(xfContext* xfc, Window window) +{ + int major = XI_2_Major; + int minor = XI_2_Minor; + int opcode = 0; + int event = 0; + int error = 0; + + WINPR_ASSERT(xfc); + + xfc->firstDist = -1.0; + xfc->z_vector = 0; + xfc->px_vector = 0; + xfc->py_vector = 0; + xfc->active_contacts = 0; + + if (!XQueryExtension(xfc->display, "XInputExtension", &opcode, &event, &error)) + { + WLog_WARN(TAG, "XInput extension not available."); + return -1; + } + + xfc->XInputOpcode = opcode; + XIQueryVersion(xfc->display, &major, &minor); + + if ((major < XI_2_Major) || ((major == XI_2_Major) && (minor < 2))) + { + WLog_WARN(TAG, "Server does not support XI 2.2"); + return -1; + } + else + { + int scr = DefaultScreen(xfc->display); + Window root = RootWindow(xfc->display, scr); + + if (!register_raw_events(xfc, root)) + return -1; + if (!register_input_events(xfc, window)) + return -1; + if (!register_device_events(xfc, window)) + return -1; + } + + return 0; +} + +static BOOL xf_input_is_duplicate(xfContext* xfc, const XGenericEventCookie* cookie) +{ + const XIDeviceEvent* event = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(cookie); + + event = cookie->data; + WINPR_ASSERT(event); + + if ((xfc->lastEvent.time == event->time) && (xfc->lastEvType == cookie->evtype) && + (xfc->lastEvent.detail == event->detail) && + (fabs(xfc->lastEvent.event_x - event->event_x) < DBL_EPSILON) && + (fabs(xfc->lastEvent.event_y - event->event_y) < DBL_EPSILON)) + { + return TRUE; + } + + return FALSE; +} + +static void xf_input_save_last_event(xfContext* xfc, const XGenericEventCookie* cookie) +{ + const XIDeviceEvent* event = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(cookie); + + event = cookie->data; + WINPR_ASSERT(event); + + xfc->lastEvType = cookie->evtype; + xfc->lastEvent.time = event->time; + xfc->lastEvent.detail = event->detail; + xfc->lastEvent.event_x = event->event_x; + xfc->lastEvent.event_y = event->event_y; +} + +static void xf_input_detect_pan(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + rdpContext* ctx = &xfc->common.context; + WINPR_ASSERT(ctx); + + if (xfc->active_contacts != 2) + { + return; + } + + const double dx[] = { xfc->contacts[0].pos_x - xfc->contacts[0].last_x, + xfc->contacts[1].pos_x - xfc->contacts[1].last_x }; + const double dy[] = { xfc->contacts[0].pos_y - xfc->contacts[0].last_y, + xfc->contacts[1].pos_y - xfc->contacts[1].last_y }; + const double px = fabs(dx[0]) < fabs(dx[1]) ? dx[0] : dx[1]; + const double py = fabs(dy[0]) < fabs(dy[1]) ? dy[0] : dy[1]; + xfc->px_vector += px; + xfc->py_vector += py; + const double dist_x = fabs(xfc->contacts[0].pos_x - xfc->contacts[1].pos_x); + const double dist_y = fabs(xfc->contacts[0].pos_y - xfc->contacts[1].pos_y); + + if (dist_y > MIN_FINGER_DIST) + { + if (xfc->px_vector > PAN_THRESHOLD) + { + { + PanningChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = 5; + e.dy = 0; + PubSub_OnPanningChange(ctx->pubSub, xfc, &e); + } + xfc->px_vector = 0; + xfc->py_vector = 0; + xfc->z_vector = 0; + } + else if (xfc->px_vector < -PAN_THRESHOLD) + { + { + PanningChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = -5; + e.dy = 0; + PubSub_OnPanningChange(ctx->pubSub, xfc, &e); + } + xfc->px_vector = 0; + xfc->py_vector = 0; + xfc->z_vector = 0; + } + } + + if (dist_x > MIN_FINGER_DIST) + { + if (xfc->py_vector > PAN_THRESHOLD) + { + { + PanningChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = 0; + e.dy = 5; + PubSub_OnPanningChange(ctx->pubSub, xfc, &e); + } + xfc->py_vector = 0; + xfc->px_vector = 0; + xfc->z_vector = 0; + } + else if (xfc->py_vector < -PAN_THRESHOLD) + { + { + PanningChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = 0; + e.dy = -5; + PubSub_OnPanningChange(ctx->pubSub, xfc, &e); + } + xfc->py_vector = 0; + xfc->px_vector = 0; + xfc->z_vector = 0; + } + } +} + +static void xf_input_detect_pinch(xfContext* xfc) +{ + ZoomingChangeEventArgs e = { 0 }; + + WINPR_ASSERT(xfc); + rdpContext* ctx = &xfc->common.context; + WINPR_ASSERT(ctx); + + if (xfc->active_contacts != 2) + { + xfc->firstDist = -1.0; + return; + } + + /* first calculate the distance */ + const double dist = sqrt(pow(xfc->contacts[1].pos_x - xfc->contacts[0].last_x, 2.0) + + pow(xfc->contacts[1].pos_y - xfc->contacts[0].last_y, 2.0)); + + /* if this is the first 2pt touch */ + if (xfc->firstDist <= 0) + { + xfc->firstDist = dist; + xfc->lastDist = xfc->firstDist; + xfc->z_vector = 0; + xfc->px_vector = 0; + xfc->py_vector = 0; + } + else + { + double delta = xfc->lastDist - dist; + + if (delta > 1.0) + delta = 1.0; + + if (delta < -1.0) + delta = -1.0; + + /* compare the current distance to the first one */ + xfc->z_vector += delta; + xfc->lastDist = dist; + + if (xfc->z_vector > ZOOM_THRESHOLD) + { + EventArgsInit(&e, "xfreerdp"); + e.dx = e.dy = -10; + PubSub_OnZoomingChange(ctx->pubSub, xfc, &e); + xfc->z_vector = 0; + xfc->px_vector = 0; + xfc->py_vector = 0; + } + + if (xfc->z_vector < -ZOOM_THRESHOLD) + { + EventArgsInit(&e, "xfreerdp"); + e.dx = e.dy = 10; + PubSub_OnZoomingChange(ctx->pubSub, xfc, &e); + xfc->z_vector = 0; + xfc->px_vector = 0; + xfc->py_vector = 0; + } + } +} + +static void xf_input_touch_begin(xfContext* xfc, const XIDeviceEvent* event) +{ + WINPR_UNUSED(xfc); + for (int i = 0; i < MAX_CONTACTS; i++) + { + if (xfc->contacts[i].id == 0) + { + xfc->contacts[i].id = event->detail; + xfc->contacts[i].count = 1; + xfc->contacts[i].pos_x = event->event_x; + xfc->contacts[i].pos_y = event->event_y; + xfc->active_contacts++; + break; + } + } +} + +static void xf_input_touch_update(xfContext* xfc, const XIDeviceEvent* event) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + for (int i = 0; i < MAX_CONTACTS; i++) + { + if (xfc->contacts[i].id == event->detail) + { + xfc->contacts[i].count++; + xfc->contacts[i].last_x = xfc->contacts[i].pos_x; + xfc->contacts[i].last_y = xfc->contacts[i].pos_y; + xfc->contacts[i].pos_x = event->event_x; + xfc->contacts[i].pos_y = event->event_y; + xf_input_detect_pinch(xfc); + xf_input_detect_pan(xfc); + break; + } + } +} + +static void xf_input_touch_end(xfContext* xfc, const XIDeviceEvent* event) +{ + WINPR_UNUSED(xfc); + for (int i = 0; i < MAX_CONTACTS; i++) + { + if (xfc->contacts[i].id == event->detail) + { + xfc->contacts[i].id = 0; + xfc->contacts[i].count = 0; + xfc->active_contacts--; + break; + } + } +} + +static int xf_input_handle_event_local(xfContext* xfc, const XEvent* event) +{ + union + { + const XGenericEventCookie* cc; + XGenericEventCookie* vc; + } cookie; + cookie.cc = &event->xcookie; + XGetEventData(xfc->display, cookie.vc); + + if ((cookie.cc->type == GenericEvent) && (cookie.cc->extension == xfc->XInputOpcode)) + { + switch (cookie.cc->evtype) + { + case XI_TouchBegin: + if (xf_input_is_duplicate(xfc, cookie.cc) == FALSE) + xf_input_touch_begin(xfc, cookie.cc->data); + + xf_input_save_last_event(xfc, cookie.cc); + break; + + case XI_TouchUpdate: + if (xf_input_is_duplicate(xfc, cookie.cc) == FALSE) + xf_input_touch_update(xfc, cookie.cc->data); + + xf_input_save_last_event(xfc, cookie.cc); + break; + + case XI_TouchEnd: + if (xf_input_is_duplicate(xfc, cookie.cc) == FALSE) + xf_input_touch_end(xfc, cookie.cc->data); + + xf_input_save_last_event(xfc, cookie.cc); + break; + + default: + xf_input_event(xfc, event, cookie.cc->data, cookie.cc->evtype); + break; + } + } + + XFreeEventData(xfc->display, cookie.vc); + return 0; +} + +#ifdef WITH_DEBUG_X11 +static char* xf_input_touch_state_string(DWORD flags) +{ + if (flags & RDPINPUT_CONTACT_FLAG_DOWN) + return "RDPINPUT_CONTACT_FLAG_DOWN"; + else if (flags & RDPINPUT_CONTACT_FLAG_UPDATE) + return "RDPINPUT_CONTACT_FLAG_UPDATE"; + else if (flags & RDPINPUT_CONTACT_FLAG_UP) + return "RDPINPUT_CONTACT_FLAG_UP"; + else if (flags & RDPINPUT_CONTACT_FLAG_INRANGE) + return "RDPINPUT_CONTACT_FLAG_INRANGE"; + else if (flags & RDPINPUT_CONTACT_FLAG_INCONTACT) + return "RDPINPUT_CONTACT_FLAG_INCONTACT"; + else if (flags & RDPINPUT_CONTACT_FLAG_CANCELED) + return "RDPINPUT_CONTACT_FLAG_CANCELED"; + else + return "RDPINPUT_CONTACT_FLAG_UNKNOWN"; +} +#endif + +static void xf_input_hide_cursor(xfContext* xfc) +{ +#ifdef WITH_XCURSOR + + if (!xfc->cursorHidden) + { + XcursorImage ci = { 0 }; + XcursorPixel xp = 0; + static Cursor nullcursor = None; + xf_lock_x11(xfc); + ci.version = XCURSOR_IMAGE_VERSION; + ci.size = sizeof(ci); + ci.width = ci.height = 1; + ci.xhot = ci.yhot = 0; + ci.pixels = &xp; + nullcursor = XcursorImageLoadCursor(xfc->display, &ci); + + if ((xfc->window) && (nullcursor != None)) + XDefineCursor(xfc->display, xfc->window->handle, nullcursor); + + xfc->cursorHidden = TRUE; + xf_unlock_x11(xfc); + } + +#endif +} + +static void xf_input_show_cursor(xfContext* xfc) +{ +#ifdef WITH_XCURSOR + xf_lock_x11(xfc); + + if (xfc->cursorHidden) + { + if (xfc->window) + { + if (!xfc->pointer) + XUndefineCursor(xfc->display, xfc->window->handle); + else + XDefineCursor(xfc->display, xfc->window->handle, xfc->pointer->cursor); + } + + xfc->cursorHidden = FALSE; + } + + xf_unlock_x11(xfc); +#endif +} + +static int xf_input_touch_remote(xfContext* xfc, XIDeviceEvent* event, int evtype) +{ + int x = 0; + int y = 0; + int touchId = 0; + RdpeiClientContext* rdpei = xfc->common.rdpei; + + if (!rdpei) + return 0; + + xf_input_hide_cursor(xfc); + touchId = event->detail; + x = (int)event->event_x; + y = (int)event->event_y; + xf_event_adjust_coordinates(xfc, &x, &y); + + switch (evtype) + { + case XI_TouchBegin: + freerdp_client_handle_touch(&xfc->common, FREERDP_TOUCH_DOWN, touchId, 0, x, y); + break; + case XI_TouchUpdate: + freerdp_client_handle_touch(&xfc->common, FREERDP_TOUCH_MOTION, touchId, 0, x, y); + break; + case XI_TouchEnd: + freerdp_client_handle_touch(&xfc->common, FREERDP_TOUCH_UP, touchId, 0, x, y); + break; + default: + break; + } + + return 0; +} + +static BOOL xf_input_pen_remote(xfContext* xfc, XIDeviceEvent* event, int evtype, int deviceid) +{ + int x = 0; + int y = 0; + RdpeiClientContext* rdpei = xfc->common.rdpei; + + if (!rdpei) + return FALSE; + + xf_input_hide_cursor(xfc); + x = (int)event->event_x; + y = (int)event->event_y; + xf_event_adjust_coordinates(xfc, &x, &y); + + double pressure = 0.0; + double* val = event->valuators.values; + for (int i = 0; i < MIN(event->valuators.mask_len * 8, 3); i++) + { + if (XIMaskIsSet(event->valuators.mask, i)) + { + double value = *val++; + if (i == 2) + pressure = value; + } + } + + UINT32 flags = FREERDP_PEN_HAS_PRESSURE; + if ((evtype == XI_ButtonPress) || (evtype == XI_ButtonRelease)) + { + WLog_DBG(TAG, "pen button %d", event->detail); + switch (event->detail) + { + case 1: + break; + case 3: + flags |= FREERDP_PEN_BARREL_PRESSED; + break; + default: + return FALSE; + } + } + + switch (evtype) + { + case XI_ButtonPress: + flags |= FREERDP_PEN_PRESS; + if (!freerdp_client_handle_pen(&xfc->common, flags, deviceid, x, y, pressure)) + return FALSE; + break; + case XI_Motion: + flags |= FREERDP_PEN_MOTION; + if (!freerdp_client_handle_pen(&xfc->common, flags, deviceid, x, y, pressure)) + return FALSE; + break; + case XI_ButtonRelease: + flags |= FREERDP_PEN_RELEASE; + if (!freerdp_client_handle_pen(&xfc->common, flags, deviceid, x, y, pressure)) + return FALSE; + break; + default: + break; + } + return TRUE; +} + +static int xf_input_pens_unhover(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + freerdp_client_pen_cancel_all(&xfc->common); + return 0; +} + +int xf_input_event(xfContext* xfc, const XEvent* xevent, XIDeviceEvent* event, int evtype) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(xevent); + WINPR_ASSERT(event); + + /* When not running RAILS we only care about events for this window. + * filter out anything else, like floatbar window events + */ + const Window w = xevent->xany.window; + + xfWindow* window = xfc->window; + if (window) + { + if (w != window->handle) + { + if (!xfc->remote_app) + return 0; + } + + if (xf_floatbar_is_locked(window->floatbar)) + return 0; + } + + xf_input_show_cursor(xfc); + + switch (evtype) + { + case XI_ButtonPress: + case XI_ButtonRelease: + xfc->xi_event = !xfc->common.mouse_grabbed || + !freerdp_client_use_relative_mouse_events(&xfc->common); + + if (xfc->xi_event) + { + xf_generic_ButtonEvent(xfc, (int)event->event_x, (int)event->event_y, event->detail, + event->event, xfc->remote_app, evtype == XI_ButtonPress); + } + break; + + case XI_Motion: + xfc->xi_event = !xfc->common.mouse_grabbed || + !freerdp_client_use_relative_mouse_events(&xfc->common); + + if (xfc->xi_event) + { + xf_generic_MotionNotify(xfc, (int)event->event_x, (int)event->event_y, + event->detail, event->event, xfc->remote_app); + } + break; + case XI_RawButtonPress: + case XI_RawButtonRelease: + xfc->xi_rawevent = + xfc->common.mouse_grabbed && freerdp_client_use_relative_mouse_events(&xfc->common); + + if (xfc->xi_rawevent) + { + const XIRawEvent* ev = (const XIRawEvent*)event; + xf_generic_RawButtonEvent(xfc, ev->detail, xfc->remote_app, + evtype == XI_RawButtonPress); + } + break; + case XI_RawMotion: + xfc->xi_rawevent = + xfc->common.mouse_grabbed && freerdp_client_use_relative_mouse_events(&xfc->common); + + if (xfc->xi_rawevent) + { + const XIRawEvent* ev = (const XIRawEvent*)event; + double x = 0.0; + double y = 0.0; + if (XIMaskIsSet(ev->valuators.mask, 0)) + x = ev->raw_values[0]; + if (XIMaskIsSet(ev->valuators.mask, 1)) + y = ev->raw_values[1]; + + xf_generic_RawMotionNotify(xfc, (int)x, (int)y, event->event, xfc->remote_app); + } + break; + case XI_DeviceChanged: + { + const XIDeviceChangedEvent* ev = (const XIDeviceChangedEvent*)event; + if (ev->reason != XIDeviceChange) + break; + + /* + * TODO: + * 1. Register only changed devices. + * 2. Both `XIDeviceChangedEvent` and `XIHierarchyEvent` have no target + * `Window` which is used to register xinput events. So assume + * `xfc->window` created by `xf_CreateDesktopWindow` is the same + * `Window` we registered. + */ + if (xfc->window) + register_input_events(xfc, xfc->window->handle); + } + break; + case XI_HierarchyChanged: + if (xfc->window) + register_input_events(xfc, xfc->window->handle); + break; + + default: + WLog_WARN(TAG, "Unhandled event %d: Event was registered but is not handled!", evtype); + break; + } + + return 0; +} + +static int xf_input_handle_event_remote(xfContext* xfc, const XEvent* event) +{ + union + { + const XGenericEventCookie* cc; + XGenericEventCookie* vc; + } cookie; + cookie.cc = &event->xcookie; + XGetEventData(xfc->display, cookie.vc); + + if ((cookie.cc->type == GenericEvent) && (cookie.cc->extension == xfc->XInputOpcode)) + { + switch (cookie.cc->evtype) + { + case XI_TouchBegin: + xf_input_pens_unhover(xfc); + /* fallthrough */ + WINPR_FALLTHROUGH + case XI_TouchUpdate: + case XI_TouchEnd: + xf_input_touch_remote(xfc, cookie.cc->data, cookie.cc->evtype); + break; + case XI_ButtonPress: + case XI_Motion: + case XI_ButtonRelease: + { + WLog_DBG(TAG, "checking for pen"); + XIDeviceEvent* deviceEvent = (XIDeviceEvent*)cookie.cc->data; + int deviceid = deviceEvent->deviceid; + + if (freerdp_client_is_pen(&xfc->common, deviceid)) + { + if (!xf_input_pen_remote(xfc, cookie.cc->data, cookie.cc->evtype, deviceid)) + { + // XXX: don't show cursor + xf_input_event(xfc, event, cookie.cc->data, cookie.cc->evtype); + } + break; + } + } + /* fallthrough */ + WINPR_FALLTHROUGH + default: + xf_input_pens_unhover(xfc); + xf_input_event(xfc, event, cookie.cc->data, cookie.cc->evtype); + break; + } + } + + XFreeEventData(xfc->display, cookie.vc); + return 0; +} + +#else + +int xf_input_init(xfContext* xfc, Window window) +{ + return 0; +} + +#endif + +int xf_input_handle_event(xfContext* xfc, const XEvent* event) +{ +#ifdef WITH_XI + const rdpSettings* settings = NULL; + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (freerdp_settings_get_bool(settings, FreeRDP_MultiTouchInput)) + { + return xf_input_handle_event_remote(xfc, event); + } + else if (freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures)) + { + return xf_input_handle_event_local(xfc, event); + } + else + { + return xf_input_handle_event_local(xfc, event); + } + +#else + return 0; +#endif +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.h new file mode 100644 index 0000000000000000000000000000000000000000..a961512b489ffdf9600fabbd9d086911fed8924d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_input.h @@ -0,0 +1,33 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Input + * + * Copyright 2013 Corey Clayton + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_INPUT_H +#define FREERDP_CLIENT_X11_INPUT_H + +#include "xf_client.h" +#include "xfreerdp.h" + +#ifdef WITH_XI +#include +#endif + +int xf_input_init(xfContext* xfc, Window window); +int xf_input_handle_event(xfContext* xfc, const XEvent* event); + +#endif /* FREERDP_CLIENT_X11_INPUT_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.c new file mode 100644 index 0000000000000000000000000000000000000000..72504be7b4d4d133dd4767436eb7b284da22b599 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.c @@ -0,0 +1,795 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Keyboard Handling + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include "xf_event.h" + +#include "xf_keyboard.h" + +#include "xf_utils.h" + +#include +#define TAG CLIENT_TAG("x11") + +typedef struct +{ + BOOL Shift; + BOOL LeftShift; + BOOL RightShift; + BOOL Alt; + BOOL LeftAlt; + BOOL RightAlt; + BOOL Ctrl; + BOOL LeftCtrl; + BOOL RightCtrl; + BOOL Super; + BOOL LeftSuper; + BOOL RightSuper; +} XF_MODIFIER_KEYS; + +static UINT32 xf_keyboard_get_toggle_keys_state(xfContext* xfc); +static BOOL xf_keyboard_handle_special_keys(xfContext* xfc, KeySym keysym); +static void xf_keyboard_handle_special_keys_release(xfContext* xfc, KeySym keysym); + +static void xf_keyboard_modifier_map_free(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + if (xfc->modifierMap) + { + XFreeModifiermap(xfc->modifierMap); + xfc->modifierMap = NULL; + } +} + +BOOL xf_keyboard_update_modifier_map(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + xf_keyboard_modifier_map_free(xfc); + xfc->modifierMap = XGetModifierMapping(xfc->display); + return xfc->modifierMap != NULL; +} + +static void xf_keyboard_send_key(xfContext* xfc, BOOL down, BOOL repeat, const XKeyEvent* ev); + +static BOOL xf_sync_kbd_state(xfContext* xfc) +{ + const UINT32 syncFlags = xf_keyboard_get_toggle_keys_state(xfc); + + WINPR_ASSERT(xfc); + return freerdp_input_send_synchronize_event(xfc->common.context.input, syncFlags); +} + +static void xf_keyboard_clear(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + ZeroMemory(xfc->KeyboardState, sizeof(xfc->KeyboardState)); +} + +static BOOL xf_action_script_append(xfContext* xfc, const char* buffer, size_t size, void* user, + const char* what, const char* arg) +{ + WINPR_ASSERT(xfc); + WINPR_UNUSED(what); + WINPR_UNUSED(arg); + + if (!buffer || (size == 0)) + return TRUE; + return ArrayList_Append(xfc->keyCombinations, buffer); +} + +static void xf_keyboard_action_script_free(xfContext* xfc) +{ + xf_event_action_script_free(xfc); + + if (xfc->keyCombinations) + { + ArrayList_Free(xfc->keyCombinations); + xfc->keyCombinations = NULL; + xfc->actionScriptExists = FALSE; + } +} + +BOOL xf_keyboard_action_script_init(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + xf_keyboard_action_script_free(xfc); + xfc->keyCombinations = ArrayList_New(TRUE); + + if (!xfc->keyCombinations) + return FALSE; + + wObject* obj = ArrayList_Object(xfc->keyCombinations); + WINPR_ASSERT(obj); + obj->fnObjectNew = winpr_ObjectStringClone; + obj->fnObjectFree = winpr_ObjectStringFree; + + if (!run_action_script(xfc, "key", NULL, xf_action_script_append, NULL)) + return FALSE; + + return xf_event_action_script_init(xfc); +} + +BOOL xf_keyboard_init(xfContext* xfc) +{ + rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + xf_keyboard_clear(xfc); + xfc->KeyboardLayout = freerdp_settings_get_uint32(settings, FreeRDP_KeyboardLayout); + xfc->KeyboardLayout = freerdp_keyboard_init_ex(xfc->KeyboardLayout, NULL); + if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardLayout, xfc->KeyboardLayout)) + return FALSE; + + return xf_keyboard_update_modifier_map(xfc); +} + +void xf_keyboard_free(xfContext* xfc) +{ + xf_keyboard_modifier_map_free(xfc); + xf_keyboard_action_script_free(xfc); +} + +void xf_keyboard_key_press(xfContext* xfc, const XKeyEvent* event, KeySym keysym) +{ + BOOL last = 0; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + WINPR_ASSERT(event->keycode < ARRAYSIZE(xfc->KeyboardState)); + + last = xfc->KeyboardState[event->keycode]; + xfc->KeyboardState[event->keycode] = TRUE; + + if (xf_keyboard_handle_special_keys(xfc, keysym)) + return; + + xf_keyboard_send_key(xfc, TRUE, last, event); +} + +void xf_keyboard_key_release(xfContext* xfc, const XKeyEvent* event, KeySym keysym) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + WINPR_ASSERT(event->keycode < ARRAYSIZE(xfc->KeyboardState)); + + BOOL last = xfc->KeyboardState[event->keycode]; + xfc->KeyboardState[event->keycode] = FALSE; + xf_keyboard_handle_special_keys_release(xfc, keysym); + xf_keyboard_send_key(xfc, FALSE, last, event); +} + +void xf_keyboard_release_all_keypress(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + WINPR_STATIC_ASSERT(ARRAYSIZE(xfc->KeyboardState) <= UINT32_MAX); + for (size_t keycode = 0; keycode < ARRAYSIZE(xfc->KeyboardState); keycode++) + { + if (xfc->KeyboardState[keycode]) + { + const DWORD rdp_scancode = + freerdp_keyboard_get_rdp_scancode_from_x11_keycode((UINT32)keycode); + + // release tab before releasing the windows key. + // this stops the start menu from opening on unfocus event. + if (rdp_scancode == RDP_SCANCODE_LWIN) + freerdp_input_send_keyboard_event_ex(xfc->common.context.input, FALSE, FALSE, + RDP_SCANCODE_TAB); + + freerdp_input_send_keyboard_event_ex(xfc->common.context.input, FALSE, FALSE, + rdp_scancode); + xfc->KeyboardState[keycode] = FALSE; + } + } + xf_sync_kbd_state(xfc); +} + +static BOOL xf_keyboard_key_pressed(xfContext* xfc, KeySym keysym) +{ + KeyCode keycode = XKeysymToKeycode(xfc->display, keysym); + WINPR_ASSERT(keycode < ARRAYSIZE(xfc->KeyboardState)); + return xfc->KeyboardState[keycode]; +} + +void xf_keyboard_send_key(xfContext* xfc, BOOL down, BOOL repeat, const XKeyEvent* event) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(event); + + rdpInput* input = xfc->common.context.input; + WINPR_ASSERT(input); + + const DWORD sc = freerdp_keyboard_get_rdp_scancode_from_x11_keycode(event->keycode); + const DWORD rdp_scancode = freerdp_keyboard_remap_key(xfc->remap_table, sc); + if (rdp_scancode == RDP_SCANCODE_PAUSE && !xf_keyboard_key_pressed(xfc, XK_Control_L) && + !xf_keyboard_key_pressed(xfc, XK_Control_R)) + { + /* Pause without Ctrl has to be sent as a series of keycodes + * in a single input PDU. Pause only happens on "press"; + * no code is sent on "release". + */ + if (down) + { + (void)freerdp_input_send_keyboard_pause_event(input); + } + } + else + { + if (freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_UnicodeInput)) + { + wchar_t buffer[32] = { 0 }; + int xwc = -1; + + switch (rdp_scancode) + { + case RDP_SCANCODE_RETURN: + break; + default: + { + XIM xim = XOpenIM(xfc->display, 0, 0, 0); + XIC xic = + XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, NULL); + + KeySym ignore = { 0 }; + Status return_status = 0; + XKeyEvent ev = *event; + ev.type = KeyPress; + xwc = XwcLookupString(xic, &ev, buffer, ARRAYSIZE(buffer), &ignore, + &return_status); + } + break; + } + + if (xwc < 1) + { + if (rdp_scancode == RDP_SCANCODE_UNKNOWN) + WLog_ERR(TAG, "Unknown key with X keycode 0x%02" PRIx8 "", event->keycode); + else + (void)freerdp_input_send_keyboard_event_ex(input, down, repeat, rdp_scancode); + } + else + { + char str[3 * ARRAYSIZE(buffer)] = { 0 }; + // NOLINTNEXTLINE(concurrency-mt-unsafe) + const size_t rc = wcstombs(str, buffer, ARRAYSIZE(buffer)); + + WCHAR wbuffer[ARRAYSIZE(buffer)] = { 0 }; + (void)ConvertUtf8ToWChar(str, wbuffer, rc); + (void)freerdp_input_send_unicode_keyboard_event(input, down ? 0 : KBD_FLAGS_RELEASE, + wbuffer[0]); + } + } + else if (rdp_scancode == RDP_SCANCODE_UNKNOWN) + WLog_ERR(TAG, "Unknown key with X keycode 0x%02" PRIx8 "", event->keycode); + else + (void)freerdp_input_send_keyboard_event_ex(input, down, repeat, rdp_scancode); + + if ((rdp_scancode == RDP_SCANCODE_CAPSLOCK) && (down == FALSE)) + { + (void)xf_sync_kbd_state(xfc); + } + } +} + +static int xf_keyboard_read_keyboard_state(xfContext* xfc) +{ + int dummy = 0; + Window wdummy = 0; + UINT32 state = 0; + + if (!xfc->remote_app && xfc->window) + { + XQueryPointer(xfc->display, xfc->window->handle, &wdummy, &wdummy, &dummy, &dummy, &dummy, + &dummy, &state); + } + else + { + XQueryPointer(xfc->display, DefaultRootWindow(xfc->display), &wdummy, &wdummy, &dummy, + &dummy, &dummy, &dummy, &state); + } + + return WINPR_ASSERTING_INT_CAST(int, state); +} + +static int xf_keyboard_get_keymask(xfContext* xfc, KeySym keysym) +{ + int keysymMask = 0; + KeyCode keycode = XKeysymToKeycode(xfc->display, keysym); + + if (keycode == NoSymbol) + return 0; + + WINPR_ASSERT(xfc->modifierMap); + for (int modifierpos = 0; modifierpos < 8; modifierpos++) + { + int offset = xfc->modifierMap->max_keypermod * modifierpos; + + for (int key = 0; key < xfc->modifierMap->max_keypermod; key++) + { + if (xfc->modifierMap->modifiermap[offset + key] == keycode) + { + keysymMask |= 1 << modifierpos; + } + } + } + + return keysymMask; +} + +static BOOL xf_keyboard_get_key_state(xfContext* xfc, int state, KeySym keysym) +{ + int keysymMask = xf_keyboard_get_keymask(xfc, keysym); + + if (!keysymMask) + return FALSE; + + return (state & keysymMask) ? TRUE : FALSE; +} + +static BOOL xf_keyboard_set_key_state(xfContext* xfc, BOOL on, KeySym keysym) +{ + if (!xfc->xkbAvailable) + return FALSE; + + const int keysymMask = xf_keyboard_get_keymask(xfc, keysym); + + if (!keysymMask) + { + return FALSE; + } + + return XkbLockModifiers(xfc->display, XkbUseCoreKbd, + WINPR_ASSERTING_INT_CAST(uint32_t, keysymMask), + on ? WINPR_ASSERTING_INT_CAST(uint32_t, keysymMask) : 0); +} + +UINT32 xf_keyboard_get_toggle_keys_state(xfContext* xfc) +{ + UINT32 toggleKeysState = 0; + const int state = xf_keyboard_read_keyboard_state(xfc); + + if (xf_keyboard_get_key_state(xfc, state, XK_Scroll_Lock)) + toggleKeysState |= KBD_SYNC_SCROLL_LOCK; + + if (xf_keyboard_get_key_state(xfc, state, XK_Num_Lock)) + toggleKeysState |= KBD_SYNC_NUM_LOCK; + + if (xf_keyboard_get_key_state(xfc, state, XK_Caps_Lock)) + toggleKeysState |= KBD_SYNC_CAPS_LOCK; + + if (xf_keyboard_get_key_state(xfc, state, XK_Kana_Lock)) + toggleKeysState |= KBD_SYNC_KANA_LOCK; + + return toggleKeysState; +} + +static void xk_keyboard_update_modifier_keys(xfContext* xfc) +{ + const KeySym keysyms[] = { XK_Shift_L, XK_Shift_R, XK_Alt_L, XK_Alt_R, + XK_Control_L, XK_Control_R, XK_Super_L, XK_Super_R }; + + xf_keyboard_clear(xfc); + + const int state = xf_keyboard_read_keyboard_state(xfc); + + for (size_t i = 0; i < ARRAYSIZE(keysyms); i++) + { + if (xf_keyboard_get_key_state(xfc, state, keysyms[i])) + { + const KeyCode keycode = XKeysymToKeycode(xfc->display, keysyms[i]); + WINPR_ASSERT(keycode < ARRAYSIZE(xfc->KeyboardState)); + xfc->KeyboardState[keycode] = TRUE; + } + } +} + +void xf_keyboard_focus_in(xfContext* xfc) +{ + UINT32 state = 0; + Window w = None; + int d = 0; + int x = 0; + int y = 0; + + WINPR_ASSERT(xfc); + if (!xfc->display || !xfc->window) + return; + + rdpInput* input = xfc->common.context.input; + WINPR_ASSERT(input); + + const UINT32 syncFlags = xf_keyboard_get_toggle_keys_state(xfc); + freerdp_input_send_focus_in_event(input, WINPR_ASSERTING_INT_CAST(UINT16, syncFlags)); + xk_keyboard_update_modifier_keys(xfc); + + /* finish with a mouse pointer position like mstsc.exe if required */ + + if (xfc->remote_app || !xfc->window) + return; + + if (XQueryPointer(xfc->display, xfc->window->handle, &w, &w, &d, &d, &x, &y, &state)) + { + if ((x >= 0) && (x < xfc->window->width) && (y >= 0) && (y < xfc->window->height)) + { + xf_event_adjust_coordinates(xfc, &x, &y); + freerdp_client_send_button_event(&xfc->common, FALSE, PTR_FLAGS_MOVE, x, y); + } + } +} + +static BOOL action_script_run(xfContext* xfc, const char* buffer, size_t size, void* user, + const char* what, const char* arg) +{ + WINPR_UNUSED(xfc); + WINPR_UNUSED(what); + WINPR_UNUSED(arg); + WINPR_ASSERT(user); + int* pstatus = user; + + if (size == 0) + { + WLog_WARN(TAG, "ActionScript key: script did not return data"); + return FALSE; + } + + if (strcmp(buffer, "key-local") == 0) + *pstatus = 0; + else if (winpr_PathFileExists(buffer)) + { + FILE* fp = popen(buffer, "w"); + if (!fp) + { + WLog_ERR(TAG, "Failed to execute '%s'", buffer); + return FALSE; + } + + *pstatus = pclose(fp); + if (*pstatus < 0) + { + WLog_ERR(TAG, "Command '%s' returned %d", buffer, *pstatus); + return FALSE; + } + } + else + { + WLog_WARN(TAG, "ActionScript key: no such file '%s'", buffer); + return FALSE; + } + return TRUE; +} + +static int xf_keyboard_execute_action_script(xfContext* xfc, XF_MODIFIER_KEYS* mod, KeySym keysym) +{ + int status = 1; + BOOL match = FALSE; + char command[2048] = { 0 }; + char combination[1024] = { 0 }; + + if (!xfc->actionScriptExists) + return 1; + + if ((keysym == XK_Shift_L) || (keysym == XK_Shift_R) || (keysym == XK_Alt_L) || + (keysym == XK_Alt_R) || (keysym == XK_Control_L) || (keysym == XK_Control_R)) + { + return 1; + } + + const char* keyStr = XKeysymToString(keysym); + + if (keyStr == 0) + { + return 1; + } + + if (mod->Shift) + winpr_str_append("Shift", combination, sizeof(combination), "+"); + + if (mod->Ctrl) + winpr_str_append("Ctrl", combination, sizeof(combination), "+"); + + if (mod->Alt) + winpr_str_append("Alt", combination, sizeof(combination), "+"); + + if (mod->Super) + winpr_str_append("Super", combination, sizeof(combination), "+"); + + winpr_str_append(keyStr, combination, sizeof(combination), "+"); + + for (size_t i = 0; i < strnlen(combination, sizeof(combination)); i++) + combination[i] = WINPR_ASSERTING_INT_CAST(char, tolower(combination[i])); + + const size_t count = ArrayList_Count(xfc->keyCombinations); + + for (size_t index = 0; index < count; index++) + { + const char* keyCombination = (const char*)ArrayList_GetItem(xfc->keyCombinations, index); + + if (_stricmp(keyCombination, combination) == 0) + { + match = TRUE; + break; + } + } + + if (!match) + return 1; + + (void)sprintf_s(command, sizeof(command), "key %s", combination); + if (!run_action_script(xfc, command, NULL, action_script_run, &status)) + return -1; + + return status; +} + +static int xk_keyboard_get_modifier_keys(xfContext* xfc, XF_MODIFIER_KEYS* mod) +{ + mod->LeftShift = xf_keyboard_key_pressed(xfc, XK_Shift_L); + mod->RightShift = xf_keyboard_key_pressed(xfc, XK_Shift_R); + mod->Shift = mod->LeftShift || mod->RightShift; + mod->LeftAlt = xf_keyboard_key_pressed(xfc, XK_Alt_L); + mod->RightAlt = xf_keyboard_key_pressed(xfc, XK_Alt_R); + mod->Alt = mod->LeftAlt || mod->RightAlt; + mod->LeftCtrl = xf_keyboard_key_pressed(xfc, XK_Control_L); + mod->RightCtrl = xf_keyboard_key_pressed(xfc, XK_Control_R); + mod->Ctrl = mod->LeftCtrl || mod->RightCtrl; + mod->LeftSuper = xf_keyboard_key_pressed(xfc, XK_Super_L); + mod->RightSuper = xf_keyboard_key_pressed(xfc, XK_Super_R); + mod->Super = mod->LeftSuper || mod->RightSuper; + return 0; +} + +BOOL xf_keyboard_handle_special_keys(xfContext* xfc, KeySym keysym) +{ + XF_MODIFIER_KEYS mod = { 0 }; + xk_keyboard_get_modifier_keys(xfc, &mod); + + // remember state of RightCtrl to ungrab keyboard if next action is release of RightCtrl + // do not return anything such that the key could be used by client if ungrab is not the goal + if (keysym == XK_Control_R) + { + if (mod.RightCtrl && !xfc->wasRightCtrlAlreadyPressed) + { + // Right Ctrl is pressed, getting ready to ungrab + xfc->ungrabKeyboardWithRightCtrl = TRUE; + xfc->wasRightCtrlAlreadyPressed = TRUE; + } + } + else + { + // some other key has been pressed, abort ungrabbing + if (xfc->ungrabKeyboardWithRightCtrl) + xfc->ungrabKeyboardWithRightCtrl = FALSE; + } + + const int rc = xf_keyboard_execute_action_script(xfc, &mod, keysym); + if (rc < 0) + return FALSE; + if (rc == 0) + return TRUE; + + if (!xfc->remote_app && xfc->fullscreen_toggle) + { + switch (keysym) + { + case XK_Return: + if (mod.Ctrl && mod.Alt) + { + /* Ctrl-Alt-Enter: toggle full screen */ + xf_toggle_fullscreen(xfc); + return TRUE; + } + break; + default: + break; + } + } + + if (mod.Ctrl && mod.Alt) + { + switch (keysym) + { + case XK_m: + case XK_M: + xf_minimize(xfc); + return TRUE; + case XK_c: + case XK_C: + /* Ctrl-Alt-C: toggle control */ + if (freerdp_client_encomsp_toggle_control(xfc->common.encomsp)) + return TRUE; + break; + default: + break; + } + } + +#if 0 /* set to 1 to enable multi touch gesture simulation via keyboard */ +#ifdef WITH_XRENDER + + if (!xfc->remote_app && freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_MultiTouchGestures)) + { + rdpContext* ctx = &xfc->common.context; + + if (mod.Ctrl && mod.Alt) + { + int pdx = 0; + int pdy = 0; + int zdx = 0; + int zdy = 0; + + switch (keysym) + { + case XK_0: /* Ctrl-Alt-0: Reset scaling and panning */{ + const UINT32 sessionWidth = freerdp_settings_get_uint32(xfc->common.context.settings, FreeRDP_DesktopWidth); + const UINT32 sessionHeight = freerdp_settings_get_uint32(xfc->common.context.settings, FreeRDP_DesktopHeight); + + xfc->scaledWidth = sessionWidth; + xfc->scaledHeight = sessionHeight; + xfc->offset_x = 0; + xfc->offset_y = 0; + + if (!xfc->fullscreen && (sessionWidth != xfc->window->width || + sessionHeight != xfc->window->height)) + { + xf_ResizeDesktopWindow(xfc, xfc->window, sessionWidth, sessionHeight); + } + + xf_draw_screen(xfc, 0, 0, sessionWidth, sessionHeight); + return TRUE; +} + + case XK_1: /* Ctrl-Alt-1: Zoom in */ + zdx = zdy = 10; + break; + + case XK_2: /* Ctrl-Alt-2: Zoom out */ + zdx = zdy = -10; + break; + + case XK_3: /* Ctrl-Alt-3: Pan left */ + pdx = -10; + break; + + case XK_4: /* Ctrl-Alt-4: Pan right */ + pdx = 10; + break; + + case XK_5: /* Ctrl-Alt-5: Pan up */ + pdy = -10; + break; + + case XK_6: /* Ctrl-Alt-6: Pan up */ + pdy = 10; + break; + } + + if (pdx != 0 || pdy != 0) + { + PanningChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = pdx; + e.dy = pdy; + PubSub_OnPanningChange(ctx->pubSub, xfc, &e); + return TRUE; + } + + if (zdx != 0 || zdy != 0) + { + ZoomingChangeEventArgs e; + EventArgsInit(&e, "xfreerdp"); + e.dx = zdx; + e.dy = zdy; + PubSub_OnZoomingChange(ctx->pubSub, xfc, &e); + return TRUE; + } + } + } + +#endif /* WITH_XRENDER defined */ +#endif /* pinch/zoom/pan simulation */ + return FALSE; +} + +void xf_keyboard_handle_special_keys_release(xfContext* xfc, KeySym keysym) +{ + if (keysym != XK_Control_R) + return; + + xfc->wasRightCtrlAlreadyPressed = FALSE; + + if (!xfc->ungrabKeyboardWithRightCtrl) + return; + + // all requirements for ungrab are fulfilled, ungrabbing now + XF_MODIFIER_KEYS mod = { 0 }; + xk_keyboard_get_modifier_keys(xfc, &mod); + + if (!mod.RightCtrl) + { + if (!xfc->fullscreen) + { + freerdp_client_encomsp_toggle_control(xfc->common.encomsp); + } + + xfc->mouse_active = FALSE; + xf_ungrab(xfc); + } + + // ungrabbed + xfc->ungrabKeyboardWithRightCtrl = FALSE; +} + +BOOL xf_keyboard_set_indicators(rdpContext* context, UINT16 led_flags) +{ + xfContext* xfc = (xfContext*)context; + xf_keyboard_set_key_state(xfc, led_flags & KBD_SYNC_SCROLL_LOCK, XK_Scroll_Lock); + xf_keyboard_set_key_state(xfc, led_flags & KBD_SYNC_NUM_LOCK, XK_Num_Lock); + xf_keyboard_set_key_state(xfc, led_flags & KBD_SYNC_CAPS_LOCK, XK_Caps_Lock); + xf_keyboard_set_key_state(xfc, led_flags & KBD_SYNC_KANA_LOCK, XK_Kana_Lock); + return TRUE; +} + +BOOL xf_keyboard_set_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, + UINT32 imeConvMode) +{ + if (!context) + return FALSE; + + WLog_WARN(TAG, + "KeyboardSetImeStatus(unitId=%04" PRIx16 ", imeState=%08" PRIx32 + ", imeConvMode=%08" PRIx32 ") ignored", + imeId, imeState, imeConvMode); + return TRUE; +} + +BOOL xf_ungrab(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + XUngrabKeyboard(xfc->display, CurrentTime); + XUngrabPointer(xfc->display, CurrentTime); + xfc->common.mouse_grabbed = FALSE; + return TRUE; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.h new file mode 100644 index 0000000000000000000000000000000000000000..a1954b5541b6df32ecbdd1c4c49f5ad0d2ef1fb7 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_keyboard.h @@ -0,0 +1,47 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Keyboard Handling + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_XF_KEYBOARD_H +#define FREERDP_CLIENT_X11_XF_KEYBOARD_H + +#include + +#include "xf_client.h" +#include "xfreerdp.h" + +BOOL xf_keyboard_init(xfContext* xfc); +void xf_keyboard_free(xfContext* xfc); + +BOOL xf_keyboard_action_script_init(xfContext* xfc); + +void xf_keyboard_key_press(xfContext* xfc, const XKeyEvent* event, KeySym keysym); +void xf_keyboard_key_release(xfContext* xfc, const XKeyEvent* event, KeySym keysym); + +void xf_keyboard_release_all_keypress(xfContext* xfc); + +void xf_keyboard_focus_in(xfContext* xfc); +BOOL xf_keyboard_set_indicators(rdpContext* context, UINT16 led_flags); +BOOL xf_keyboard_set_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, + UINT32 imeConvMode); + +BOOL xf_ungrab(xfContext* xfc); + +void xf_button_map_init(xfContext* xfc); + +#endif /* FREERDP_CLIENT_X11_XF_KEYBOARD_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.c new file mode 100644 index 0000000000000000000000000000000000000000..7ea0adda49f16ce8feb6fbc68c7e16c5f8962c24 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.c @@ -0,0 +1,655 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Monitor Handling + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2017 David Fort + * Copyright 2018 Kai Harms + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#define TAG CLIENT_TAG("x11") + +#ifdef WITH_XINERAMA +#include +#endif + +#ifdef WITH_XRANDR +#include +#include + +#if (RANDR_MAJOR * 100 + RANDR_MINOR) >= 105 +#define USABLE_XRANDR +#endif + +#endif + +#include "xf_monitor.h" + +/* See MSDN Section on Multiple Display Monitors: http://msdn.microsoft.com/en-us/library/dd145071 + */ + +int xf_list_monitors(xfContext* xfc) +{ + WINPR_UNUSED(xfc); + + int major = 0; + int minor = 0; + int nmonitors = 0; + Display* display = XOpenDisplay(NULL); + + if (!display) + { + WLog_ERR(TAG, "failed to open X display"); + return -1; + } + +#if defined(USABLE_XRANDR) + + if (XRRQueryExtension(display, &major, &minor) && + (XRRQueryVersion(display, &major, &minor) == True) && (major * 100 + minor >= 105)) + { + XRRMonitorInfo* monitors = + XRRGetMonitors(display, DefaultRootWindow(display), 1, &nmonitors); + + for (int i = 0; i < nmonitors; i++) + { + printf(" %s [%d] %dx%d\t+%d+%d\n", monitors[i].primary ? "*" : " ", i, + monitors[i].width, monitors[i].height, monitors[i].x, monitors[i].y); + } + + XRRFreeMonitors(monitors); + } + else +#endif +#ifdef WITH_XINERAMA + if (XineramaQueryExtension(display, &major, &minor)) + { + if (XineramaIsActive(display)) + { + XineramaScreenInfo* screen = XineramaQueryScreens(display, &nmonitors); + + for (int i = 0; i < nmonitors; i++) + { + printf(" %s [%d] %hdx%hd\t+%hd+%hd\n", (i == 0) ? "*" : " ", i, + screen[i].width, screen[i].height, screen[i].x_org, screen[i].y_org); + } + + XFree(screen); + } + } + else +#else + { + Screen* screen = ScreenOfDisplay(display, DefaultScreen(display)); + printf(" * [0] %dx%d\t+0+0\n", WidthOfScreen(screen), HeightOfScreen(screen)); + } + +#endif + XCloseDisplay(display); + return 0; +} + +static BOOL xf_is_monitor_id_active(xfContext* xfc, UINT32 id) +{ + const rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + const UINT32 NumMonitorIds = freerdp_settings_get_uint32(settings, FreeRDP_NumMonitorIds); + if (NumMonitorIds == 0) + return TRUE; + + for (UINT32 index = 0; index < NumMonitorIds; index++) + { + const UINT32* cur = freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorIds, index); + if (cur && (*cur == id)) + return TRUE; + } + + return FALSE; +} + +BOOL xf_detect_monitors(xfContext* xfc, UINT32* pMaxWidth, UINT32* pMaxHeight) +{ + BOOL rc = FALSE; + UINT32 monitor_index = 0; + BOOL primaryMonitorFound = FALSE; + int mouse_x = 0; + int mouse_y = 0; + int _dummy_i = 0; + Window _dummy_w = 0; + UINT32 current_monitor = 0; + Screen* screen = NULL; +#if defined WITH_XINERAMA || defined WITH_XRANDR + int major = 0; + int minor = 0; +#endif +#if defined(USABLE_XRANDR) + XRRMonitorInfo* rrmonitors = NULL; + BOOL useXRandr = FALSE; +#endif + + if (!xfc || !pMaxWidth || !pMaxHeight || !xfc->common.context.settings) + return FALSE; + + rdpSettings* settings = xfc->common.context.settings; + VIRTUAL_SCREEN* vscreen = &xfc->vscreen; + + *pMaxWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + *pMaxHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + + if (freerdp_settings_get_uint64(settings, FreeRDP_ParentWindowId) > 0) + { + xfc->workArea.x = 0; + xfc->workArea.y = 0; + xfc->workArea.width = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + xfc->workArea.height = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + return TRUE; + } + + /* get mouse location */ + if (!XQueryPointer(xfc->display, DefaultRootWindow(xfc->display), &_dummy_w, &_dummy_w, + &mouse_x, &mouse_y, &_dummy_i, &_dummy_i, (void*)&_dummy_i)) + mouse_x = mouse_y = 0; + +#if defined(USABLE_XRANDR) + + if (XRRQueryExtension(xfc->display, &major, &minor) && + (XRRQueryVersion(xfc->display, &major, &minor) == True) && (major * 100 + minor >= 105)) + { + int nmonitors = 0; + rrmonitors = XRRGetMonitors(xfc->display, DefaultRootWindow(xfc->display), 1, &nmonitors); + + if ((nmonitors < 0) || (nmonitors > 16)) + vscreen->nmonitors = 0; + else + vscreen->nmonitors = (UINT32)nmonitors; + + if (vscreen->nmonitors) + { + for (UINT32 i = 0; i < vscreen->nmonitors; i++) + { + MONITOR_INFO* cur_vscreen = &vscreen->monitors[i]; + const XRRMonitorInfo* cur_monitor = &rrmonitors[i]; + + cur_vscreen->area.left = WINPR_ASSERTING_INT_CAST(UINT16, cur_monitor->x); + cur_vscreen->area.top = WINPR_ASSERTING_INT_CAST(UINT16, cur_monitor->y); + cur_vscreen->area.right = + WINPR_ASSERTING_INT_CAST(UINT16, cur_monitor->x + cur_monitor->width - 1); + cur_vscreen->area.bottom = + WINPR_ASSERTING_INT_CAST(UINT16, cur_monitor->y + cur_monitor->height - 1); + cur_vscreen->primary = cur_monitor->primary > 0; + } + } + + useXRandr = TRUE; + } + else +#endif +#ifdef WITH_XINERAMA + if (XineramaQueryExtension(xfc->display, &major, &minor) && XineramaIsActive(xfc->display)) + { + int nmonitors = 0; + XineramaScreenInfo* screenInfo = XineramaQueryScreens(xfc->display, &nmonitors); + + if ((nmonitors < 0) || (nmonitors > 16)) + vscreen->nmonitors = 0; + else + vscreen->nmonitors = (UINT32)nmonitors; + + if (vscreen->nmonitors) + { + for (UINT32 i = 0; i < vscreen->nmonitors; i++) + { + MONITOR_INFO* monitor = &vscreen->monitors[i]; + monitor->area.left = WINPR_ASSERTING_INT_CAST(uint16_t, screenInfo[i].x_org); + monitor->area.top = WINPR_ASSERTING_INT_CAST(uint16_t, screenInfo[i].y_org); + monitor->area.right = WINPR_ASSERTING_INT_CAST( + uint16_t, screenInfo[i].x_org + screenInfo[i].width - 1); + monitor->area.bottom = WINPR_ASSERTING_INT_CAST( + uint16_t, screenInfo[i].y_org + screenInfo[i].height - 1); + } + } + + XFree(screenInfo); + } + else +#endif + { + /* Both XRandR and Xinerama are either not compiled in or are not working, do nothing. + */ + } + + rdpMonitor* rdpmonitors = calloc(vscreen->nmonitors + 1, sizeof(rdpMonitor)); + if (!rdpmonitors) + goto fail; + + xfc->fullscreenMonitors.top = 0; + xfc->fullscreenMonitors.bottom = 0; + xfc->fullscreenMonitors.left = 0; + xfc->fullscreenMonitors.right = 0; + + /* Determine which monitor that the mouse cursor is on */ + if (vscreen->monitors) + { + for (UINT32 i = 0; i < vscreen->nmonitors; i++) + { + const MONITOR_INFO* monitor = &vscreen->monitors[i]; + + if ((mouse_x >= monitor->area.left) && (mouse_x <= monitor->area.right) && + (mouse_y >= monitor->area.top) && (mouse_y <= monitor->area.bottom)) + { + current_monitor = i; + break; + } + } + } + + /* + Even for a single monitor, we need to calculate the virtual screen to support + window managers that do not implement all X window state hints. + + If the user did not request multiple monitor or is using workarea + without remote app, we force the number of monitors be 1 so later + the rest of the client don't end up using more monitors than the user desires. + */ + if ((!freerdp_settings_get_bool(settings, FreeRDP_UseMultimon) && + !freerdp_settings_get_bool(settings, FreeRDP_SpanMonitors)) || + (freerdp_settings_get_bool(settings, FreeRDP_Workarea) && + !freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode))) + { + /* If no monitors were specified on the command-line then set the current monitor as active + */ + if (freerdp_settings_get_uint32(settings, FreeRDP_NumMonitorIds) == 0) + { + UINT32 id = current_monitor; + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_MonitorIds, &id, 1)) + goto fail; + } + + /* Always sets number of monitors from command-line to just 1. + * If the monitor is invalid then we will default back to current monitor + * later as a fallback. So, there is no need to validate command-line entry here. + */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_NumMonitorIds, 1)) + goto fail; + } + + /* WORKAROUND: With Remote Application Mode - using NET_WM_WORKAREA + * causes issues with the ability to fully size the window vertically + * (the bottom of the window area is never updated). So, we just set + * the workArea to match the full Screen width/height. + */ + if (freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode) || !xf_GetWorkArea(xfc)) + { + /* + if only 1 monitor is enabled, use monitor area + this is required in case of a screen composed of more than one monitor + but user did not enable multimonitor + */ + if ((freerdp_settings_get_uint32(settings, FreeRDP_NumMonitorIds) == 1) && + (vscreen->nmonitors > current_monitor)) + { + MONITOR_INFO* monitor = vscreen->monitors + current_monitor; + + if (!monitor) + goto fail; + + xfc->workArea.x = monitor->area.left; + xfc->workArea.y = monitor->area.top; + xfc->workArea.width = monitor->area.right - monitor->area.left + 1; + xfc->workArea.height = monitor->area.bottom - monitor->area.top + 1; + } + else + { + xfc->workArea.x = 0; + xfc->workArea.y = 0; + xfc->workArea.width = WINPR_ASSERTING_INT_CAST(uint32_t, WidthOfScreen(xfc->screen)); + xfc->workArea.height = WINPR_ASSERTING_INT_CAST(uint32_t, HeightOfScreen(xfc->screen)); + } + } + + if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)) + { + *pMaxWidth = WINPR_ASSERTING_INT_CAST(uint32_t, WidthOfScreen(xfc->screen)); + *pMaxHeight = WINPR_ASSERTING_INT_CAST(uint32_t, HeightOfScreen(xfc->screen)); + } + else if (freerdp_settings_get_bool(settings, FreeRDP_Workarea)) + { + *pMaxWidth = xfc->workArea.width; + *pMaxHeight = xfc->workArea.height; + } + else if (freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) + { + /* If we have specific monitor information then limit the PercentScreen value + * to only affect the current monitor vs. the entire desktop + */ + if (vscreen->nmonitors > 0) + { + if (!vscreen->monitors) + goto fail; + + const MONITOR_INFO* vmonitor = &vscreen->monitors[current_monitor]; + const RECTANGLE_16* area = &vmonitor->area; + + *pMaxWidth = area->right - area->left + 1; + *pMaxHeight = area->bottom - area->top + 1; + + if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth)) + *pMaxWidth = ((area->right - area->left + 1) * + freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / + 100; + + if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseHeight)) + *pMaxHeight = ((area->bottom - area->top + 1) * + freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / + 100; + } + else + { + *pMaxWidth = xfc->workArea.width; + *pMaxHeight = xfc->workArea.height; + + if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth)) + *pMaxWidth = (xfc->workArea.width * + freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / + 100; + + if (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseHeight)) + *pMaxHeight = (xfc->workArea.height * + freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen)) / + 100; + } + } + else if (freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) && + freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)) + { + *pMaxWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth); + *pMaxHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight); + } + + /* Create array of all active monitors by taking into account monitors requested on the + * command-line */ + size_t nmonitors = 0; + { + UINT32 nr = 0; + + { + const UINT32* ids = freerdp_settings_get_pointer(settings, FreeRDP_MonitorIds); + if (ids) + nr = *ids; + } + for (UINT32 i = 0; i < vscreen->nmonitors; i++) + { + MONITOR_ATTRIBUTES* attrs = NULL; + + if (!xf_is_monitor_id_active(xfc, i)) + continue; + + if (!vscreen->monitors) + goto fail; + + rdpMonitor* monitor = &rdpmonitors[nmonitors]; + monitor->x = + WINPR_ASSERTING_INT_CAST( + int32_t, vscreen->monitors[i].area.left*( + freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth) + ? freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen) + : 100)) / + 100; + monitor->y = + WINPR_ASSERTING_INT_CAST( + int32_t, vscreen->monitors[i].area.top*( + freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseHeight) + ? freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen) + : 100)) / + 100; + monitor->width = + WINPR_ASSERTING_INT_CAST( + int32_t, + (vscreen->monitors[i].area.right - vscreen->monitors[i].area.left + 1) * + (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth) + ? freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen) + : 100)) / + 100; + monitor->height = + WINPR_ASSERTING_INT_CAST( + int32_t, + (vscreen->monitors[i].area.bottom - vscreen->monitors[i].area.top + 1) * + (freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth) + ? freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen) + : 100)) / + 100; + monitor->orig_screen = i; +#ifdef USABLE_XRANDR + + if (useXRandr && rrmonitors) + { + Rotation rot = 0; + Rotation ret = 0; + attrs = &monitor->attributes; + attrs->physicalWidth = WINPR_ASSERTING_INT_CAST(uint32_t, rrmonitors[i].mwidth); + attrs->physicalHeight = WINPR_ASSERTING_INT_CAST(uint32_t, rrmonitors[i].mheight); + ret = XRRRotations(xfc->display, WINPR_ASSERTING_INT_CAST(int, i), &rot); + attrs->orientation = ret; + } + +#endif + + if (i == nr) + { + monitor->is_primary = TRUE; + primaryMonitorFound = TRUE; + } + + nmonitors++; + } + } + + /* If no monitor is active(bogus command-line monitor specification) - then lets try to fallback + * to go fullscreen on the current monitor only */ + if ((nmonitors == 0) && (vscreen->nmonitors > 0)) + { + if (!vscreen->monitors) + goto fail; + + const MONITOR_INFO* vmonitor = &vscreen->monitors[current_monitor]; + const RECTANGLE_16* area = &vmonitor->area; + + const INT32 width = area->right - area->left + 1; + const INT32 height = area->bottom - area->top + 1; + const INT32 maxw = + ((width < 0) || ((UINT32)width < *pMaxWidth)) ? width : (INT32)*pMaxWidth; + const INT32 maxh = + ((height < 0) || ((UINT32)height < *pMaxHeight)) ? width : (INT32)*pMaxHeight; + + rdpMonitor* monitor = &rdpmonitors[0]; + if (!monitor) + goto fail; + + monitor->x = area->left; + monitor->y = area->top; + monitor->width = maxw; + monitor->height = maxh; + monitor->orig_screen = current_monitor; + nmonitors = 1; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_MonitorCount, + WINPR_ASSERTING_INT_CAST(uint32_t, nmonitors))) + goto fail; + + /* If we have specific monitor information */ + if (freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount) > 0) + { + const rdpMonitor* cmonitor = &rdpmonitors[0]; + if (!cmonitor) + goto fail; + + /* Initialize bounding rectangle for all monitors */ + int vX = cmonitor->x; + int vY = cmonitor->y; + int vR = vX + cmonitor->width; + int vB = vY + cmonitor->height; + const int32_t corig = WINPR_ASSERTING_INT_CAST(int32_t, cmonitor->orig_screen); + xfc->fullscreenMonitors.top = corig; + xfc->fullscreenMonitors.bottom = corig; + xfc->fullscreenMonitors.left = corig; + xfc->fullscreenMonitors.right = corig; + + /* Calculate bounding rectangle around all monitors to be used AND + * also set the Xinerama indices which define left/top/right/bottom monitors. + */ + for (UINT32 i = 0; i < freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); i++) + { + rdpMonitor* monitor = &rdpmonitors[i]; + + /* does the same as gdk_rectangle_union */ + const int destX = MIN(vX, monitor->x); + const int destY = MIN(vY, monitor->y); + const int destR = MAX(vR, monitor->x + monitor->width); + const int destB = MAX(vB, monitor->y + monitor->height); + const int32_t orig = WINPR_ASSERTING_INT_CAST(int32_t, monitor->orig_screen); + + if (vX != destX) + xfc->fullscreenMonitors.left = orig; + + if (vY != destY) + xfc->fullscreenMonitors.top = orig; + + if (vR != destR) + xfc->fullscreenMonitors.right = orig; + + if (vB != destB) + xfc->fullscreenMonitors.bottom = orig; + + const UINT32 ps = freerdp_settings_get_uint32(settings, FreeRDP_PercentScreen); + WINPR_ASSERT(ps <= 100); + + const int psuw = + freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseWidth) ? (int)ps : 100; + const int psuh = + freerdp_settings_get_bool(settings, FreeRDP_PercentScreenUseHeight) ? (int)ps : 100; + vX = (destX * psuw) / 100; + vY = (destY * psuh) / 100; + vR = (destR * psuw) / 100; + vB = (destB * psuh) / 100; + } + + vscreen->area.left = 0; + const int r = vR - vX - 1; + vscreen->area.right = WINPR_ASSERTING_INT_CAST(UINT16, r); + vscreen->area.top = 0; + const int b = vB - vY - 1; + vscreen->area.bottom = WINPR_ASSERTING_INT_CAST(UINT16, b); + + if (freerdp_settings_get_bool(settings, FreeRDP_Workarea)) + { + INT64 bottom = xfc->workArea.height + xfc->workArea.y - 1; + vscreen->area.top = WINPR_ASSERTING_INT_CAST(UINT16, xfc->workArea.y); + vscreen->area.bottom = WINPR_ASSERTING_INT_CAST(UINT16, bottom); + } + + if (!primaryMonitorFound) + { + /* If we have a command line setting we should use it */ + if (freerdp_settings_get_uint32(settings, FreeRDP_NumMonitorIds) > 0) + { + /* The first monitor is the first in the setting which should be used */ + UINT32* ids = + freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorIds, 0); + if (ids) + monitor_index = *ids; + } + else + { + /* This is the same as when we would trust the Xinerama results.. + and set the monitor index to zero. + The monitor listed with /list:monitor on index zero is always the primary + */ + screen = DefaultScreenOfDisplay(xfc->display); + monitor_index = WINPR_ASSERTING_INT_CAST(uint32_t, XScreenNumberOfScreen(screen)); + } + + UINT32 j = monitor_index; + rdpMonitor* pmonitor = &rdpmonitors[j]; + + /* If the "default" monitor is not 0,0 use it */ + if ((pmonitor->x != 0) || (pmonitor->y != 0)) + { + pmonitor->is_primary = TRUE; + } + else + { + /* Lets try to see if there is a monitor with a 0,0 coordinate and use it as a + * fallback*/ + for (UINT32 i = 0; i < freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); + i++) + { + rdpMonitor* monitor = &rdpmonitors[i]; + if (!primaryMonitorFound && monitor->x == 0 && monitor->y == 0) + { + monitor->is_primary = TRUE; + primaryMonitorFound = TRUE; + } + } + } + } + + /* Set the desktop width and height according to the bounding rectangle around the active + * monitors */ + *pMaxWidth = MIN(*pMaxWidth, (UINT32)vscreen->area.right - vscreen->area.left + 1); + *pMaxHeight = MIN(*pMaxHeight, (UINT32)vscreen->area.bottom - vscreen->area.top + 1); + } + + /* some 2008 server freeze at logon if we announce support for monitor layout PDU with + * #monitors < 2. So let's announce it only if we have more than 1 monitor. + */ + nmonitors = freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); + if (nmonitors > 1) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportMonitorLayoutPdu, TRUE)) + goto fail; + } + + rc = freerdp_settings_set_monitor_def_array_sorted(settings, rdpmonitors, nmonitors); + +fail: +#ifdef USABLE_XRANDR + + if (rrmonitors) + XRRFreeMonitors(rrmonitors); + +#endif + free(rdpmonitors); + return rc; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..6597c1560ca7da07c99e9c6cded00c4d0881cbf0 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_monitor.h @@ -0,0 +1,48 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Monitor Handling + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_MONITOR_H +#define FREERDP_CLIENT_X11_MONITOR_H + +#include +#include + +typedef struct +{ + RECTANGLE_16 area; + RECTANGLE_16 workarea; + BOOL primary; +} MONITOR_INFO; + +typedef struct +{ + UINT32 nmonitors; + RECTANGLE_16 area; + RECTANGLE_16 workarea; + MONITOR_INFO* monitors; +} VIRTUAL_SCREEN; + +#include "xf_client.h" +#include "xfreerdp.h" + +FREERDP_API int xf_list_monitors(xfContext* xfc); +FREERDP_API BOOL xf_detect_monitors(xfContext* xfc, UINT32* pWidth, UINT32* pHeight); +FREERDP_API void xf_monitors_free(xfContext* xfc); + +#endif /* FREERDP_CLIENT_X11_MONITOR_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.c new file mode 100644 index 0000000000000000000000000000000000000000..4c7154eb471643942b0640749bd5842c59410add --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.c @@ -0,0 +1,1245 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 RAIL + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "xf_window.h" +#include "xf_rail.h" +#include "xf_utils.h" + +#include +#define TAG CLIENT_TAG("x11") + +static const char* error_code_names[] = { "RAIL_EXEC_S_OK", + "RAIL_EXEC_E_HOOK_NOT_LOADED", + "RAIL_EXEC_E_DECODE_FAILED", + "RAIL_EXEC_E_NOT_IN_ALLOWLIST", + "RAIL_EXEC_E_FILE_NOT_FOUND", + "RAIL_EXEC_E_FAIL", + "RAIL_EXEC_E_SESSION_LOCKED" }; + +#ifdef WITH_DEBUG_RAIL +static const char* movetype_names[] = { + "(invalid)", "RAIL_WMSZ_LEFT", "RAIL_WMSZ_RIGHT", + "RAIL_WMSZ_TOP", "RAIL_WMSZ_TOPLEFT", "RAIL_WMSZ_TOPRIGHT", + "RAIL_WMSZ_BOTTOM", "RAIL_WMSZ_BOTTOMLEFT", "RAIL_WMSZ_BOTTOMRIGHT", + "RAIL_WMSZ_MOVE", "RAIL_WMSZ_KEYMOVE", "RAIL_WMSZ_KEYSIZE" +}; +#endif + +struct xf_rail_icon +{ + long* data; + int length; +}; +typedef struct xf_rail_icon xfRailIcon; + +struct xf_rail_icon_cache +{ + xfRailIcon* entries; + UINT32 numCaches; + UINT32 numCacheEntries; + xfRailIcon scratch; +}; + +typedef struct +{ + xfContext* xfc; + const RECTANGLE_16* rect; +} rail_paint_fn_arg_t; + +void xf_rail_enable_remoteapp_mode(xfContext* xfc) +{ + if (!xfc->remote_app) + { + xfc->remote_app = TRUE; + xfc->drawable = xf_CreateDummyWindow(xfc); + xf_DestroyDesktopWindow(xfc, xfc->window); + xfc->window = NULL; + } +} + +void xf_rail_disable_remoteapp_mode(xfContext* xfc) +{ + if (xfc->remote_app) + { + xfc->remote_app = FALSE; + xf_DestroyDummyWindow(xfc, xfc->drawable); + xf_create_window(xfc); + xf_create_image(xfc); + } +} + +void xf_rail_send_activate(xfContext* xfc, Window xwindow, BOOL enabled) +{ + RAIL_ACTIVATE_ORDER activate = { 0 }; + xfAppWindow* appWindow = xf_AppWindowFromX11Window(xfc, xwindow); + + if (!appWindow) + return; + + if (enabled) + xf_SetWindowStyle(xfc, appWindow, appWindow->dwStyle, appWindow->dwExStyle); + + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + activate.windowId = (UINT32)appWindow->windowId; + activate.enabled = enabled; + xfc->rail->ClientActivate(xfc->rail, &activate); +} + +BOOL xf_rail_send_client_system_command(xfContext* xfc, UINT64 windowId, UINT16 command) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(xfc->rail); + WINPR_ASSERT(xfc->rail->ClientSystemCommand); + if (windowId > UINT32_MAX) + return FALSE; + + const RAIL_SYSCOMMAND_ORDER syscommand = { .windowId = (UINT32)windowId, .command = command }; + const UINT rc = xfc->rail->ClientSystemCommand(xfc->rail, &syscommand); + return rc == CHANNEL_RC_OK; +} + +/** + * The position of the X window can become out of sync with the RDP window + * if the X window is moved locally by the window manager. In this event + * send an update to the RDP server informing it of the new window position + * and size. + */ +void xf_rail_adjust_position(xfContext* xfc, xfAppWindow* appWindow) +{ + RAIL_WINDOW_MOVE_ORDER windowMove = { 0 }; + + if (!appWindow->is_mapped || appWindow->local_move.state != LMS_NOT_ACTIVE) + return; + + /* If current window position disagrees with RDP window position, send update to RDP server */ + if (appWindow->x != appWindow->windowOffsetX || appWindow->y != appWindow->windowOffsetY || + appWindow->width != (INT64)appWindow->windowWidth || + appWindow->height != (INT64)appWindow->windowHeight) + { + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + windowMove.windowId = (UINT32)appWindow->windowId; + /* + * Calculate new size/position for the rail window(new values for + * windowOffsetX/windowOffsetY/windowWidth/windowHeight) on the server + */ + const INT16 left = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginLeft); + const INT16 right = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginRight); + const INT16 top = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginTop); + const INT16 bottom = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginBottom); + windowMove.left = WINPR_ASSERTING_INT_CAST(INT16, appWindow->x - left); + windowMove.top = WINPR_ASSERTING_INT_CAST(INT16, appWindow->y - top); + windowMove.right = WINPR_ASSERTING_INT_CAST(INT16, appWindow->x + appWindow->width + right); + windowMove.bottom = + WINPR_ASSERTING_INT_CAST(INT16, appWindow->y + appWindow->height + bottom); + xfc->rail->ClientWindowMove(xfc->rail, &windowMove); + } +} + +void xf_rail_end_local_move(xfContext* xfc, xfAppWindow* appWindow) +{ + int x = 0; + int y = 0; + int child_x = 0; + int child_y = 0; + unsigned int mask = 0; + Window root_window = 0; + Window child_window = 0; + + WINPR_ASSERT(xfc); + + if ((appWindow->local_move.direction == _NET_WM_MOVERESIZE_MOVE_KEYBOARD) || + (appWindow->local_move.direction == _NET_WM_MOVERESIZE_SIZE_KEYBOARD)) + { + RAIL_WINDOW_MOVE_ORDER windowMove = { 0 }; + + /* + * For keyboard moves send and explicit update to RDP server + */ + WINPR_ASSERT(appWindow->windowId <= UINT32_MAX); + windowMove.windowId = (UINT32)appWindow->windowId; + /* + * Calculate new size/position for the rail window(new values for + * windowOffsetX/windowOffsetY/windowWidth/windowHeight) on the server + * + */ + const INT16 left = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginLeft); + const INT16 right = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginRight); + const INT16 top = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginTop); + const INT16 bottom = WINPR_ASSERTING_INT_CAST(INT16, appWindow->resizeMarginBottom); + const INT16 w = WINPR_ASSERTING_INT_CAST(INT16, appWindow->width + right); + const INT16 h = WINPR_ASSERTING_INT_CAST(INT16, appWindow->height + bottom); + windowMove.left = WINPR_ASSERTING_INT_CAST(INT16, appWindow->x - left); + windowMove.top = WINPR_ASSERTING_INT_CAST(INT16, appWindow->y - top); + windowMove.right = WINPR_ASSERTING_INT_CAST(INT16, appWindow->x + w); /* In the update to + RDP the position is one past the window */ + windowMove.bottom = WINPR_ASSERTING_INT_CAST(INT16, appWindow->y + h); + xfc->rail->ClientWindowMove(xfc->rail, &windowMove); + } + + /* + * Simulate button up at new position to end the local move (per RDP spec) + */ + XQueryPointer(xfc->display, appWindow->handle, &root_window, &child_window, &x, &y, &child_x, + &child_y, &mask); + + /* only send the mouse coordinates if not a keyboard move or size */ + if ((appWindow->local_move.direction != _NET_WM_MOVERESIZE_MOVE_KEYBOARD) && + (appWindow->local_move.direction != _NET_WM_MOVERESIZE_SIZE_KEYBOARD)) + { + freerdp_client_send_button_event(&xfc->common, FALSE, PTR_FLAGS_BUTTON1, x, y); + } + + /* + * Proactively update the RAIL window dimensions. There is a race condition where + * we can start to receive GDI orders for the new window dimensions before we + * receive the RAIL ORDER for the new window size. This avoids that race condition. + */ + appWindow->windowOffsetX = appWindow->x; + appWindow->windowOffsetY = appWindow->y; + appWindow->windowWidth = WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->width); + appWindow->windowHeight = WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->height); + appWindow->local_move.state = LMS_TERMINATING; +} + +BOOL xf_rail_paint_surface(xfContext* xfc, UINT64 windowId, const RECTANGLE_16* rect) +{ + xfAppWindow* appWindow = xf_rail_get_window(xfc, windowId); + + WINPR_ASSERT(rect); + + if (!appWindow) + return FALSE; + + const RECTANGLE_16 windowRect = { + .left = WINPR_ASSERTING_INT_CAST(UINT16, MAX(appWindow->x, 0)), + .top = WINPR_ASSERTING_INT_CAST(UINT16, MAX(appWindow->y, 0)), + .right = WINPR_ASSERTING_INT_CAST(UINT16, MAX(appWindow->x + appWindow->width, 0)), + .bottom = WINPR_ASSERTING_INT_CAST(UINT16, MAX(appWindow->y + appWindow->height, 0)) + }; + + REGION16 windowInvalidRegion = { 0 }; + region16_init(&windowInvalidRegion); + region16_union_rect(&windowInvalidRegion, &windowInvalidRegion, &windowRect); + region16_intersect_rect(&windowInvalidRegion, &windowInvalidRegion, rect); + + if (!region16_is_empty(&windowInvalidRegion)) + { + const RECTANGLE_16* extents = region16_extents(&windowInvalidRegion); + + const RECTANGLE_16 updateRect = { + .left = WINPR_ASSERTING_INT_CAST(UINT16, extents->left - appWindow->x), + .top = WINPR_ASSERTING_INT_CAST(UINT16, extents->top - appWindow->y), + .right = WINPR_ASSERTING_INT_CAST(UINT16, extents->right - appWindow->x), + .bottom = WINPR_ASSERTING_INT_CAST(UINT16, extents->bottom - appWindow->y) + }; + + xf_UpdateWindowArea(xfc, appWindow, updateRect.left, updateRect.top, + updateRect.right - updateRect.left, updateRect.bottom - updateRect.top); + } + region16_uninit(&windowInvalidRegion); + return TRUE; +} + +static BOOL rail_paint_fn(const void* pvkey, void* value, void* pvarg) +{ + rail_paint_fn_arg_t* arg = pvarg; + WINPR_ASSERT(pvkey); + WINPR_ASSERT(arg); + + const UINT64 key = *(const UINT64*)pvkey; + return xf_rail_paint_surface(arg->xfc, key, arg->rect); +} + +BOOL xf_rail_paint(xfContext* xfc, const RECTANGLE_16* rect) +{ + rail_paint_fn_arg_t arg = { .xfc = xfc, .rect = rect }; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(rect); + + if (!xfc->railWindows) + return TRUE; + + return HashTable_Foreach(xfc->railWindows, rail_paint_fn, &arg); +} + +#define window_state_log_style(log, windowState) \ + window_state_log_style_int((log), (windowState), __FILE__, __func__, __LINE__) +static void window_state_log_style_int(wLog* log, const WINDOW_STATE_ORDER* windowState, + const char* file, const char* fkt, size_t line) +{ + const DWORD log_level = WLOG_DEBUG; + + WINPR_ASSERT(log); + WINPR_ASSERT(windowState); + if (WLog_IsLevelActive(log, log_level)) + { + char buffer1[128] = { 0 }; + char buffer2[128] = { 0 }; + + window_styles_to_string(windowState->style, buffer1, sizeof(buffer1)); + window_styles_ex_to_string(windowState->extendedStyle, buffer2, sizeof(buffer2)); + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, log_level, line, file, fkt, + "windowStyle={%s, %s}", buffer1, buffer2); + } +} + +/* RemoteApp Core Protocol Extension */ + +static BOOL xf_rail_window_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_STATE_ORDER* windowState) +{ + xfAppWindow* appWindow = NULL; + xfContext* xfc = (xfContext*)context; + UINT32 fieldFlags = orderInfo->fieldFlags; + BOOL position_or_size_updated = FALSE; + appWindow = xf_rail_get_window(xfc, orderInfo->windowId); + + if (fieldFlags & WINDOW_ORDER_STATE_NEW) + { + if (!appWindow) + appWindow = xf_rail_add_window(xfc, orderInfo->windowId, windowState->windowOffsetX, + windowState->windowOffsetY, windowState->windowWidth, + windowState->windowHeight, 0xFFFFFFFF); + + if (!appWindow) + return FALSE; + + appWindow->dwStyle = windowState->style; + appWindow->dwExStyle = windowState->extendedStyle; + window_state_log_style(xfc->log, windowState); + + /* Ensure window always gets a window title */ + if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + union + { + WCHAR* wc; + BYTE* b; + } cnv; + char* title = NULL; + + cnv.b = windowState->titleInfo.string; + if (windowState->titleInfo.length == 0) + { + if (!(title = _strdup(""))) + { + WLog_ERR(TAG, "failed to duplicate empty window title string"); + /* error handled below */ + } + } + else if (!(title = ConvertWCharNToUtf8Alloc( + cnv.wc, windowState->titleInfo.length / sizeof(WCHAR), NULL))) + { + WLog_ERR(TAG, "failed to convert window title"); + /* error handled below */ + } + + appWindow->title = title; + } + else + { + if (!(appWindow->title = _strdup("RdpRailWindow"))) + WLog_ERR(TAG, "failed to duplicate default window title string"); + } + + if (!appWindow->title) + { + free(appWindow); + return FALSE; + } + + xf_AppWindowInit(xfc, appWindow); + } + + if (!appWindow) + return FALSE; + + /* Keep track of any position/size update so that we can force a refresh of the window */ + if ((fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) || + (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) || + (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) || + (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) || + (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) || + (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) || + (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)) + { + position_or_size_updated = TRUE; + } + + /* Update Parameters */ + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) + { + appWindow->windowOffsetX = windowState->windowOffsetX; + appWindow->windowOffsetY = windowState->windowOffsetY; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) + { + appWindow->windowWidth = windowState->windowWidth; + appWindow->windowHeight = windowState->windowHeight; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X) + { + appWindow->resizeMarginLeft = windowState->resizeMarginLeft; + appWindow->resizeMarginRight = windowState->resizeMarginRight; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y) + { + appWindow->resizeMarginTop = windowState->resizeMarginTop; + appWindow->resizeMarginBottom = windowState->resizeMarginBottom; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_OWNER) + { + appWindow->ownerWindowId = windowState->ownerWindowId; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) + { + appWindow->dwStyle = windowState->style; + appWindow->dwExStyle = windowState->extendedStyle; + window_state_log_style(xfc->log, windowState); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) + { + appWindow->showState = windowState->showState; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + char* title = NULL; + union + { + WCHAR* wc; + BYTE* b; + } cnv; + + cnv.b = windowState->titleInfo.string; + if (windowState->titleInfo.length == 0) + { + if (!(title = _strdup(""))) + { + WLog_ERR(TAG, "failed to duplicate empty window title string"); + return FALSE; + } + } + else if (!(title = ConvertWCharNToUtf8Alloc( + cnv.wc, windowState->titleInfo.length / sizeof(WCHAR), NULL))) + { + WLog_ERR(TAG, "failed to convert window title"); + return FALSE; + } + + free(appWindow->title); + appWindow->title = title; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) + { + appWindow->clientOffsetX = windowState->clientOffsetX; + appWindow->clientOffsetY = windowState->clientOffsetY; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) + { + appWindow->clientAreaWidth = windowState->clientAreaWidth; + appWindow->clientAreaHeight = windowState->clientAreaHeight; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) + { + appWindow->windowClientDeltaX = windowState->windowClientDeltaX; + appWindow->windowClientDeltaY = windowState->windowClientDeltaY; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) + { + if (appWindow->windowRects) + { + free(appWindow->windowRects); + appWindow->windowRects = NULL; + } + + appWindow->numWindowRects = windowState->numWindowRects; + + if (appWindow->numWindowRects) + { + appWindow->windowRects = + (RECTANGLE_16*)calloc(appWindow->numWindowRects, sizeof(RECTANGLE_16)); + + if (!appWindow->windowRects) + return FALSE; + + CopyMemory(appWindow->windowRects, windowState->windowRects, + appWindow->numWindowRects * sizeof(RECTANGLE_16)); + } + } + + if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) + { + appWindow->visibleOffsetX = windowState->visibleOffsetX; + appWindow->visibleOffsetY = windowState->visibleOffsetY; + } + + if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) + { + if (appWindow->visibilityRects) + { + free(appWindow->visibilityRects); + appWindow->visibilityRects = NULL; + } + + appWindow->numVisibilityRects = windowState->numVisibilityRects; + + if (appWindow->numVisibilityRects) + { + appWindow->visibilityRects = + (RECTANGLE_16*)calloc(appWindow->numVisibilityRects, sizeof(RECTANGLE_16)); + + if (!appWindow->visibilityRects) + return FALSE; + + CopyMemory(appWindow->visibilityRects, windowState->visibilityRects, + appWindow->numVisibilityRects * sizeof(RECTANGLE_16)); + } + } + + /* Update Window */ + + if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) + { + } + + if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) + { + xf_ShowWindow(xfc, appWindow, WINPR_ASSERTING_INT_CAST(UINT8, appWindow->showState)); + } + + if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) + { + if (appWindow->title) + xf_SetWindowText(xfc, appWindow, appWindow->title); + } + + if (position_or_size_updated) + { + const INT32 visibilityRectsOffsetX = + (appWindow->visibleOffsetX - + (appWindow->clientOffsetX - appWindow->windowClientDeltaX)); + const INT32 visibilityRectsOffsetY = + (appWindow->visibleOffsetY - + (appWindow->clientOffsetY - appWindow->windowClientDeltaY)); + + /* + * The rail server like to set the window to a small size when it is minimized even though + * it is hidden in some cases this can cause the window not to restore back to its original + * size. Therefore we don't update our local window when that rail window state is minimized + */ + if (appWindow->rail_state != WINDOW_SHOW_MINIMIZED) + { + /* Redraw window area if already in the correct position */ + if (appWindow->x == (INT64)appWindow->windowOffsetX && + appWindow->y == (INT64)appWindow->windowOffsetY && + appWindow->width == (INT64)appWindow->windowWidth && + appWindow->height == (INT64)appWindow->windowHeight) + { + xf_UpdateWindowArea(xfc, appWindow, 0, 0, + WINPR_ASSERTING_INT_CAST(int, appWindow->windowWidth), + WINPR_ASSERTING_INT_CAST(int, appWindow->windowHeight)); + } + else + { + xf_MoveWindow(xfc, appWindow, appWindow->windowOffsetX, appWindow->windowOffsetY, + WINPR_ASSERTING_INT_CAST(int, appWindow->windowWidth), + WINPR_ASSERTING_INT_CAST(int, appWindow->windowHeight)); + } + + xf_SetWindowVisibilityRects( + xfc, appWindow, WINPR_ASSERTING_INT_CAST(uint32_t, visibilityRectsOffsetX), + WINPR_ASSERTING_INT_CAST(uint32_t, visibilityRectsOffsetY), + appWindow->visibilityRects, + WINPR_ASSERTING_INT_CAST(int, appWindow->numVisibilityRects)); + } + + if (appWindow->rail_state == WINDOW_SHOW_MAXIMIZED) + { + xf_SendClientEvent(xfc, appWindow->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_ADD, + xfc->_NET_WM_STATE_MAXIMIZED_VERT, xfc->_NET_WM_STATE_MAXIMIZED_HORZ, + 0, 0); + } + } + + if (fieldFlags & (WINDOW_ORDER_STATE_NEW | WINDOW_ORDER_FIELD_STYLE)) + xf_SetWindowStyle(xfc, appWindow, appWindow->dwStyle, appWindow->dwExStyle); + + /* We should only be using the visibility rects for shaping the window */ + /*if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) + { + xf_SetWindowRects(xfc, appWindow, appWindow->windowRects, appWindow->numWindowRects); + }*/ + return TRUE; +} + +static BOOL xf_rail_window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + xfContext* xfc = (xfContext*)context; + return xf_rail_del_window(xfc, orderInfo->windowId); +} + +static xfRailIconCache* RailIconCache_New(rdpSettings* settings) +{ + xfRailIconCache* cache = NULL; + cache = calloc(1, sizeof(xfRailIconCache)); + + if (!cache) + return NULL; + + cache->numCaches = freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCaches); + cache->numCacheEntries = + freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCacheEntries); + cache->entries = calloc(1ull * cache->numCaches * cache->numCacheEntries, sizeof(xfRailIcon)); + + if (!cache->entries) + { + WLog_ERR(TAG, "failed to allocate icon cache %" PRIu32 " x %" PRIu32 " entries", + cache->numCaches, cache->numCacheEntries); + free(cache); + return NULL; + } + + return cache; +} + +static void RailIconCache_Free(xfRailIconCache* cache) +{ + if (cache) + { + for (UINT32 i = 0; i < cache->numCaches * cache->numCacheEntries; i++) + { + free(cache->entries[i].data); + } + + free(cache->scratch.data); + free(cache->entries); + free(cache); + } +} + +static xfRailIcon* RailIconCache_Lookup(xfRailIconCache* cache, UINT8 cacheId, UINT16 cacheEntry) +{ + /* + * MS-RDPERP 2.2.1.2.3 Icon Info (TS_ICON_INFO) + * + * CacheId (1 byte): + * If the value is 0xFFFF, the icon SHOULD NOT be cached. + * + * Yes, the spec says "0xFFFF" in the 2018-03-16 revision, + * but the actual protocol field is 1-byte wide. + */ + if (cacheId == 0xFF) + return &cache->scratch; + + if (cacheId >= cache->numCaches) + return NULL; + + if (cacheEntry >= cache->numCacheEntries) + return NULL; + + return &cache->entries[cache->numCacheEntries * cacheId + cacheEntry]; +} + +/* + * _NET_WM_ICON format is defined as "array of CARDINAL" values which for + * Xlib must be represented with an array of C's "long" values. Note that + * "long" != "INT32" on 64-bit systems. Therefore we can't simply cast + * the bitmap data as (unsigned char*), we have to copy all the pixels. + * + * The first two values are width and height followed by actual color data + * in ARGB format (e.g., 0xFFFF0000L is opaque red), pixels are in normal, + * left-to-right top-down order. + */ +static BOOL convert_rail_icon(const ICON_INFO* iconInfo, xfRailIcon* railIcon) +{ + BYTE* argbPixels = NULL; + BYTE* nextPixel = NULL; + long* pixels = NULL; + argbPixels = calloc(1ull * iconInfo->width * iconInfo->height, 4); + + if (!argbPixels) + goto error; + + if (!freerdp_image_copy_from_icon_data( + argbPixels, PIXEL_FORMAT_ARGB32, 0, 0, 0, + WINPR_ASSERTING_INT_CAST(UINT16, iconInfo->width), + WINPR_ASSERTING_INT_CAST(UINT16, iconInfo->height), iconInfo->bitsColor, + WINPR_ASSERTING_INT_CAST(UINT16, iconInfo->cbBitsColor), iconInfo->bitsMask, + WINPR_ASSERTING_INT_CAST(UINT16, iconInfo->cbBitsMask), iconInfo->colorTable, + WINPR_ASSERTING_INT_CAST(UINT16, iconInfo->cbColorTable), iconInfo->bpp)) + goto error; + + const UINT32 nelements = 2 + iconInfo->width * iconInfo->height; + pixels = realloc(railIcon->data, nelements * sizeof(long)); + + if (!pixels) + goto error; + + railIcon->data = pixels; + + railIcon->length = WINPR_ASSERTING_INT_CAST(int, nelements); + pixels[0] = iconInfo->width; + pixels[1] = iconInfo->height; + nextPixel = argbPixels; + + for (UINT32 i = 2; i < nelements; i++) + { + pixels[i] = FreeRDPReadColor(nextPixel, PIXEL_FORMAT_BGRA32); + nextPixel += 4; + } + + free(argbPixels); + return TRUE; +error: + free(argbPixels); + return FALSE; +} + +static void xf_rail_set_window_icon(xfContext* xfc, xfAppWindow* railWindow, xfRailIcon* icon, + BOOL replace) +{ + WINPR_ASSERT(xfc); + + LogTagAndXChangeProperty(TAG, xfc->display, railWindow->handle, xfc->_NET_WM_ICON, XA_CARDINAL, + 32, replace ? PropModeReplace : PropModeAppend, + (unsigned char*)icon->data, icon->length); + XFlush(xfc->display); +} + +static BOOL xf_rail_window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_ICON_ORDER* windowIcon) +{ + xfContext* xfc = (xfContext*)context; + BOOL replaceIcon = 0; + xfAppWindow* railWindow = xf_rail_get_window(xfc, orderInfo->windowId); + + if (!railWindow) + return TRUE; + + WINPR_ASSERT(windowIcon); + WINPR_ASSERT(windowIcon->iconInfo); + xfRailIcon* icon = RailIconCache_Lookup( + xfc->railIconCache, WINPR_ASSERTING_INT_CAST(UINT8, windowIcon->iconInfo->cacheId), + WINPR_ASSERTING_INT_CAST(UINT16, windowIcon->iconInfo->cacheEntry)); + + if (!icon) + { + WLog_WARN(TAG, "failed to get icon from cache %02X:%04X", windowIcon->iconInfo->cacheId, + windowIcon->iconInfo->cacheEntry); + return FALSE; + } + + if (!convert_rail_icon(windowIcon->iconInfo, icon)) + { + WLog_WARN(TAG, "failed to convert icon for window %08X", orderInfo->windowId); + return FALSE; + } + + replaceIcon = !!(orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW); + xf_rail_set_window_icon(xfc, railWindow, icon, replaceIcon); + return TRUE; +} + +static BOOL xf_rail_window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const WINDOW_CACHED_ICON_ORDER* windowCachedIcon) +{ + xfContext* xfc = (xfContext*)context; + xfAppWindow* railWindow = NULL; + xfRailIcon* icon = NULL; + BOOL replaceIcon = 0; + railWindow = xf_rail_get_window(xfc, orderInfo->windowId); + + if (!railWindow) + return TRUE; + + icon = RailIconCache_Lookup( + xfc->railIconCache, WINPR_ASSERTING_INT_CAST(UINT8, windowCachedIcon->cachedIcon.cacheId), + WINPR_ASSERTING_INT_CAST(UINT16, windowCachedIcon->cachedIcon.cacheEntry)); + + if (!icon) + { + WLog_WARN(TAG, "failed to get icon from cache %02X:%04X", + windowCachedIcon->cachedIcon.cacheId, windowCachedIcon->cachedIcon.cacheEntry); + return FALSE; + } + + replaceIcon = !!(orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW); + xf_rail_set_window_icon(xfc, railWindow, icon, replaceIcon); + return TRUE; +} + +static BOOL xf_rail_notify_icon_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_ICON) + { + } + + if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) + { + } + + return TRUE; +} + +static BOOL xf_rail_notify_icon_create(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + return xf_rail_notify_icon_common(context, orderInfo, notifyIconState); +} + +static BOOL xf_rail_notify_icon_update(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const NOTIFY_ICON_STATE_ORDER* notifyIconState) +{ + return xf_rail_notify_icon_common(context, orderInfo, notifyIconState); +} + +static BOOL xf_rail_notify_icon_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + return TRUE; +} + +static BOOL xf_rail_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo, + const MONITORED_DESKTOP_ORDER* monitoredDesktop) +{ + return TRUE; +} + +static BOOL xf_rail_non_monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo) +{ + xfContext* xfc = (xfContext*)context; + xf_rail_disable_remoteapp_mode(xfc); + return TRUE; +} + +static void xf_rail_register_update_callbacks(rdpUpdate* update) +{ + rdpWindowUpdate* window = update->window; + window->WindowCreate = xf_rail_window_common; + window->WindowUpdate = xf_rail_window_common; + window->WindowDelete = xf_rail_window_delete; + window->WindowIcon = xf_rail_window_icon; + window->WindowCachedIcon = xf_rail_window_cached_icon; + window->NotifyIconCreate = xf_rail_notify_icon_create; + window->NotifyIconUpdate = xf_rail_notify_icon_update; + window->NotifyIconDelete = xf_rail_notify_icon_delete; + window->MonitoredDesktop = xf_rail_monitored_desktop; + window->NonMonitoredDesktop = xf_rail_non_monitored_desktop; +} + +/* RemoteApp Virtual Channel Extension */ + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_execute_result(RailClientContext* context, + const RAIL_EXEC_RESULT_ORDER* execResult) +{ + xfContext* xfc = NULL; + + WINPR_ASSERT(context); + WINPR_ASSERT(execResult); + + xfc = (xfContext*)context->custom; + WINPR_ASSERT(xfc); + + if (execResult->execResult != RAIL_EXEC_S_OK) + { + WLog_ERR(TAG, "RAIL exec error: execResult=%s NtError=0x%X\n", + error_code_names[execResult->execResult], execResult->rawResult); + freerdp_abort_connect_context(&xfc->common.context); + } + else + { + xf_rail_enable_remoteapp_mode(xfc); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_system_param(RailClientContext* context, + const RAIL_SYSPARAM_ORDER* sysparam) +{ + // TODO: Actually apply param + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_handshake(RailClientContext* context, + const RAIL_HANDSHAKE_ORDER* handshake) +{ + return client_rail_server_start_cmd(context); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_handshake_ex(RailClientContext* context, + const RAIL_HANDSHAKE_EX_ORDER* handshakeEx) +{ + return client_rail_server_start_cmd(context); +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_local_move_size(RailClientContext* context, + const RAIL_LOCALMOVESIZE_ORDER* localMoveSize) +{ + int x = 0; + int y = 0; + int direction = 0; + Window child_window = 0; + xfContext* xfc = (xfContext*)context->custom; + xfAppWindow* appWindow = xf_rail_get_window(xfc, localMoveSize->windowId); + + if (!appWindow) + return ERROR_INTERNAL_ERROR; + + switch (localMoveSize->moveSizeType) + { + case RAIL_WMSZ_LEFT: + direction = _NET_WM_MOVERESIZE_SIZE_LEFT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_RIGHT: + direction = _NET_WM_MOVERESIZE_SIZE_RIGHT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_TOP: + direction = _NET_WM_MOVERESIZE_SIZE_TOP; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_TOPLEFT: + direction = _NET_WM_MOVERESIZE_SIZE_TOPLEFT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_TOPRIGHT: + direction = _NET_WM_MOVERESIZE_SIZE_TOPRIGHT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_BOTTOM: + direction = _NET_WM_MOVERESIZE_SIZE_BOTTOM; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_BOTTOMLEFT: + direction = _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_BOTTOMRIGHT: + direction = _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT; + x = localMoveSize->posX; + y = localMoveSize->posY; + break; + + case RAIL_WMSZ_MOVE: + direction = _NET_WM_MOVERESIZE_MOVE; + XTranslateCoordinates(xfc->display, appWindow->handle, RootWindowOfScreen(xfc->screen), + localMoveSize->posX, localMoveSize->posY, &x, &y, &child_window); + break; + + case RAIL_WMSZ_KEYMOVE: + direction = _NET_WM_MOVERESIZE_MOVE_KEYBOARD; + x = localMoveSize->posX; + y = localMoveSize->posY; + /* FIXME: local keyboard moves not working */ + return CHANNEL_RC_OK; + + case RAIL_WMSZ_KEYSIZE: + direction = _NET_WM_MOVERESIZE_SIZE_KEYBOARD; + x = localMoveSize->posX; + y = localMoveSize->posY; + /* FIXME: local keyboard moves not working */ + return CHANNEL_RC_OK; + default: + break; + } + + if (localMoveSize->isMoveSizeStart) + xf_StartLocalMoveSize(xfc, appWindow, direction, x, y); + else + xf_EndLocalMoveSize(xfc, appWindow); + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_min_max_info(RailClientContext* context, + const RAIL_MINMAXINFO_ORDER* minMaxInfo) +{ + xfContext* xfc = (xfContext*)context->custom; + xfAppWindow* appWindow = xf_rail_get_window(xfc, minMaxInfo->windowId); + + if (appWindow) + { + xf_SetWindowMinMaxInfo(xfc, appWindow, minMaxInfo->maxWidth, minMaxInfo->maxHeight, + minMaxInfo->maxPosX, minMaxInfo->maxPosY, minMaxInfo->minTrackWidth, + minMaxInfo->minTrackHeight, minMaxInfo->maxTrackWidth, + minMaxInfo->maxTrackHeight); + } + + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_language_bar_info(RailClientContext* context, + const RAIL_LANGBAR_INFO_ORDER* langBarInfo) +{ + return CHANNEL_RC_OK; +} + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT xf_rail_server_get_appid_response(RailClientContext* context, + const RAIL_GET_APPID_RESP_ORDER* getAppIdResp) +{ + return CHANNEL_RC_OK; +} + +static BOOL rail_window_key_equals(const void* key1, const void* key2) +{ + const UINT64* k1 = (const UINT64*)key1; + const UINT64* k2 = (const UINT64*)key2; + + if (!k1 || !k2) + return FALSE; + + return *k1 == *k2; +} + +static UINT32 rail_window_key_hash(const void* key) +{ + const UINT64* k1 = (const UINT64*)key; + return (UINT32)*k1; +} + +static void rail_window_free(void* value) +{ + xfAppWindow* appWindow = (xfAppWindow*)value; + + if (!appWindow) + return; + + xf_DestroyWindow(appWindow->xfc, appWindow); +} + +int xf_rail_init(xfContext* xfc, RailClientContext* rail) +{ + rdpContext* context = (rdpContext*)xfc; + + if (!xfc || !rail) + return 0; + + xfc->rail = rail; + xf_rail_register_update_callbacks(context->update); + rail->custom = (void*)xfc; + rail->ServerExecuteResult = xf_rail_server_execute_result; + rail->ServerSystemParam = xf_rail_server_system_param; + rail->ServerHandshake = xf_rail_server_handshake; + rail->ServerHandshakeEx = xf_rail_server_handshake_ex; + rail->ServerLocalMoveSize = xf_rail_server_local_move_size; + rail->ServerMinMaxInfo = xf_rail_server_min_max_info; + rail->ServerLanguageBarInfo = xf_rail_server_language_bar_info; + rail->ServerGetAppIdResponse = xf_rail_server_get_appid_response; + xfc->railWindows = HashTable_New(TRUE); + + if (!xfc->railWindows) + return 0; + + if (!HashTable_SetHashFunction(xfc->railWindows, rail_window_key_hash)) + goto fail; + { + wObject* obj = HashTable_KeyObject(xfc->railWindows); + obj->fnObjectEquals = rail_window_key_equals; + } + { + wObject* obj = HashTable_ValueObject(xfc->railWindows); + obj->fnObjectFree = rail_window_free; + } + xfc->railIconCache = RailIconCache_New(xfc->common.context.settings); + + if (!xfc->railIconCache) + { + } + + return 1; +fail: + HashTable_Free(xfc->railWindows); + return 0; +} + +int xf_rail_uninit(xfContext* xfc, RailClientContext* rail) +{ + WINPR_UNUSED(rail); + + if (xfc->rail) + { + xfc->rail->custom = NULL; + xfc->rail = NULL; + } + + if (xfc->railWindows) + { + HashTable_Free(xfc->railWindows); + xfc->railWindows = NULL; + } + + if (xfc->railIconCache) + { + RailIconCache_Free(xfc->railIconCache); + xfc->railIconCache = NULL; + } + + return 1; +} + +xfAppWindow* xf_rail_add_window(xfContext* xfc, UINT64 id, INT32 x, INT32 y, UINT32 width, + UINT32 height, UINT32 surfaceId) +{ + xfAppWindow* appWindow = NULL; + + if (!xfc) + return NULL; + + appWindow = (xfAppWindow*)calloc(1, sizeof(xfAppWindow)); + + if (!appWindow) + return NULL; + + appWindow->xfc = xfc; + appWindow->windowId = id; + appWindow->surfaceId = surfaceId; + appWindow->x = x; + appWindow->y = y; + appWindow->width = WINPR_ASSERTING_INT_CAST(int, width); + appWindow->height = WINPR_ASSERTING_INT_CAST(int, height); + + if (!xf_AppWindowCreate(xfc, appWindow)) + goto fail; + if (!HashTable_Insert(xfc->railWindows, &appWindow->windowId, (void*)appWindow)) + goto fail; + return appWindow; +fail: + rail_window_free(appWindow); + return NULL; +} + +BOOL xf_rail_del_window(xfContext* xfc, UINT64 id) +{ + if (!xfc) + return FALSE; + + if (!xfc->railWindows) + return FALSE; + + return HashTable_Remove(xfc->railWindows, &id); +} + +xfAppWindow* xf_rail_get_window(xfContext* xfc, UINT64 id) +{ + if (!xfc) + return NULL; + + if (!xfc->railWindows) + return FALSE; + + return HashTable_GetItemValue(xfc->railWindows, &id); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.h new file mode 100644 index 0000000000000000000000000000000000000000..8d2fd704496c757a4c89fe119641216ee2788e7d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_rail.h @@ -0,0 +1,47 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 RAIL + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_RAIL_H +#define FREERDP_CLIENT_X11_RAIL_H + +#include "xf_client.h" +#include "xfreerdp.h" + +#include + +BOOL xf_rail_paint(xfContext* xfc, const RECTANGLE_16* rect); +BOOL xf_rail_paint_surface(xfContext* xfc, UINT64 windowId, const RECTANGLE_16* rect); + +BOOL xf_rail_send_client_system_command(xfContext* xfc, UINT64 windowId, UINT16 command); +void xf_rail_send_activate(xfContext* xfc, Window xwindow, BOOL enabled); +void xf_rail_adjust_position(xfContext* xfc, xfAppWindow* appWindow); +void xf_rail_end_local_move(xfContext* xfc, xfAppWindow* appWindow); +void xf_rail_enable_remoteapp_mode(xfContext* xfc); +void xf_rail_disable_remoteapp_mode(xfContext* xfc); + +xfAppWindow* xf_rail_add_window(xfContext* xfc, UINT64 id, INT32 x, INT32 y, UINT32 width, + UINT32 height, UINT32 surfaceId); +xfAppWindow* xf_rail_get_window(xfContext* xfc, UINT64 id); + +BOOL xf_rail_del_window(xfContext* xfc, UINT64 id); + +int xf_rail_init(xfContext* xfc, RailClientContext* rail); +int xf_rail_uninit(xfContext* xfc, RailClientContext* rail); + +#endif /* FREERDP_CLIENT_X11_RAIL_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.c new file mode 100644 index 0000000000000000000000000000000000000000..9ed346009069f910fd89c1cee67ec846c0e7a699 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.c @@ -0,0 +1,479 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Video Redirection + * + * Copyright 2010-2011 Vic Lee + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "xf_tsmf.h" +#include "xf_utils.h" + +#ifdef WITH_XV + +#include +#include + +static long xv_port = 0; + +struct xf_xv_context +{ + long xv_port; + Atom xv_colorkey_atom; + int xv_image_size; + int xv_shmid; + char* xv_shmaddr; + UINT32* xv_pixfmts; +}; +typedef struct xf_xv_context xfXvContext; + +#define TAG CLIENT_TAG("x11") + +static BOOL xf_tsmf_is_format_supported(xfXvContext* xv, UINT32 pixfmt) +{ + if (!xv->xv_pixfmts) + return FALSE; + + for (int i = 0; xv->xv_pixfmts[i]; i++) + { + if (xv->xv_pixfmts[i] == pixfmt) + return TRUE; + } + + return FALSE; +} + +static int xf_tsmf_xv_video_frame_event(TsmfClientContext* tsmf, TSMF_VIDEO_FRAME_EVENT* event) +{ + int x = 0; + int y = 0; + UINT32 width = 0; + UINT32 height = 0; + BYTE* data1 = NULL; + BYTE* data2 = NULL; + UINT32 pixfmt = 0; + UINT32 xvpixfmt = 0; + XvImage* image = NULL; + int colorkey = 0; + int numRects = 0; + xfContext* xfc = NULL; + xfXvContext* xv = NULL; + XRectangle* xrects = NULL; + XShmSegmentInfo shminfo; + BOOL converti420yv12 = FALSE; + + if (!tsmf) + return -1; + + xfc = (xfContext*)tsmf->custom; + + if (!xfc) + return -1; + + xv = (xfXvContext*)xfc->xv_context; + + if (!xv) + return -1; + + if (xv->xv_port == 0) + return -1001; + + /* In case the player is minimized */ + if (event->x < -2048 || event->y < -2048 || event->numVisibleRects == 0) + { + return -1002; + } + + xrects = NULL; + numRects = event->numVisibleRects; + + if (numRects > 0) + { + xrects = (XRectangle*)calloc(numRects, sizeof(XRectangle)); + + if (!xrects) + return -1; + + for (int i = 0; i < numRects; i++) + { + x = event->x + event->visibleRects[i].left; + y = event->y + event->visibleRects[i].top; + width = event->visibleRects[i].right - event->visibleRects[i].left; + height = event->visibleRects[i].bottom - event->visibleRects[i].top; + + xrects[i].x = x; + xrects[i].y = y; + xrects[i].width = width; + xrects[i].height = height; + } + } + + if (xv->xv_colorkey_atom != None) + { + XvGetPortAttribute(xfc->display, xv->xv_port, xv->xv_colorkey_atom, &colorkey); + XSetFunction(xfc->display, xfc->gc, GXcopy); + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + XSetForeground(xfc->display, xfc->gc, colorkey); + + if (event->numVisibleRects < 1) + { + XSetClipMask(xfc->display, xfc->gc, None); + } + else + { + XFillRectangles(xfc->display, xfc->window->handle, xfc->gc, xrects, numRects); + } + } + else + { + XSetFunction(xfc->display, xfc->gc, GXcopy); + XSetFillStyle(xfc->display, xfc->gc, FillSolid); + + if (event->numVisibleRects < 1) + { + XSetClipMask(xfc->display, xfc->gc, None); + } + else + { + XSetClipRectangles(xfc->display, xfc->gc, 0, 0, xrects, numRects, YXBanded); + } + } + + pixfmt = event->framePixFmt; + + if (xf_tsmf_is_format_supported(xv, pixfmt)) + { + xvpixfmt = pixfmt; + } + else if (pixfmt == RDP_PIXFMT_I420 && xf_tsmf_is_format_supported(xv, RDP_PIXFMT_YV12)) + { + xvpixfmt = RDP_PIXFMT_YV12; + converti420yv12 = TRUE; + } + else if (pixfmt == RDP_PIXFMT_YV12 && xf_tsmf_is_format_supported(xv, RDP_PIXFMT_I420)) + { + xvpixfmt = RDP_PIXFMT_I420; + converti420yv12 = TRUE; + } + else + { + WLog_DBG(TAG, "pixel format 0x%" PRIX32 " not supported by hardware.", pixfmt); + free(xrects); + return -1003; + } + + image = XvShmCreateImage(xfc->display, xv->xv_port, xvpixfmt, 0, event->frameWidth, + event->frameHeight, &shminfo); + + if (xv->xv_image_size != image->data_size) + { + if (xv->xv_image_size > 0) + { + shmdt(xv->xv_shmaddr); + shmctl(xv->xv_shmid, IPC_RMID, NULL); + } + + xv->xv_image_size = image->data_size; + xv->xv_shmid = shmget(IPC_PRIVATE, image->data_size, IPC_CREAT | 0777); + xv->xv_shmaddr = shmat(xv->xv_shmid, 0, 0); + } + + shminfo.shmid = xv->xv_shmid; + shminfo.shmaddr = image->data = xv->xv_shmaddr; + shminfo.readOnly = FALSE; + + if (!XShmAttach(xfc->display, &shminfo)) + { + XFree(image); + free(xrects); + WLog_DBG(TAG, "XShmAttach failed."); + return -1004; + } + + /* The video driver may align each line to a different size + and we need to convert our original image data. */ + switch (pixfmt) + { + case RDP_PIXFMT_I420: + case RDP_PIXFMT_YV12: + /* Y */ + if (image->pitches[0] == event->frameWidth) + { + CopyMemory(image->data + image->offsets[0], event->frameData, + 1ULL * event->frameWidth * event->frameHeight); + } + else + { + for (int i = 0; i < event->frameHeight; i++) + { + CopyMemory(image->data + 1ULL * image->offsets[0] + + 1ULL * i * image->pitches[0], + event->frameData + 1ULL * i * event->frameWidth, event->frameWidth); + } + } + /* UV */ + /* Conversion between I420 and YV12 is to simply swap U and V */ + if (!converti420yv12) + { + data1 = event->frameData + 1ULL * event->frameWidth * event->frameHeight; + data2 = event->frameData + 1ULL * event->frameWidth * event->frameHeight + + 1ULL * event->frameWidth * event->frameHeight / 4; + } + else + { + data2 = event->frameData + 1ULL * event->frameWidth * event->frameHeight; + data1 = event->frameData + 1ULL * event->frameWidth * event->frameHeight + + 1ULL * event->frameWidth * event->frameHeight / 4; + image->id = pixfmt == RDP_PIXFMT_I420 ? RDP_PIXFMT_YV12 : RDP_PIXFMT_I420; + } + + if (image->pitches[1] * 2 == event->frameWidth) + { + CopyMemory(image->data + image->offsets[1], data1, + event->frameWidth * event->frameHeight / 4); + CopyMemory(image->data + image->offsets[2], data2, + event->frameWidth * event->frameHeight / 4); + } + else + { + for (int i = 0; i < event->frameHeight / 2; i++) + { + CopyMemory(image->data + 1ULL * image->offsets[1] + + 1ULL * i * image->pitches[1], + data1 + 1ULL * i * event->frameWidth / 2, event->frameWidth / 2); + CopyMemory(image->data + 1ULL * image->offsets[2] + + 1ULL * i * image->pitches[2], + data2 + 1ULL * i * event->frameWidth / 2, event->frameWidth / 2); + } + } + break; + + default: + if (image->data_size < 0) + { + free(xrects); + return -2000; + } + else + { + const size_t size = ((UINT32)image->data_size <= event->frameSize) + ? (UINT32)image->data_size + : event->frameSize; + CopyMemory(image->data, event->frameData, size); + } + break; + } + + XvShmPutImage(xfc->display, xv->xv_port, xfc->window->handle, xfc->gc, image, 0, 0, + image->width, image->height, event->x, event->y, event->width, event->height, + FALSE); + + if (xv->xv_colorkey_atom == None) + XSetClipMask(xfc->display, xfc->gc, None); + + XSync(xfc->display, FALSE); + + XShmDetach(xfc->display, &shminfo); + XFree(image); + + free(xrects); + + return 1; +} + +static int xf_tsmf_xv_init(xfContext* xfc, TsmfClientContext* tsmf) +{ + int ret = 0; + unsigned int version = 0; + unsigned int release = 0; + unsigned int event_base = 0; + unsigned int error_base = 0; + unsigned int request_base = 0; + unsigned int num_adaptors = 0; + xfXvContext* xv = NULL; + XvAdaptorInfo* ai = NULL; + XvAttribute* attr = NULL; + XvImageFormatValues* fo = NULL; + + if (xfc->xv_context) + return 1; /* context already created */ + + xv = (xfXvContext*)calloc(1, sizeof(xfXvContext)); + + if (!xv) + return -1; + + xfc->xv_context = xv; + + xv->xv_colorkey_atom = None; + xv->xv_image_size = 0; + xv->xv_port = xv_port; + + if (!XShmQueryExtension(xfc->display)) + { + WLog_DBG(TAG, "no xshm available."); + return -1; + } + + ret = + XvQueryExtension(xfc->display, &version, &release, &request_base, &event_base, &error_base); + + if (ret != Success) + { + WLog_DBG(TAG, "XvQueryExtension failed %d.", ret); + return -1; + } + + WLog_DBG(TAG, "version %u release %u", version, release); + + ret = XvQueryAdaptors(xfc->display, DefaultRootWindow(xfc->display), &num_adaptors, &ai); + + if (ret != Success) + { + WLog_DBG(TAG, "XvQueryAdaptors failed %d.", ret); + return -1; + } + + for (unsigned int i = 0; i < num_adaptors; i++) + { + WLog_DBG(TAG, "adapter port %lu-%lu (%s)", ai[i].base_id, + ai[i].base_id + ai[i].num_ports - 1, ai[i].name); + + if (xv->xv_port == 0 && i == num_adaptors - 1) + xv->xv_port = ai[i].base_id; + } + + if (num_adaptors > 0) + XvFreeAdaptorInfo(ai); + + if (xv->xv_port == 0) + { + WLog_DBG(TAG, "no adapter selected, video frames will not be processed."); + return -1; + } + WLog_DBG(TAG, "selected %ld", xv->xv_port); + + attr = XvQueryPortAttributes(xfc->display, xv->xv_port, &ret); + + unsigned int i = 0; + for (; i < (unsigned int)ret; i++) + { + if (strcmp(attr[i].name, "XV_COLORKEY") == 0) + { + static wLog* log = NULL; + if (!log) + log = WLog_Get(TAG); + xv->xv_colorkey_atom = Logging_XInternAtom(log, xfc->display, "XV_COLORKEY", FALSE); + XvSetPortAttribute(xfc->display, xv->xv_port, xv->xv_colorkey_atom, + attr[i].min_value + 1); + break; + } + } + XFree(attr); + + WLog_DBG(TAG, "xf_tsmf_init: pixel format "); + + fo = XvListImageFormats(xfc->display, xv->xv_port, &ret); + + if (ret > 0) + { + xv->xv_pixfmts = (UINT32*)calloc((ret + 1), sizeof(UINT32)); + + size_t x = 0; + for (; x < (size_t)ret; x++) + { + xv->xv_pixfmts[x] = fo[x].id; + WLog_DBG(TAG, "%c%c%c%c ", ((char*)(xv->xv_pixfmts + x))[0], + ((char*)(xv->xv_pixfmts + x))[1], ((char*)(xv->xv_pixfmts + x))[2], + ((char*)(xv->xv_pixfmts + x))[3]); + } + xv->xv_pixfmts[x] = 0; + } + XFree(fo); + + if (tsmf) + { + xfc->tsmf = tsmf; + tsmf->custom = (void*)xfc; + + tsmf->FrameEvent = xf_tsmf_xv_video_frame_event; + } + + return 1; +} + +static int xf_tsmf_xv_uninit(xfContext* xfc, TsmfClientContext* tsmf) +{ + xfXvContext* xv = (xfXvContext*)xfc->xv_context; + + WINPR_UNUSED(tsmf); + if (xv) + { + if (xv->xv_image_size > 0) + { + shmdt(xv->xv_shmaddr); + shmctl(xv->xv_shmid, IPC_RMID, NULL); + } + if (xv->xv_pixfmts) + { + free(xv->xv_pixfmts); + xv->xv_pixfmts = NULL; + } + free(xv); + xfc->xv_context = NULL; + } + + if (xfc->tsmf) + { + xfc->tsmf->custom = NULL; + xfc->tsmf = NULL; + } + + return 1; +} + +#endif + +int xf_tsmf_init(xfContext* xfc, TsmfClientContext* tsmf) +{ +#ifdef WITH_XV + return xf_tsmf_xv_init(xfc, tsmf); +#else + return 1; +#endif +} + +int xf_tsmf_uninit(xfContext* xfc, TsmfClientContext* tsmf) +{ +#ifdef WITH_XV + return xf_tsmf_xv_uninit(xfc, tsmf); +#else + return 1; +#endif +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.h new file mode 100644 index 0000000000000000000000000000000000000000..63a973aa730391efb380b304baa847b71cdf22a9 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_tsmf.h @@ -0,0 +1,29 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Video Redirection + * + * Copyright 2010-2011 Vic Lee + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_TSMF_H +#define FREERDP_CLIENT_X11_TSMF_H + +#include "xf_client.h" +#include "xfreerdp.h" + +int xf_tsmf_init(xfContext* xfc, TsmfClientContext* tsmf); +int xf_tsmf_uninit(xfContext* xfc, TsmfClientContext* tsmf); + +#endif /* FREERDP_CLIENT_X11_TSMF_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..fe2eb2ea1a2a5137a8eb640f910830646de1d4d5 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.c @@ -0,0 +1,239 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 helper utilities + * + * Copyright 2023 Armin Novak + * Copyringht 2023 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "xf_utils.h" +#include "xfreerdp.h" + +#include + +#define TAG CLIENT_TAG("xfreerdp.utils") + +static const DWORD log_level = WLOG_TRACE; + +static void write_log(wLog* log, DWORD level, const char* fname, const char* fkt, size_t line, ...) +{ + va_list ap = { 0 }; + va_start(ap, line); + WLog_PrintMessageVA(log, WLOG_MESSAGE_TEXT, level, line, fname, fkt, ap); + va_end(ap); +} + +char* Safe_XGetAtomNameEx(wLog* log, Display* display, Atom atom, const char* varname) +{ + WLog_Print(log, log_level, "XGetAtomName(%s, 0x%08" PRIx32 ")", varname, atom); + if (atom == None) + return strdup("Atom_None"); + return XGetAtomName(display, atom); +} + +Atom Logging_XInternAtom(wLog* log, Display* display, _Xconst char* atom_name, Bool only_if_exists) +{ + Atom atom = XInternAtom(display, atom_name, only_if_exists); + if (WLog_IsLevelActive(log, log_level)) + { + WLog_Print(log, log_level, "XInternAtom(0x%08" PRIx32 ", %s, %s) -> 0x%08" PRIx32, display, + atom_name, only_if_exists ? "True" : "False", atom); + } + return atom; +} + +int LogTagAndXChangeProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, Atom type, int format, + int mode, const unsigned char* data, int nelements) +{ + wLog* log = WLog_Get(tag); + return LogDynAndXChangeProperty_ex(log, file, fkt, line, display, w, property, type, format, + mode, data, nelements); +} + +int LogDynAndXChangeProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, Atom type, int format, + int mode, const unsigned char* data, int nelements) +{ + if (WLog_IsLevelActive(log, log_level)) + { + char* propstr = Safe_XGetAtomName(log, display, property); + char* typestr = Safe_XGetAtomName(log, display, type); + write_log(log, log_level, file, fkt, line, + "XChangeProperty(%p, %d, %s [%d], %s [%d], %d, %d, %p, %d)", display, w, propstr, + property, typestr, type, format, mode, data, nelements); + XFree(propstr); + XFree(typestr); + } + return XChangeProperty(display, w, property, type, format, mode, data, nelements); +} + +int LogTagAndXDeleteProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property) +{ + wLog* log = WLog_Get(tag); + return LogDynAndXDeleteProperty_ex(log, file, fkt, line, display, w, property); +} + +int LogDynAndXDeleteProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property) +{ + if (WLog_IsLevelActive(log, log_level)) + { + char* propstr = Safe_XGetAtomName(log, display, property); + write_log(log, log_level, file, fkt, line, "XDeleteProperty(%p, %d, %s [%d])", display, w, + propstr, property); + XFree(propstr); + } + return XDeleteProperty(display, w, property); +} + +int LogTagAndXConvertSelection_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Atom selection, Atom target, Atom property, + Window requestor, Time time) +{ + wLog* log = WLog_Get(tag); + return LogDynAndXConvertSelection_ex(log, file, fkt, line, display, selection, target, property, + requestor, time); +} + +int LogDynAndXConvertSelection_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Atom selection, Atom target, Atom property, + Window requestor, Time time) +{ + if (WLog_IsLevelActive(log, log_level)) + { + char* selectstr = Safe_XGetAtomName(log, display, selection); + char* targetstr = Safe_XGetAtomName(log, display, target); + char* propstr = Safe_XGetAtomName(log, display, property); + write_log(log, log_level, file, fkt, line, + "XConvertSelection(%p, %s [%d], %s [%d], %s [%d], %d, %lu)", display, selectstr, + selection, targetstr, target, propstr, property, requestor, time); + XFree(propstr); + XFree(targetstr); + XFree(selectstr); + } + return XConvertSelection(display, selection, target, property, requestor, time); +} + +int LogTagAndXGetWindowProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, long long_offset, + long long_length, int delete, Atom req_type, + Atom* actual_type_return, int* actual_format_return, + unsigned long* nitems_return, unsigned long* bytes_after_return, + unsigned char** prop_return) +{ + wLog* log = WLog_Get(tag); + return LogDynAndXGetWindowProperty_ex( + log, file, fkt, line, display, w, property, long_offset, long_length, delete, req_type, + actual_type_return, actual_format_return, nitems_return, bytes_after_return, prop_return); +} + +int LogDynAndXGetWindowProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, long long_offset, + long long_length, int delete, Atom req_type, + Atom* actual_type_return, int* actual_format_return, + unsigned long* nitems_return, unsigned long* bytes_after_return, + unsigned char** prop_return) +{ + if (WLog_IsLevelActive(log, log_level)) + { + char* propstr = Safe_XGetAtomName(log, display, property); + char* req_type_str = Safe_XGetAtomName(log, display, req_type); + write_log(log, log_level, file, fkt, line, + "XGetWindowProperty(%p, %d, %s [%d], %ld, %ld, %d, %s [%d], %p, %p, %p, %p, %p)", + display, w, propstr, property, long_offset, long_length, delete, req_type_str, + req_type, actual_type_return, actual_format_return, nitems_return, + bytes_after_return, prop_return); + XFree(propstr); + XFree(req_type_str); + } + return XGetWindowProperty(display, w, property, long_offset, long_length, delete, req_type, + actual_type_return, actual_format_return, nitems_return, + bytes_after_return, prop_return); +} + +BOOL IsGnome(void) +{ + // NOLINTNEXTLINE(concurrency-mt-unsafe) + char* env = getenv("DESKTOP_SESSION"); + return (env != NULL && strcmp(env, "gnome") == 0); +} + +BOOL run_action_script(xfContext* xfc, const char* what, const char* arg, fn_action_script_run fkt, + void* user) +{ + BOOL rc = FALSE; + FILE* keyScript = NULL; + WINPR_ASSERT(xfc); + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + const char* ActionScript = freerdp_settings_get_string(settings, FreeRDP_ActionScript); + + xfc->actionScriptExists = winpr_PathFileExists(ActionScript); + + if (!xfc->actionScriptExists) + goto fail; + + char command[2048] = { 0 }; + (void)sprintf_s(command, sizeof(command), "%s %s", ActionScript, what); + keyScript = popen(command, "r"); + + if (!keyScript) + { + WLog_ERR(TAG, "Failed to execute '%s'", command); + goto fail; + } + + BOOL read_data = FALSE; + char buffer[2048] = { 0 }; + while (fgets(buffer, sizeof(buffer), keyScript) != NULL) + { + char* context = NULL; + (void)strtok_s(buffer, "\n", &context); + + if (fkt) + { + if (!fkt(xfc, buffer, strnlen(buffer, sizeof(buffer)), user, what, arg)) + goto fail; + } + read_data = TRUE; + } + + rc = read_data; +fail: + if (!rc) + xfc->actionScriptExists = FALSE; + if (keyScript) + pclose(keyScript); + return rc; +} + +const char* x11_error_to_string(xfContext* xfc, int error, char* buffer, size_t size) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(size <= INT32_MAX); + const int rc = XGetErrorText(xfc->display, error, buffer, (int)size); + if (rc) + WLog_WARN(TAG, "XGetErrorText returned %d", rc); + return buffer; +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..81b020eff8e0b92f1ab733fda7c5f30fcaf4c608 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_utils.h @@ -0,0 +1,106 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 helper utilities + * + * Copyright 2023 Armin Novak + * Copyringht 2023 Thincast Technologies GmbH + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include + +#include +#include "xfreerdp.h" + +const char* x11_error_to_string(xfContext* xfc, int error, char* buffer, size_t size); + +#define X_GET_ATOM_VAR_NAME(x) #x +#define Safe_XGetAtomName(log, display, atom) \ + Safe_XGetAtomNameEx((log), (display), (atom), X_GET_ATOM_VAR_NAME(atom)) +char* Safe_XGetAtomNameEx(wLog* log, Display* display, Atom atom, const char* varname); +Atom Logging_XInternAtom(wLog* log, Display* display, _Xconst char* atom_name, Bool only_if_exists); + +typedef BOOL (*fn_action_script_run)(xfContext* xfc, const char* buffer, size_t size, void* user, + const char* what, const char* arg); +BOOL run_action_script(xfContext* xfc, const char* what, const char* arg, fn_action_script_run fkt, + void* user); + +#define LogTagAndXGetWindowProperty(tag, display, w, property, long_offset, long_length, delete, \ + req_type, actual_type_return, actual_format_return, \ + nitems_return, bytes_after_return, prop_return) \ + LogTagAndXGetWindowProperty_ex((tag), __FILE__, __func__, __LINE__, (display), (w), \ + (property), (long_offset), (long_length), (delete), (req_type), \ + (actual_type_return), (actual_format_return), (nitems_return), \ + (bytes_after_return), (prop_return)) +int LogTagAndXGetWindowProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, long long_offset, + long long_length, Bool delete, Atom req_type, + Atom* actual_type_return, int* actual_format_return, + unsigned long* nitems_return, unsigned long* bytes_after_return, + unsigned char** prop_return); + +#define LogDynAndXGetWindowProperty(log, display, w, property, long_offset, long_length, delete, \ + req_type, actual_type_return, actual_format_return, \ + nitems_return, bytes_after_return, prop_return) \ + LogDynAndXGetWindowProperty_ex((log), __FILE__, __func__, __LINE__, (display), (w), \ + (property), (long_offset), (long_length), (delete), (req_type), \ + (actual_type_return), (actual_format_return), (nitems_return), \ + (bytes_after_return), (prop_return)) +int LogDynAndXGetWindowProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, long long_offset, + long long_length, Bool delete, Atom req_type, + Atom* actual_type_return, int* actual_format_return, + unsigned long* nitems_return, unsigned long* bytes_after_return, + unsigned char** prop_return); + +#define LogTagAndXChangeProperty(tag, display, w, property, type, format, mode, data, nelements) \ + LogTagAndXChangeProperty_ex((tag), __FILE__, __func__, __LINE__, (display), (w), (property), \ + (type), (format), (mode), (data), (nelements)) +int LogTagAndXChangeProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, Atom type, int format, + int mode, _Xconst unsigned char* data, int nelements); + +#define LogDynAndXChangeProperty(log, display, w, property, type, format, mode, data, nelements) \ + LogDynAndXChangeProperty_ex((log), __FILE__, __func__, __LINE__, (display), (w), (property), \ + (type), (format), (mode), (data), (nelements)) +int LogDynAndXChangeProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property, Atom type, int format, + int mode, _Xconst unsigned char* data, int nelements); + +#define LogTagAndXDeleteProperty(tag, display, w, property) \ + LogTagAndXDeleteProperty_ex((tag), __FILE__, __func__, __LINE__, (display), (w), (property)) +int LogTagAndXDeleteProperty_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property); + +#define LogDynAndXDeleteProperty(log, display, w, property) \ + LogDynAndXDeleteProperty_ex((log), __FILE__, __func__, __LINE__, (display), (w), (property)) +int LogDynAndXDeleteProperty_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Window w, Atom property); + +#define LogTagAndXConvertSelection(tag, display, selection, target, property, requestor, time) \ + LogTagAndXConvertSelection_ex((tag), __FILE__, __func__, __LINE__, (display), (selection), \ + (target), (property), (requestor), (time)) +int LogTagAndXConvertSelection_ex(const char* tag, const char* file, const char* fkt, size_t line, + Display* display, Atom selection, Atom target, Atom property, + Window requestor, Time time); + +#define LogDynAndXConvertSelection(log, display, selection, target, property, requestor, time) \ + LogDynAndXConvertSelection_ex((log), __FILE__, __func__, __LINE__, (display), (w), (property)) +int LogDynAndXConvertSelection_ex(wLog* log, const char* file, const char* fkt, size_t line, + Display* display, Atom selection, Atom target, Atom property, + Window requestor, Time time); + +BOOL IsGnome(void); diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.c new file mode 100644 index 0000000000000000000000000000000000000000..a647c1b96c9f9559f7e770113bcb0b267991a473 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.c @@ -0,0 +1,138 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Optimized Remoting Virtual Channel Extension for X11 + * + * Copyright 2017 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "xf_video.h" + +#include +#define TAG CLIENT_TAG("video") + +typedef struct +{ + VideoSurface base; + XImage* image; +} xfVideoSurface; + +static VideoSurface* xfVideoCreateSurface(VideoClientContext* video, UINT32 x, UINT32 y, + UINT32 width, UINT32 height) +{ + xfContext* xfc = NULL; + xfVideoSurface* ret = NULL; + + WINPR_ASSERT(video); + ret = (xfVideoSurface*)VideoClient_CreateCommonContext(sizeof(xfContext), x, y, width, height); + if (!ret) + return NULL; + + xfc = (xfContext*)video->custom; + WINPR_ASSERT(xfc); + + ret->image = XCreateImage( + xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), ZPixmap, 0, + (char*)ret->base.data, width, height, 8, WINPR_ASSERTING_INT_CAST(int, ret->base.scanline)); + + if (!ret->image) + { + WLog_ERR(TAG, "unable to create surface image"); + VideoClient_DestroyCommonContext(&ret->base); + return NULL; + } + + return &ret->base; +} + +static BOOL xfVideoShowSurface(VideoClientContext* video, const VideoSurface* surface, + UINT32 destinationWidth, UINT32 destinationHeight) +{ + const xfVideoSurface* xfSurface = (const xfVideoSurface*)surface; + xfContext* xfc = NULL; + const rdpSettings* settings = NULL; + + WINPR_ASSERT(video); + WINPR_ASSERT(xfSurface); + + xfc = video->custom; + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + +#ifdef WITH_XRENDER + + if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) || + freerdp_settings_get_bool(settings, FreeRDP_MultiTouchGestures)) + { + XPutImage(xfc->display, xfc->primary, xfc->gc, xfSurface->image, 0, 0, + WINPR_ASSERTING_INT_CAST(int, surface->x), + WINPR_ASSERTING_INT_CAST(int, surface->y), surface->w, surface->h); + xf_draw_screen(xfc, WINPR_ASSERTING_INT_CAST(int32_t, surface->x), + WINPR_ASSERTING_INT_CAST(int32_t, surface->y), + WINPR_ASSERTING_INT_CAST(int32_t, surface->w), + WINPR_ASSERTING_INT_CAST(int32_t, surface->h)); + } + else +#endif + { + XPutImage(xfc->display, xfc->drawable, xfc->gc, xfSurface->image, 0, 0, + WINPR_ASSERTING_INT_CAST(int, surface->x), + WINPR_ASSERTING_INT_CAST(int, surface->y), surface->w, surface->h); + } + + return TRUE; +} + +static BOOL xfVideoDeleteSurface(VideoClientContext* video, VideoSurface* surface) +{ + xfVideoSurface* xfSurface = (xfVideoSurface*)surface; + + WINPR_UNUSED(video); + + if (xfSurface) + XFree(xfSurface->image); + + VideoClient_DestroyCommonContext(surface); + return TRUE; +} + +void xf_video_control_init(xfContext* xfc, VideoClientContext* video) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(video); + + gdi_video_control_init(xfc->common.context.gdi, video); + + /* X11 needs to be able to handle 32bpp colors directly. */ + if (xfc->depth >= 24) + { + video->custom = xfc; + video->createSurface = xfVideoCreateSurface; + video->showSurface = xfVideoShowSurface; + video->deleteSurface = xfVideoDeleteSurface; + } +} + +void xf_video_control_uninit(xfContext* xfc, VideoClientContext* video) +{ + WINPR_ASSERT(xfc); + gdi_video_control_uninit(xfc->common.context.gdi, video); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.h new file mode 100644 index 0000000000000000000000000000000000000000..385b4eae7133cb55160848c7b03b9f32a3952cf7 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_video.h @@ -0,0 +1,35 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Video Optimized Remoting Virtual Channel Extension for X11 + * + * Copyright 2017 David Fort + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CLIENT_X11_XF_VIDEO_H_ +#define CLIENT_X11_XF_VIDEO_H_ + +#include "xfreerdp.h" + +#include +#include + +void xf_video_control_init(xfContext* xfc, VideoClientContext* video); +void xf_video_control_uninit(xfContext* xfc, VideoClientContext* video); + +void xf_video_free(xfVideoContext* context); + +WINPR_ATTR_MALLOC(xf_video_free, 1) +xfVideoContext* xf_video_new(xfContext* xfc); + +#endif /* CLIENT_X11_XF_VIDEO_H_ */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.c b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.c new file mode 100644 index 0000000000000000000000000000000000000000..03400b96c9d7b7159f4c391501d5fd229f9fe8ab --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.c @@ -0,0 +1,1575 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Windows + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2012 HP Development Company, LLC + * Copyright 2016 Thincast Technologies GmbH + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#ifdef WITH_XEXT +#include +#endif + +#ifdef WITH_XI +#include +#endif + +#include "xf_gfx.h" +#include "xf_rail.h" +#include "xf_input.h" +#include "xf_keyboard.h" +#include "xf_utils.h" + +#define TAG CLIENT_TAG("x11") + +#ifdef WITH_DEBUG_X11 +#define DEBUG_X11(...) WLog_DBG(TAG, __VA_ARGS__) +#else +#define DEBUG_X11(...) \ + do \ + { \ + } while (0) +#endif + +#include +#define xf_icon_prop FreeRDP_Icon_256px_prop + +#include "xf_window.h" + +/* Extended Window Manager Hints: http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html */ + +/* bit definitions for MwmHints.flags */ +#define MWM_HINTS_FUNCTIONS (1L << 0) +#define MWM_HINTS_DECORATIONS (1L << 1) +// #define MWM_HINTS_INPUT_MODE (1L << 2) +// #define MWM_HINTS_STATUS (1L << 3) + +/* bit definitions for MwmHints.functions */ +#define MWM_FUNC_ALL (1L << 0) +// #define MWM_FUNC_RESIZE (1L << 1) +// #define MWM_FUNC_MOVE (1L << 2) +// #define MWM_FUNC_MINIMIZE (1L << 3) +// #define MWM_FUNC_MAXIMIZE (1L << 4) +// #define MWM_FUNC_CLOSE (1L << 5) + +/* bit definitions for MwmHints.decorations */ +#define MWM_DECOR_ALL (1L << 0) +// #define MWM_DECOR_BORDER (1L << 1) +// #define MWM_DECOR_RESIZEH (1L << 2) +// #define MWM_DECOR_TITLE (1L << 3) +// #define MWM_DECOR_MENU (1L << 4) +// #define MWM_DECOR_MINIMIZE (1L << 5) +// #define MWM_DECOR_MAXIMIZE (1L << 6) + +#define PROP_MOTIF_WM_HINTS_ELEMENTS 5 + +#define ENTRY(x) \ + case x: \ + return #x + +typedef struct +{ + unsigned long flags; + unsigned long functions; + unsigned long decorations; + long inputMode; + unsigned long status; +} PropMotifWmHints; + +static void xf_XSetTransientForHint(xfContext* xfc, xfAppWindow* window); + +static const char* window_style_to_string(UINT32 style) +{ + switch (style) + { + ENTRY(WS_NONE); + ENTRY(WS_BORDER); + ENTRY(WS_CAPTION); + ENTRY(WS_CHILD); + ENTRY(WS_CLIPCHILDREN); + ENTRY(WS_CLIPSIBLINGS); + ENTRY(WS_DISABLED); + ENTRY(WS_DLGFRAME); + ENTRY(WS_GROUP); + ENTRY(WS_HSCROLL); + ENTRY(WS_MAXIMIZE); + ENTRY(WS_MAXIMIZEBOX); + ENTRY(WS_MINIMIZE); + ENTRY(WS_OVERLAPPEDWINDOW); + ENTRY(WS_POPUP); + ENTRY(WS_POPUPWINDOW); + ENTRY(WS_SIZEBOX); + ENTRY(WS_SYSMENU); + ENTRY(WS_VISIBLE); + ENTRY(WS_VSCROLL); + default: + return NULL; + } +} + +const char* window_styles_to_string(UINT32 style, char* buffer, size_t length) +{ + (void)_snprintf(buffer, length, "style[0x%08" PRIx32 "] {", style); + const char* sep = ""; + for (size_t x = 0; x < 32; x++) + { + const UINT32 val = 1 << x; + if ((style & val) != 0) + { + const char* str = window_style_to_string(val); + if (str) + { + winpr_str_append(str, buffer, length, sep); + sep = "|"; + } + } + } + winpr_str_append("}", buffer, length, ""); + + return buffer; +} + +static const char* window_style_ex_to_string(UINT32 styleEx) +{ + switch (styleEx) + { + ENTRY(WS_EX_ACCEPTFILES); + ENTRY(WS_EX_APPWINDOW); + ENTRY(WS_EX_CLIENTEDGE); + ENTRY(WS_EX_COMPOSITED); + ENTRY(WS_EX_CONTEXTHELP); + ENTRY(WS_EX_CONTROLPARENT); + ENTRY(WS_EX_DLGMODALFRAME); + ENTRY(WS_EX_LAYERED); + ENTRY(WS_EX_LAYOUTRTL); + ENTRY(WS_EX_LEFTSCROLLBAR); + ENTRY(WS_EX_MDICHILD); + ENTRY(WS_EX_NOACTIVATE); + ENTRY(WS_EX_NOINHERITLAYOUT); + ENTRY(WS_EX_NOPARENTNOTIFY); + ENTRY(WS_EX_OVERLAPPEDWINDOW); + ENTRY(WS_EX_PALETTEWINDOW); + ENTRY(WS_EX_RIGHT); + ENTRY(WS_EX_RIGHTSCROLLBAR); + ENTRY(WS_EX_RTLREADING); + ENTRY(WS_EX_STATICEDGE); + ENTRY(WS_EX_TOOLWINDOW); + ENTRY(WS_EX_TOPMOST); + ENTRY(WS_EX_TRANSPARENT); + ENTRY(WS_EX_WINDOWEDGE); + default: + return NULL; + } +} + +const char* window_styles_ex_to_string(UINT32 styleEx, char* buffer, size_t length) +{ + (void)_snprintf(buffer, length, "styleEx[0x%08" PRIx32 "] {", styleEx); + const char* sep = ""; + for (size_t x = 0; x < 32; x++) + { + const UINT32 val = (UINT32)(1UL << x); + if ((styleEx & val) != 0) + { + const char* str = window_style_ex_to_string(val); + if (str) + { + winpr_str_append(str, buffer, length, sep); + sep = "|"; + } + } + } + winpr_str_append("}", buffer, length, ""); + + return buffer; +} + +static void xf_SetWindowTitleText(xfContext* xfc, Window window, const char* name) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(name); + + const size_t i = strnlen(name, MAX_PATH); + XStoreName(xfc->display, window, name); + Atom wm_Name = xfc->_NET_WM_NAME; + Atom utf8Str = xfc->UTF8_STRING; + LogTagAndXChangeProperty(TAG, xfc->display, window, wm_Name, utf8Str, 8, PropModeReplace, + (const unsigned char*)name, (int)i); +} + +/** + * Post an event from the client to the X server + */ +void xf_SendClientEvent(xfContext* xfc, Window window, Atom atom, unsigned int numArgs, ...) +{ + XEvent xevent = { 0 }; + va_list argp; + va_start(argp, numArgs); + + xevent.xclient.type = ClientMessage; + xevent.xclient.serial = 0; + xevent.xclient.send_event = False; + xevent.xclient.display = xfc->display; + xevent.xclient.window = window; + xevent.xclient.message_type = atom; + xevent.xclient.format = 32; + + for (size_t i = 0; i < numArgs; i++) + { + xevent.xclient.data.l[i] = va_arg(argp, int); + } + + DEBUG_X11("Send ClientMessage Event: wnd=0x%04lX", (unsigned long)xevent.xclient.window); + XSendEvent(xfc->display, RootWindowOfScreen(xfc->screen), False, + SubstructureRedirectMask | SubstructureNotifyMask, &xevent); + XSync(xfc->display, False); + va_end(argp); +} + +void xf_SetWindowMinimized(xfContext* xfc, xfWindow* window) +{ + XIconifyWindow(xfc->display, window->handle, xfc->screen_number); +} + +void xf_SetWindowFullscreen(xfContext* xfc, xfWindow* window, BOOL fullscreen) +{ + const rdpSettings* settings = NULL; + int startX = 0; + int startY = 0; + UINT32 width = WINPR_ASSERTING_INT_CAST(uint32_t, window->width); + UINT32 height = WINPR_ASSERTING_INT_CAST(uint32_t, window->height); + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + /* xfc->decorations is set by caller depending on settings and whether it is fullscreen or not + */ + window->decorations = xfc->decorations; + /* show/hide decorations (e.g. title bar) as guided by xfc->decorations */ + xf_SetWindowDecorations(xfc, window->handle, window->decorations); + DEBUG_X11(TAG, "X window decoration set to %d", (int)window->decorations); + xf_floatbar_toggle_fullscreen(xfc->window->floatbar, fullscreen); + + if (fullscreen) + { + xfc->savedWidth = xfc->window->width; + xfc->savedHeight = xfc->window->height; + xfc->savedPosX = xfc->window->left; + xfc->savedPosY = xfc->window->top; + + startX = (freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX) != UINT32_MAX) + ? WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX)) + : 0; + startY = (freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY) != UINT32_MAX) + ? WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY)) + : 0; + } + else + { + width = WINPR_ASSERTING_INT_CAST(uint32_t, xfc->savedWidth); + height = WINPR_ASSERTING_INT_CAST(uint32_t, xfc->savedHeight); + startX = xfc->savedPosX; + startY = xfc->savedPosY; + } + + /* Determine the x,y starting location for the fullscreen window */ + if (fullscreen) + { + const rdpMonitor* firstMonitor = + freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, 0); + /* Initialize startX and startY with reasonable values */ + startX = firstMonitor->x; + startY = firstMonitor->y; + + /* Search all monitors to find the lowest startX and startY values */ + for (size_t i = 0; i < freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); i++) + { + const rdpMonitor* monitor = + freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, i); + startX = MIN(startX, monitor->x); + startY = MIN(startY, monitor->y); + } + + /* Lastly apply any monitor shift(translation from remote to local coordinate system) + * to startX and startY values + */ + startX += freerdp_settings_get_int32(settings, FreeRDP_MonitorLocalShiftX); + startY += freerdp_settings_get_int32(settings, FreeRDP_MonitorLocalShiftY); + } + + /* + It is safe to proceed with simply toggling _NET_WM_STATE_FULLSCREEN window state on the + following conditions: + - The window manager supports multiple monitor full screen + - The user requested to use a single monitor to render the remote desktop + */ + if (xfc->_NET_WM_FULLSCREEN_MONITORS != None || + freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount) == 1) + { + xf_ResizeDesktopWindow(xfc, window, WINPR_ASSERTING_INT_CAST(int, width), + WINPR_ASSERTING_INT_CAST(int, height)); + + if (fullscreen) + { + /* enter full screen: move the window before adding NET_WM_STATE_FULLSCREEN */ + XMoveWindow(xfc->display, window->handle, startX, startY); + } + + /* Set the fullscreen state */ + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, + fullscreen ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE, + xfc->_NET_WM_STATE_FULLSCREEN, 0, 0); + + if (!fullscreen) + { + /* leave full screen: move the window after removing NET_WM_STATE_FULLSCREEN + * Resize the window again, the previous call to xf_SendClientEvent might have + * changed the window size (borders, ...) + */ + xf_ResizeDesktopWindow(xfc, window, WINPR_ASSERTING_INT_CAST(int, width), + WINPR_ASSERTING_INT_CAST(int, height)); + XMoveWindow(xfc->display, window->handle, startX, startY); + } + + /* Set monitor bounds */ + if (freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount) > 1) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_FULLSCREEN_MONITORS, 5, + xfc->fullscreenMonitors.top, xfc->fullscreenMonitors.bottom, + xfc->fullscreenMonitors.left, xfc->fullscreenMonitors.right, 1); + } + } + else + { + if (fullscreen) + { + xf_SetWindowDecorations(xfc, window->handle, FALSE); + + if (xfc->fullscreenMonitors.top) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_ADD, + xfc->fullscreenMonitors.top, 0, 0); + } + else + { + XSetWindowAttributes xswa = { 0 }; + xswa.override_redirect = True; + XChangeWindowAttributes(xfc->display, window->handle, CWOverrideRedirect, &xswa); + XRaiseWindow(xfc->display, window->handle); + xswa.override_redirect = False; + XChangeWindowAttributes(xfc->display, window->handle, CWOverrideRedirect, &xswa); + } + + /* if window is in maximized state, save and remove */ + if (xfc->_NET_WM_STATE_MAXIMIZED_VERT != None) + { + BYTE state = 0; + unsigned long nitems = 0; + unsigned long bytes = 0; + BYTE* prop = NULL; + + if (xf_GetWindowProperty(xfc, window->handle, xfc->_NET_WM_STATE, 255, &nitems, + &bytes, &prop)) + { + const Atom* aprop = (const Atom*)prop; + state = 0; + + for (size_t x = 0; x < nitems; x++) + { + if (aprop[x] == xfc->_NET_WM_STATE_MAXIMIZED_VERT) + state |= 0x01; + + if (aprop[x] == xfc->_NET_WM_STATE_MAXIMIZED_HORZ) + state |= 0x02; + } + + if (state) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, + _NET_WM_STATE_REMOVE, xfc->_NET_WM_STATE_MAXIMIZED_VERT, + 0, 0); + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, + _NET_WM_STATE_REMOVE, xfc->_NET_WM_STATE_MAXIMIZED_HORZ, + 0, 0); + xfc->savedMaximizedState = state; + } + + XFree(prop); + } + } + + width = xfc->vscreen.area.right - xfc->vscreen.area.left + 1; + height = xfc->vscreen.area.bottom - xfc->vscreen.area.top + 1; + DEBUG_X11("X window move and resize %dx%d@%dx%d", startX, startY, width, height); + xf_ResizeDesktopWindow(xfc, window, WINPR_ASSERTING_INT_CAST(int, width), + WINPR_ASSERTING_INT_CAST(int, height)); + XMoveWindow(xfc->display, window->handle, startX, startY); + } + else + { + xf_SetWindowDecorations(xfc, window->handle, window->decorations); + xf_ResizeDesktopWindow(xfc, window, WINPR_ASSERTING_INT_CAST(int, width), + WINPR_ASSERTING_INT_CAST(int, height)); + XMoveWindow(xfc->display, window->handle, startX, startY); + + if (xfc->fullscreenMonitors.top) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_REMOVE, + xfc->fullscreenMonitors.top, 0, 0); + } + + /* restore maximized state, if the window was maximized before setting fullscreen */ + if (xfc->savedMaximizedState & 0x01) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_ADD, + xfc->_NET_WM_STATE_MAXIMIZED_VERT, 0, 0); + } + + if (xfc->savedMaximizedState & 0x02) + { + xf_SendClientEvent(xfc, window->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_ADD, + xfc->_NET_WM_STATE_MAXIMIZED_HORZ, 0, 0); + } + + xfc->savedMaximizedState = 0; + } + } +} + +/* http://tronche.com/gui/x/xlib/window-information/XGetWindowProperty.html */ + +BOOL xf_GetWindowProperty(xfContext* xfc, Window window, Atom property, int length, + unsigned long* nitems, unsigned long* bytes, BYTE** prop) +{ + int status = 0; + Atom actual_type = None; + int actual_format = 0; + + if (property == None) + return FALSE; + + status = LogTagAndXGetWindowProperty(TAG, xfc->display, window, property, 0, length, False, + AnyPropertyType, &actual_type, &actual_format, nitems, + bytes, prop); + + if (status != Success) + return FALSE; + + if (actual_type == None) + { + WLog_DBG(TAG, "Property %lu does not exist", (unsigned long)property); + return FALSE; + } + + return TRUE; +} + +static BOOL xf_GetNumberOfDesktops(xfContext* xfc, Window root, unsigned* pval) +{ + unsigned long nitems = 0; + unsigned long bytes = 0; + BYTE* bprop = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(pval); + + const BOOL rc = + xf_GetWindowProperty(xfc, root, xfc->_NET_NUMBER_OF_DESKTOPS, 1, &nitems, &bytes, &bprop); + + long* prop = (long*)bprop; + *pval = 0; + if (!rc) + return FALSE; + + BOOL res = FALSE; + if ((*prop >= 0) && (*prop <= UINT32_MAX)) + { + *pval = (UINT32)*prop; + res = TRUE; + } + XFree(prop); + return res; +} + +static BOOL xf_GetCurrentDesktop(xfContext* xfc, Window root) +{ + unsigned long nitems = 0; + unsigned long bytes = 0; + BYTE* bprop = NULL; + unsigned max = 0; + + if (!xf_GetNumberOfDesktops(xfc, root, &max)) + return FALSE; + if (max < 1) + return FALSE; + + const BOOL rc = + xf_GetWindowProperty(xfc, root, xfc->_NET_CURRENT_DESKTOP, 1, &nitems, &bytes, &bprop); + + long* prop = (long*)bprop; + xfc->current_desktop = 0; + if (!rc) + return FALSE; + + xfc->current_desktop = (int)MIN(max - 1, *prop); + XFree(prop); + return TRUE; +} + +static BOOL xf_GetWorkArea_NET_WORKAREA(xfContext* xfc, Window root) +{ + BOOL rc = FALSE; + unsigned long nitems = 0; + unsigned long bytes = 0; + BYTE* bprop = NULL; + + const BOOL status = + xf_GetWindowProperty(xfc, root, xfc->_NET_WORKAREA, INT_MAX, &nitems, &bytes, &bprop); + long* prop = (long*)bprop; + + if (!status) + goto fail; + + if ((xfc->current_desktop * 4 + 3) >= (INT64)nitems) + goto fail; + + xfc->workArea.x = (INT32)MIN(INT32_MAX, prop[xfc->current_desktop * 4 + 0]); + xfc->workArea.y = (INT32)MIN(INT32_MAX, prop[xfc->current_desktop * 4 + 1]); + xfc->workArea.width = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 2]); + xfc->workArea.height = (UINT32)MIN(UINT32_MAX, prop[xfc->current_desktop * 4 + 3]); + + rc = TRUE; +fail: + XFree(prop); + return rc; +} + +BOOL xf_GetWorkArea(xfContext* xfc) +{ + WINPR_ASSERT(xfc); + + Window root = DefaultRootWindow(xfc->display); + (void)xf_GetCurrentDesktop(xfc, root); + return xf_GetWorkArea_NET_WORKAREA(xfc, root); +} + +void xf_SetWindowDecorations(xfContext* xfc, Window window, BOOL show) +{ + PropMotifWmHints hints = { .decorations = (show) ? MWM_DECOR_ALL : 0, + .functions = MWM_FUNC_ALL, + .flags = MWM_HINTS_DECORATIONS | MWM_HINTS_FUNCTIONS, + .inputMode = 0, + .status = 0 }; + WINPR_ASSERT(xfc); + LogTagAndXChangeProperty(TAG, xfc->display, window, xfc->_MOTIF_WM_HINTS, xfc->_MOTIF_WM_HINTS, + 32, PropModeReplace, (BYTE*)&hints, PROP_MOTIF_WM_HINTS_ELEMENTS); +} + +void xf_SetWindowUnlisted(xfContext* xfc, Window window) +{ + WINPR_ASSERT(xfc); + Atom window_state[] = { xfc->_NET_WM_STATE_SKIP_PAGER, xfc->_NET_WM_STATE_SKIP_TASKBAR }; + LogTagAndXChangeProperty(TAG, xfc->display, window, xfc->_NET_WM_STATE, XA_ATOM, 32, + PropModeReplace, (BYTE*)window_state, 2); +} + +static void xf_SetWindowPID(xfContext* xfc, Window window, pid_t pid) +{ + Atom am_wm_pid = 0; + + WINPR_ASSERT(xfc); + if (!pid) + pid = getpid(); + + am_wm_pid = xfc->_NET_WM_PID; + LogTagAndXChangeProperty(TAG, xfc->display, window, am_wm_pid, XA_CARDINAL, 32, PropModeReplace, + (BYTE*)&pid, 1); +} + +static const char* get_shm_id(void) +{ + static char shm_id[64]; + (void)sprintf_s(shm_id, sizeof(shm_id), "/com.freerdp.xfreerdp.tsmf_%016X", + GetCurrentProcessId()); + return shm_id; +} + +Window xf_CreateDummyWindow(xfContext* xfc) +{ + return XCreateWindow(xfc->display, RootWindowOfScreen(xfc->screen), + WINPR_ASSERTING_INT_CAST(int, xfc->workArea.x), + WINPR_ASSERTING_INT_CAST(int, xfc->workArea.y), 1, 1, 0, xfc->depth, + InputOutput, xfc->visual, + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->attribs_mask), &xfc->attribs); +} + +void xf_DestroyDummyWindow(xfContext* xfc, Window window) +{ + if (window) + XDestroyWindow(xfc->display, window); +} + +xfWindow* xf_CreateDesktopWindow(xfContext* xfc, char* name, int width, int height) +{ + XEvent xevent = { 0 }; + int input_mask = 0; + XClassHint* classHints = NULL; + xfWindow* window = (xfWindow*)calloc(1, sizeof(xfWindow)); + + if (!window) + return NULL; + + rdpSettings* settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + Window parentWindow = (Window)freerdp_settings_get_uint64(settings, FreeRDP_ParentWindowId); + window->width = width; + window->height = height; + window->decorations = xfc->decorations; + window->is_mapped = FALSE; + window->is_transient = FALSE; + + WINPR_ASSERT(xfc->depth != 0); + window->handle = + XCreateWindow(xfc->display, RootWindowOfScreen(xfc->screen), + WINPR_ASSERTING_INT_CAST(int, xfc->workArea.x), + WINPR_ASSERTING_INT_CAST(int, xfc->workArea.y), xfc->workArea.width, + xfc->workArea.height, 0, xfc->depth, InputOutput, xfc->visual, + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->attribs_mask), &xfc->attribs); + window->shmid = shm_open(get_shm_id(), (O_CREAT | O_RDWR), (S_IREAD | S_IWRITE)); + + if (window->shmid < 0) + { + DEBUG_X11("xf_CreateDesktopWindow: failed to get access to shared memory - shmget()\n"); + } + else + { + int rc = ftruncate(window->shmid, sizeof(window->handle)); + if (rc != 0) + { +#ifdef WITH_DEBUG_X11 + char ebuffer[256] = { 0 }; + DEBUG_X11("ftruncate failed with %s [%d]", winpr_strerror(rc, ebuffer, sizeof(ebuffer)), + rc); +#endif + } + else + { + void* mem = mmap(0, sizeof(window->handle), PROT_READ | PROT_WRITE, MAP_SHARED, + window->shmid, 0); + + if (mem == MAP_FAILED) + { + DEBUG_X11( + "xf_CreateDesktopWindow: failed to assign pointer to the memory address - " + "shmat()\n"); + } + else + { + window->xfwin = mem; + *window->xfwin = window->handle; + } + } + } + + classHints = XAllocClassHint(); + + if (classHints) + { + classHints->res_name = "xfreerdp"; + + char* res_class = NULL; + const char* WmClass = freerdp_settings_get_string(settings, FreeRDP_WmClass); + if (WmClass) + res_class = _strdup(WmClass); + else + res_class = _strdup("xfreerdp"); + + classHints->res_class = res_class; + XSetClassHint(xfc->display, window->handle, classHints); + XFree(classHints); + free(res_class); + } + + xf_ResizeDesktopWindow(xfc, window, width, height); + xf_SetWindowDecorations(xfc, window->handle, window->decorations); + xf_SetWindowPID(xfc, window->handle, 0); + input_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | + VisibilityChangeMask | FocusChangeMask | StructureNotifyMask | PointerMotionMask | + ExposureMask | PropertyChangeMask; + + if (xfc->grab_keyboard) + input_mask |= EnterWindowMask | LeaveWindowMask; + + LogTagAndXChangeProperty(TAG, xfc->display, window->handle, xfc->_NET_WM_ICON, XA_CARDINAL, 32, + PropModeReplace, (BYTE*)xf_icon_prop, ARRAYSIZE(xf_icon_prop)); + + if (parentWindow) + XReparentWindow(xfc->display, window->handle, parentWindow, 0, 0); + + XSelectInput(xfc->display, window->handle, input_mask); + XClearWindow(xfc->display, window->handle); + xf_SetWindowTitleText(xfc, window->handle, name); + XMapWindow(xfc->display, window->handle); + xf_input_init(xfc, window->handle); + + /* + * NOTE: This must be done here to handle reparenting the window, + * so that we don't miss the event and hang waiting for the next one + */ + do + { + XMaskEvent(xfc->display, VisibilityChangeMask, &xevent); + } while (xevent.type != VisibilityNotify); + + /* + * The XCreateWindow call will start the window in the upper-left corner of our current + * monitor instead of the upper-left monitor for remote app mode (which uses all monitors). + * This extra call after the window is mapped will position the login window correctly + */ + if (freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode)) + { + XMoveWindow(xfc->display, window->handle, 0, 0); + } + else if ((freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX) != UINT32_MAX) && + (freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY) != UINT32_MAX)) + { + XMoveWindow(xfc->display, window->handle, + WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosX)), + WINPR_ASSERTING_INT_CAST( + int, freerdp_settings_get_uint32(settings, FreeRDP_DesktopPosY))); + } + + window->floatbar = xf_floatbar_new(xfc, window->handle, name, + freerdp_settings_get_uint32(settings, FreeRDP_Floatbar)); + + if (xfc->_XWAYLAND_MAY_GRAB_KEYBOARD) + xf_SendClientEvent(xfc, window->handle, xfc->_XWAYLAND_MAY_GRAB_KEYBOARD, 1, 1); + + return window; +} + +void xf_ResizeDesktopWindow(xfContext* xfc, xfWindow* window, int width, int height) +{ + XSizeHints* size_hints = NULL; + rdpSettings* settings = NULL; + + if (!xfc || !window) + return; + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (!(size_hints = XAllocSizeHints())) + return; + + size_hints->flags = PMinSize | PMaxSize | PWinGravity; + size_hints->win_gravity = NorthWestGravity; + size_hints->min_width = size_hints->min_height = 1; + size_hints->max_width = size_hints->max_height = 16384; + XResizeWindow(xfc->display, window->handle, WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, height)); +#ifdef WITH_XRENDER + + if (!freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) && + !freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) +#endif + { + if (!xfc->fullscreen) + { + /* min == max is an hint for the WM to indicate that the window should + * not be resizable */ + size_hints->min_width = size_hints->max_width = width; + size_hints->min_height = size_hints->max_height = height; + } + } + + XSetWMNormalHints(xfc->display, window->handle, size_hints); + XFree(size_hints); +} + +void xf_DestroyDesktopWindow(xfContext* xfc, xfWindow* window) +{ + if (!window) + return; + + if (xfc->window == window) + xfc->window = NULL; + + xf_floatbar_free(window->floatbar); + + if (window->gc) + XFreeGC(xfc->display, window->gc); + + if (window->handle) + { + XUnmapWindow(xfc->display, window->handle); + XDestroyWindow(xfc->display, window->handle); + } + + if (window->xfwin) + munmap(0, sizeof(*window->xfwin)); + + if (window->shmid >= 0) + close(window->shmid); + + shm_unlink(get_shm_id()); + window->xfwin = (Window*)-1; + window->shmid = -1; + free(window); +} + +void xf_SetWindowStyle(xfContext* xfc, xfAppWindow* appWindow, UINT32 style, UINT32 ex_style) +{ + Atom window_type = 0; + BOOL redirect = FALSE; + + window_type = xfc->_NET_WM_WINDOW_TYPE_NORMAL; + + if ((ex_style & WS_EX_NOACTIVATE) || (ex_style & WS_EX_TOOLWINDOW)) + { + redirect = TRUE; + appWindow->is_transient = TRUE; + xf_SetWindowUnlisted(xfc, appWindow->handle); + window_type = xfc->_NET_WM_WINDOW_TYPE_DROPDOWN_MENU; + } + /* + * TOPMOST window that is not a tool window is treated like a regular window (i.e. task + * manager). Want to do this here, since the window may have type WS_POPUP + */ + else if (ex_style & WS_EX_TOPMOST) + { + window_type = xfc->_NET_WM_WINDOW_TYPE_NORMAL; + } + + if (style & WS_POPUP) + { + window_type = xfc->_NET_WM_WINDOW_TYPE_DIALOG; + /* this includes dialogs, popups, etc, that need to be full-fledged windows */ + + if (!((ex_style & WS_EX_DLGMODALFRAME) || (ex_style & WS_EX_LAYERED) || + (style & WS_SYSMENU))) + { + appWindow->is_transient = TRUE; + redirect = TRUE; + + xf_SetWindowUnlisted(xfc, appWindow->handle); + } + } + + if (!(style == 0 && ex_style == 0)) + { + xf_SetWindowActions(xfc, appWindow); + } + + { + /* + * Tooltips and menu items should be unmanaged windows + * (called "override redirect" in X windows parlance) + * If they are managed, there are issues with window focus that + * cause the windows to behave improperly. For example, a mouse + * press will dismiss a drop-down menu because the RDP server + * sees that as a focus out event from the window owning the + * dropdown. + */ + XSetWindowAttributes attrs = { 0 }; + attrs.override_redirect = redirect ? True : False; + XChangeWindowAttributes(xfc->display, appWindow->handle, CWOverrideRedirect, &attrs); + } + + LogTagAndXChangeProperty(TAG, xfc->display, appWindow->handle, xfc->_NET_WM_WINDOW_TYPE, + XA_ATOM, 32, PropModeReplace, (BYTE*)&window_type, 1); + + const BOOL above = (ex_style & WS_EX_TOPMOST) != 0; + const BOOL transient = (style & WS_CHILD) == 0; + + if (transient) + xf_XSetTransientForHint( + xfc, appWindow); // xf_XSetTransientForHint only sets the hint if there is a parent + + xf_SendClientEvent(xfc, appWindow->handle, xfc->_NET_WM_STATE, 4, + above ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE, xfc->_NET_WM_STATE_ABOVE, + 0, 0); +} + +void xf_SetWindowActions(xfContext* xfc, xfAppWindow* appWindow) +{ + Atom allowed_actions[] = { + xfc->NET_WM_ACTION_CLOSE, xfc->NET_WM_ACTION_MINIMIZE, + xfc->NET_WM_ACTION_MOVE, xfc->NET_WM_ACTION_RESIZE, + xfc->NET_WM_ACTION_MAXIMIZE_HORZ, xfc->NET_WM_ACTION_MAXIMIZE_VERT, + xfc->NET_WM_ACTION_FULLSCREEN, xfc->NET_WM_ACTION_CHANGE_DESKTOP + }; + + if (!(appWindow->dwStyle & WS_SYSMENU)) + allowed_actions[0] = 0; + + if (!(appWindow->dwStyle & WS_MINIMIZEBOX)) + allowed_actions[1] = 0; + + if (!(appWindow->dwStyle & WS_SIZEBOX)) + allowed_actions[3] = 0; + + if (!(appWindow->dwStyle & WS_MAXIMIZEBOX)) + { + allowed_actions[4] = 0; + allowed_actions[5] = 0; + allowed_actions[6] = 0; + } + + XChangeProperty(xfc->display, appWindow->handle, xfc->NET_WM_ALLOWED_ACTIONS, XA_ATOM, 32, + PropModeReplace, (unsigned char*)&allowed_actions, 8); +} + +void xf_SetWindowText(xfContext* xfc, xfAppWindow* appWindow, const char* name) +{ + xf_SetWindowTitleText(xfc, appWindow->handle, name); +} + +static void xf_FixWindowCoordinates(xfContext* xfc, int* x, int* y, int* width, int* height) +{ + int vscreen_width = 0; + int vscreen_height = 0; + vscreen_width = xfc->vscreen.area.right - xfc->vscreen.area.left + 1; + vscreen_height = xfc->vscreen.area.bottom - xfc->vscreen.area.top + 1; + + if (*x < xfc->vscreen.area.left) + { + *width += *x; + *x = xfc->vscreen.area.left; + } + + if (*y < xfc->vscreen.area.top) + { + *height += *y; + *y = xfc->vscreen.area.top; + } + + if (*width > vscreen_width) + { + *width = vscreen_width; + } + + if (*height > vscreen_height) + { + *height = vscreen_height; + } + + if (*width < 1) + { + *width = 1; + } + + if (*height < 1) + { + *height = 1; + } +} + +int xf_AppWindowInit(xfContext* xfc, xfAppWindow* appWindow) +{ + if (!xfc || !appWindow) + return -1; + + xf_SetWindowDecorations(xfc, appWindow->handle, appWindow->decorations); + xf_SetWindowStyle(xfc, appWindow, appWindow->dwStyle, appWindow->dwExStyle); + xf_SetWindowPID(xfc, appWindow->handle, 0); + xf_ShowWindow(xfc, appWindow, WINDOW_SHOW); + XClearWindow(xfc->display, appWindow->handle); + XMapWindow(xfc->display, appWindow->handle); + /* Move doesn't seem to work until window is mapped. */ + xf_MoveWindow(xfc, appWindow, appWindow->x, appWindow->y, appWindow->width, appWindow->height); + xf_SetWindowText(xfc, appWindow, appWindow->title); + return 1; +} + +BOOL xf_AppWindowCreate(xfContext* xfc, xfAppWindow* appWindow) +{ + XGCValues gcv = { 0 }; + int input_mask = 0; + XWMHints* InputModeHint = NULL; + XClassHint* class_hints = NULL; + const rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(appWindow); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + xf_FixWindowCoordinates(xfc, &appWindow->x, &appWindow->y, &appWindow->width, + &appWindow->height); + appWindow->shmid = -1; + appWindow->decorations = FALSE; + appWindow->fullscreen = FALSE; + appWindow->local_move.state = LMS_NOT_ACTIVE; + appWindow->is_mapped = FALSE; + appWindow->is_transient = FALSE; + appWindow->rail_state = 0; + appWindow->maxVert = FALSE; + appWindow->maxHorz = FALSE; + appWindow->minimized = FALSE; + appWindow->rail_ignore_configure = FALSE; + + WINPR_ASSERT(xfc->depth != 0); + appWindow->handle = XCreateWindow( + xfc->display, RootWindowOfScreen(xfc->screen), appWindow->x, appWindow->y, + WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->width), + WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->height), 0, xfc->depth, InputOutput, + xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->attribs_mask), &xfc->attribs); + + if (!appWindow->handle) + return FALSE; + + appWindow->gc = XCreateGC(xfc->display, appWindow->handle, GCGraphicsExposures, &gcv); + + if (!xf_AppWindowResize(xfc, appWindow)) + return FALSE; + + class_hints = XAllocClassHint(); + + if (class_hints) + { + char* strclass = NULL; + + const char* WmClass = freerdp_settings_get_string(settings, FreeRDP_WmClass); + if (WmClass) + strclass = _strdup(WmClass); + else + { + size_t size = 0; + winpr_asprintf(&strclass, &size, "RAIL:%08" PRIX64 "", appWindow->windowId); + } + class_hints->res_class = strclass; + class_hints->res_name = "RAIL"; + XSetClassHint(xfc->display, appWindow->handle, class_hints); + XFree(class_hints); + free(strclass); + } + + /* Set the input mode hint for the WM */ + InputModeHint = XAllocWMHints(); + InputModeHint->flags = (1L << 0); + InputModeHint->input = True; + XSetWMHints(xfc->display, appWindow->handle, InputModeHint); + XFree(InputModeHint); + XSetWMProtocols(xfc->display, appWindow->handle, &(xfc->WM_DELETE_WINDOW), 1); + input_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | + EnterWindowMask | LeaveWindowMask | PointerMotionMask | Button1MotionMask | + Button2MotionMask | Button3MotionMask | Button4MotionMask | Button5MotionMask | + ButtonMotionMask | KeymapStateMask | ExposureMask | VisibilityChangeMask | + StructureNotifyMask | SubstructureNotifyMask | SubstructureRedirectMask | + FocusChangeMask | PropertyChangeMask | ColormapChangeMask | OwnerGrabButtonMask; + XSelectInput(xfc->display, appWindow->handle, input_mask); + + if (xfc->_XWAYLAND_MAY_GRAB_KEYBOARD) + xf_SendClientEvent(xfc, appWindow->handle, xfc->_XWAYLAND_MAY_GRAB_KEYBOARD, 1, 1); + + return TRUE; +} + +void xf_SetWindowMinMaxInfo(xfContext* xfc, xfAppWindow* appWindow, int maxWidth, int maxHeight, + int maxPosX, int maxPosY, int minTrackWidth, int minTrackHeight, + int maxTrackWidth, int maxTrackHeight) +{ + XSizeHints* size_hints = NULL; + size_hints = XAllocSizeHints(); + + if (size_hints) + { + size_hints->flags = PMinSize | PMaxSize | PResizeInc; + size_hints->min_width = minTrackWidth; + size_hints->min_height = minTrackHeight; + size_hints->max_width = maxTrackWidth; + size_hints->max_height = maxTrackHeight; + /* to speedup window drawing we need to select optimal value for sizing step. */ + size_hints->width_inc = size_hints->height_inc = 1; + XSetWMNormalHints(xfc->display, appWindow->handle, size_hints); + XFree(size_hints); + } +} + +void xf_StartLocalMoveSize(xfContext* xfc, xfAppWindow* appWindow, int direction, int x, int y) +{ + if (appWindow->local_move.state != LMS_NOT_ACTIVE) + return; + + /* + * Save original mouse location relative to root. This will be needed + * to end local move to RDP server and/or X server + */ + appWindow->local_move.root_x = x; + appWindow->local_move.root_y = y; + appWindow->local_move.state = LMS_STARTING; + appWindow->local_move.direction = direction; + + xf_ungrab(xfc); + + xf_SendClientEvent( + xfc, appWindow->handle, + xfc->_NET_WM_MOVERESIZE, /* request X window manager to initiate a local move */ + 5, /* 5 arguments to follow */ + x, /* x relative to root window */ + y, /* y relative to root window */ + direction, /* extended ICCM direction flag */ + 1, /* simulated mouse button 1 */ + 1); /* 1 == application request per extended ICCM */ +} + +void xf_EndLocalMoveSize(xfContext* xfc, xfAppWindow* appWindow) +{ + if (appWindow->local_move.state == LMS_NOT_ACTIVE) + return; + + if (appWindow->local_move.state == LMS_STARTING) + { + /* + * The move never was property started. This can happen due to race + * conditions between the mouse button up and the communications to the + * RDP server for local moves. We must cancel the X window manager move. + * Per ICCM, the X client can ask to cancel an active move. + */ + xf_SendClientEvent( + xfc, appWindow->handle, + xfc->_NET_WM_MOVERESIZE, /* request X window manager to abort a local move */ + 5, /* 5 arguments to follow */ + appWindow->local_move.root_x, /* x relative to root window */ + appWindow->local_move.root_y, /* y relative to root window */ + _NET_WM_MOVERESIZE_CANCEL, /* extended ICCM direction flag */ + 1, /* simulated mouse button 1 */ + 1); /* 1 == application request per extended ICCM */ + } + + appWindow->local_move.state = LMS_NOT_ACTIVE; +} + +void xf_MoveWindow(xfContext* xfc, xfAppWindow* appWindow, int x, int y, int width, int height) +{ + BOOL resize = FALSE; + + if ((width * height) < 1) + return; + + if ((appWindow->width != width) || (appWindow->height != height)) + resize = TRUE; + + if (appWindow->local_move.state == LMS_STARTING || appWindow->local_move.state == LMS_ACTIVE) + return; + + appWindow->x = x; + appWindow->y = y; + appWindow->width = width; + appWindow->height = height; + + if (resize) + XMoveResizeWindow(xfc->display, appWindow->handle, x, y, + WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, height)); + else + XMoveWindow(xfc->display, appWindow->handle, x, y); + + xf_UpdateWindowArea(xfc, appWindow, 0, 0, width, height); +} + +void xf_ShowWindow(xfContext* xfc, xfAppWindow* appWindow, BYTE state) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(appWindow); + + switch (state) + { + case WINDOW_HIDE: + XWithdrawWindow(xfc->display, appWindow->handle, xfc->screen_number); + break; + + case WINDOW_SHOW_MINIMIZED: + appWindow->minimized = TRUE; + XIconifyWindow(xfc->display, appWindow->handle, xfc->screen_number); + break; + + case WINDOW_SHOW_MAXIMIZED: + /* Set the window as maximized */ + appWindow->maxHorz = TRUE; + appWindow->maxVert = TRUE; + xf_SendClientEvent(xfc, appWindow->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_ADD, + xfc->_NET_WM_STATE_MAXIMIZED_VERT, xfc->_NET_WM_STATE_MAXIMIZED_HORZ, + 0); + + /* + * This is a workaround for the case where the window is maximized locally before the + * rail server is told to maximize the window, this appears to be a race condition where + * the local window with incomplete data and once the window is actually maximized on + * the server + * - an update of the new areas may not happen. So, we simply to do a full update of the + * entire window once the rail server notifies us that the window is now maximized. + */ + if (appWindow->rail_state == WINDOW_SHOW_MAXIMIZED) + { + xf_UpdateWindowArea(xfc, appWindow, 0, 0, + WINPR_ASSERTING_INT_CAST(int, appWindow->windowWidth), + WINPR_ASSERTING_INT_CAST(int, appWindow->windowHeight)); + } + + break; + + case WINDOW_SHOW: + /* Ensure the window is not maximized */ + xf_SendClientEvent(xfc, appWindow->handle, xfc->_NET_WM_STATE, 4, _NET_WM_STATE_REMOVE, + xfc->_NET_WM_STATE_MAXIMIZED_VERT, xfc->_NET_WM_STATE_MAXIMIZED_HORZ, + 0); + + /* + * Ignore configure requests until both the Maximized properties have been processed + * to prevent condition where WM overrides size of request due to one or both of these + * properties still being set - which causes a position adjustment to be sent back to + * the server thus causing the window to not return to its original size + */ + if (appWindow->rail_state == WINDOW_SHOW_MAXIMIZED) + appWindow->rail_ignore_configure = TRUE; + + if (appWindow->is_transient) + xf_SetWindowUnlisted(xfc, appWindow->handle); + + XMapWindow(xfc->display, appWindow->handle); + break; + default: + break; + } + + /* Save the current rail state of this window */ + appWindow->rail_state = state; + XFlush(xfc->display); +} + +void xf_SetWindowRects(xfContext* xfc, xfAppWindow* appWindow, RECTANGLE_16* rects, int nrects) +{ + XRectangle* xrects = NULL; + + if (nrects < 1) + return; + +#ifdef WITH_XEXT + xrects = (XRectangle*)calloc(WINPR_ASSERTING_INT_CAST(uint32_t, nrects), sizeof(XRectangle)); + + for (int i = 0; i < nrects; i++) + { + xrects[i].x = WINPR_ASSERTING_INT_CAST(short, rects[i].left); + xrects[i].y = WINPR_ASSERTING_INT_CAST(short, rects[i].top); + xrects[i].width = WINPR_ASSERTING_INT_CAST(unsigned short, rects[i].right - rects[i].left); + xrects[i].height = WINPR_ASSERTING_INT_CAST(unsigned short, rects[i].bottom - rects[i].top); + } + + XShapeCombineRectangles(xfc->display, appWindow->handle, ShapeBounding, 0, 0, xrects, nrects, + ShapeSet, 0); + free(xrects); +#endif +} + +void xf_SetWindowVisibilityRects(xfContext* xfc, xfAppWindow* appWindow, UINT32 rectsOffsetX, + UINT32 rectsOffsetY, RECTANGLE_16* rects, int nrects) +{ + XRectangle* xrects = NULL; + + if (nrects < 1) + return; + +#ifdef WITH_XEXT + xrects = (XRectangle*)calloc(WINPR_ASSERTING_INT_CAST(uint32_t, nrects), sizeof(XRectangle)); + + for (int i = 0; i < nrects; i++) + { + xrects[i].x = WINPR_ASSERTING_INT_CAST(short, rects[i].left); + xrects[i].y = WINPR_ASSERTING_INT_CAST(short, rects[i].top); + xrects[i].width = WINPR_ASSERTING_INT_CAST(unsigned short, rects[i].right - rects[i].left); + xrects[i].height = WINPR_ASSERTING_INT_CAST(unsigned short, rects[i].bottom - rects[i].top); + } + + XShapeCombineRectangles( + xfc->display, appWindow->handle, ShapeBounding, WINPR_ASSERTING_INT_CAST(int, rectsOffsetX), + WINPR_ASSERTING_INT_CAST(int, rectsOffsetY), xrects, nrects, ShapeSet, 0); + free(xrects); +#endif +} + +void xf_UpdateWindowArea(xfContext* xfc, xfAppWindow* appWindow, int x, int y, int width, + int height) +{ + int ax = 0; + int ay = 0; + const rdpSettings* settings = NULL; + + WINPR_ASSERT(xfc); + + settings = xfc->common.context.settings; + WINPR_ASSERT(settings); + + if (appWindow == NULL) + return; + + if (appWindow->surfaceId < UINT16_MAX) + return; + + ax = x + appWindow->windowOffsetX; + ay = y + appWindow->windowOffsetY; + + if (ax + width > appWindow->windowOffsetX + appWindow->width) + width = (appWindow->windowOffsetX + appWindow->width - 1) - ax; + + if (ay + height > appWindow->windowOffsetY + appWindow->height) + height = (appWindow->windowOffsetY + appWindow->height - 1) - ay; + + xf_lock_x11(xfc); + + if (freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi)) + { + XPutImage(xfc->display, appWindow->pixmap, appWindow->gc, xfc->image, ax, ay, x, y, + WINPR_ASSERTING_INT_CAST(uint32_t, width), + WINPR_ASSERTING_INT_CAST(uint32_t, height)); + } + + XCopyArea(xfc->display, appWindow->pixmap, appWindow->handle, appWindow->gc, x, y, + WINPR_ASSERTING_INT_CAST(uint32_t, width), WINPR_ASSERTING_INT_CAST(uint32_t, height), + x, y); + XFlush(xfc->display); + xf_unlock_x11(xfc); +} + +static void xf_AppWindowDestroyImage(xfAppWindow* appWindow) +{ + WINPR_ASSERT(appWindow); + if (appWindow->image) + { + appWindow->image->data = NULL; + XDestroyImage(appWindow->image); + appWindow->image = NULL; + } +} + +void xf_DestroyWindow(xfContext* xfc, xfAppWindow* appWindow) +{ + if (!appWindow) + return; + + if (xfc->appWindow == appWindow) + xfc->appWindow = NULL; + + if (appWindow->gc) + XFreeGC(xfc->display, appWindow->gc); + + if (appWindow->pixmap) + XFreePixmap(xfc->display, appWindow->pixmap); + + xf_AppWindowDestroyImage(appWindow); + + if (appWindow->handle) + { + XUnmapWindow(xfc->display, appWindow->handle); + XDestroyWindow(xfc->display, appWindow->handle); + } + + if (appWindow->xfwin) + munmap(0, sizeof(*appWindow->xfwin)); + + if (appWindow->shmid >= 0) + close(appWindow->shmid); + + shm_unlink(get_shm_id()); + appWindow->xfwin = (Window*)-1; + appWindow->shmid = -1; + free(appWindow->title); + free(appWindow->windowRects); + free(appWindow->visibilityRects); + free(appWindow); +} + +xfAppWindow* xf_AppWindowFromX11Window(xfContext* xfc, Window wnd) +{ + ULONG_PTR* pKeys = NULL; + + WINPR_ASSERT(xfc); + if (!xfc->railWindows) + return NULL; + + size_t count = HashTable_GetKeys(xfc->railWindows, &pKeys); + + for (size_t index = 0; index < count; index++) + { + xfAppWindow* appWindow = xf_rail_get_window(xfc, *(UINT64*)pKeys[index]); + + if (!appWindow) + { + free(pKeys); + return NULL; + } + + if (appWindow->handle == wnd) + { + free(pKeys); + return appWindow; + } + } + + free(pKeys); + return NULL; +} + +UINT xf_AppUpdateWindowFromSurface(xfContext* xfc, gdiGfxSurface* surface) +{ + XImage* image = NULL; + UINT rc = ERROR_INTERNAL_ERROR; + + WINPR_ASSERT(xfc); + WINPR_ASSERT(surface); + + xfAppWindow* appWindow = xf_rail_get_window(xfc, surface->windowId); + if (!appWindow) + { + WLog_VRB(TAG, "Failed to find a window for id=0x%08" PRIx64, surface->windowId); + return CHANNEL_RC_OK; + } + + const BOOL swGdi = freerdp_settings_get_bool(xfc->common.context.settings, FreeRDP_SoftwareGdi); + UINT32 nrects = 0; + const RECTANGLE_16* rects = region16_rects(&surface->invalidRegion, &nrects); + + xf_lock_x11(xfc); + if (swGdi) + { + if (appWindow->surfaceId != surface->surfaceId) + { + xf_AppWindowDestroyImage(appWindow); + appWindow->surfaceId = surface->surfaceId; + } + if (appWindow->width != (INT64)surface->width) + xf_AppWindowDestroyImage(appWindow); + if (appWindow->height != (INT64)surface->height) + xf_AppWindowDestroyImage(appWindow); + + if (!appWindow->image) + { + WINPR_ASSERT(xfc->depth != 0); + appWindow->image = XCreateImage( + xfc->display, xfc->visual, WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth), ZPixmap, + 0, (char*)surface->data, surface->width, surface->height, xfc->scanline_pad, + WINPR_ASSERTING_INT_CAST(int, surface->scanline)); + if (!appWindow->image) + { + WLog_WARN(TAG, + "Failed create a XImage[%" PRIu32 "x%" PRIu32 ", scanline=%" PRIu32 + ", bpp=%" PRIu32 "] for window id=0x%08" PRIx64, + surface->width, surface->height, surface->scanline, xfc->depth, + surface->windowId); + goto fail; + } + appWindow->image->byte_order = LSBFirst; + appWindow->image->bitmap_bit_order = LSBFirst; + } + + image = appWindow->image; + } + else + { + xfGfxSurface* xfSurface = (xfGfxSurface*)surface; + image = xfSurface->image; + } + + for (UINT32 x = 0; x < nrects; x++) + { + const RECTANGLE_16* rect = &rects[x]; + const UINT32 width = rect->right - rect->left; + const UINT32 height = rect->bottom - rect->top; + + XPutImage(xfc->display, appWindow->pixmap, appWindow->gc, image, rect->left, rect->top, + rect->left, rect->top, width, height); + + XCopyArea(xfc->display, appWindow->pixmap, appWindow->handle, appWindow->gc, rect->left, + rect->top, width, height, rect->left, rect->top); + } + + rc = CHANNEL_RC_OK; +fail: + XFlush(xfc->display); + xf_unlock_x11(xfc); + return rc; +} + +BOOL xf_AppWindowResize(xfContext* xfc, xfAppWindow* appWindow) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(appWindow); + + if (appWindow->pixmap != 0) + XFreePixmap(xfc->display, appWindow->pixmap); + + WINPR_ASSERT(xfc->depth != 0); + appWindow->pixmap = XCreatePixmap(xfc->display, xfc->drawable, + WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->width), + WINPR_ASSERTING_INT_CAST(uint32_t, appWindow->height), + WINPR_ASSERTING_INT_CAST(uint32_t, xfc->depth)); + xf_AppWindowDestroyImage(appWindow); + + return appWindow->pixmap != 0; +} + +void xf_XSetTransientForHint(xfContext* xfc, xfAppWindow* window) +{ + WINPR_ASSERT(xfc); + WINPR_ASSERT(window); + + if (window->ownerWindowId == 0) + return; + + xfAppWindow* parent = xf_rail_get_window(xfc, window->ownerWindowId); + if (!parent) + return; + + const int rc = XSetTransientForHint(xfc->display, window->handle, parent->handle); + if (rc) + { + char buffer[128] = { 0 }; + WLog_WARN(TAG, "XSetTransientForHint [%d]{%s}", rc, + x11_error_to_string(xfc, rc, buffer, sizeof(buffer))); + } +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.h new file mode 100644 index 0000000000000000000000000000000000000000..efbc67d06a50de6bf7db4fc55c9a5d6c348d1939 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xf_window.h @@ -0,0 +1,210 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Windows + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_WINDOW_H +#define FREERDP_CLIENT_X11_WINDOW_H + +#include + +#include +#include +#include + +typedef struct xf_app_window xfAppWindow; + +typedef struct xf_localmove xfLocalMove; +typedef struct xf_window xfWindow; + +#include "xf_client.h" +#include "xf_floatbar.h" +#include "xfreerdp.h" + +// Extended ICCM flags http://standards.freedesktop.org/wm-spec/wm-spec-latest.html +WINPR_PRAGMA_DIAG_PUSH +WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO + +#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0 +#define _NET_WM_MOVERESIZE_SIZE_TOP 1 +#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2 +#define _NET_WM_MOVERESIZE_SIZE_RIGHT 3 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6 +#define _NET_WM_MOVERESIZE_SIZE_LEFT 7 +#define _NET_WM_MOVERESIZE_MOVE 8 /* movement only */ +#define _NET_WM_MOVERESIZE_SIZE_KEYBOARD 9 /* size via keyboard */ +#define _NET_WM_MOVERESIZE_MOVE_KEYBOARD 10 /* move via keyboard */ +#define _NET_WM_MOVERESIZE_CANCEL 11 /* cancel operation */ + +#define _NET_WM_STATE_REMOVE 0 /* remove/unset property */ +#define _NET_WM_STATE_ADD 1 /* add/set property */ +#define _NET_WM_STATE_TOGGLE 2 /* toggle property */ + +WINPR_PRAGMA_DIAG_POP + +enum xf_localmove_state +{ + LMS_NOT_ACTIVE, + LMS_STARTING, + LMS_ACTIVE, + LMS_TERMINATING +}; + +struct xf_localmove +{ + int root_x; + int root_y; + int window_x; + int window_y; + enum xf_localmove_state state; + int direction; +}; + +struct xf_window +{ + GC gc; + int left; + int top; + int right; + int bottom; + int width; + int height; + int shmid; + Window handle; + Window* xfwin; + xfFloatbar* floatbar; + BOOL decorations; + BOOL is_mapped; + BOOL is_transient; +}; + +struct xf_app_window +{ + xfContext* xfc; + + int x; + int y; + int width; + int height; + char* title; + + UINT32 surfaceId; + UINT64 windowId; + UINT32 ownerWindowId; + + UINT32 dwStyle; + UINT32 dwExStyle; + UINT32 showState; + + INT32 clientOffsetX; + INT32 clientOffsetY; + UINT32 clientAreaWidth; + UINT32 clientAreaHeight; + + INT32 windowOffsetX; + INT32 windowOffsetY; + INT32 windowClientDeltaX; + INT32 windowClientDeltaY; + UINT32 windowWidth; + UINT32 windowHeight; + UINT32 numWindowRects; + RECTANGLE_16* windowRects; + + INT32 visibleOffsetX; + INT32 visibleOffsetY; + UINT32 numVisibilityRects; + RECTANGLE_16* visibilityRects; + + UINT32 localWindowOffsetCorrX; + UINT32 localWindowOffsetCorrY; + + UINT32 resizeMarginLeft; + UINT32 resizeMarginTop; + UINT32 resizeMarginRight; + UINT32 resizeMarginBottom; + + GC gc; + int shmid; + Window handle; + Window* xfwin; + BOOL fullscreen; + BOOL decorations; + BOOL is_mapped; + BOOL is_transient; + xfLocalMove local_move; + BYTE rail_state; + BOOL maxVert; + BOOL maxHorz; + BOOL minimized; + BOOL rail_ignore_configure; + + Pixmap pixmap; + XImage* image; +}; + +void xf_ewmhints_init(xfContext* xfc); + +BOOL xf_GetWorkArea(xfContext* xfc); + +void xf_SetWindowFullscreen(xfContext* xfc, xfWindow* window, BOOL fullscreen); +void xf_SetWindowMinimized(xfContext* xfc, xfWindow* window); +void xf_SetWindowDecorations(xfContext* xfc, Window window, BOOL show); +void xf_SetWindowUnlisted(xfContext* xfc, Window window); + +xfWindow* xf_CreateDesktopWindow(xfContext* xfc, char* name, int width, int height); +void xf_ResizeDesktopWindow(xfContext* xfc, xfWindow* window, int width, int height); +void xf_DestroyDesktopWindow(xfContext* xfc, xfWindow* window); + +Window xf_CreateDummyWindow(xfContext* xfc); +void xf_DestroyDummyWindow(xfContext* xfc, Window window); + +BOOL xf_GetWindowProperty(xfContext* xfc, Window window, Atom property, int length, + unsigned long* nitems, unsigned long* bytes, BYTE** prop); +void xf_SendClientEvent(xfContext* xfc, Window window, Atom atom, unsigned int numArgs, ...); + +BOOL xf_AppWindowCreate(xfContext* xfc, xfAppWindow* appWindow); +int xf_AppWindowInit(xfContext* xfc, xfAppWindow* appWindow); + +BOOL xf_AppWindowResize(xfContext* xfc, xfAppWindow* appWindow); + +void xf_SetWindowText(xfContext* xfc, xfAppWindow* appWindow, const char* name); +void xf_MoveWindow(xfContext* xfc, xfAppWindow* appWindow, int x, int y, int width, int height); +void xf_ShowWindow(xfContext* xfc, xfAppWindow* appWindow, BYTE state); +// void xf_SetWindowIcon(xfContext* xfc, xfAppWindow* appWindow, rdpIcon* icon); +void xf_SetWindowRects(xfContext* xfc, xfAppWindow* appWindow, RECTANGLE_16* rects, int nrects); +void xf_SetWindowVisibilityRects(xfContext* xfc, xfAppWindow* appWindow, UINT32 rectsOffsetX, + UINT32 rectsOffsetY, RECTANGLE_16* rects, int nrects); +void xf_SetWindowStyle(xfContext* xfc, xfAppWindow* appWindow, UINT32 style, UINT32 ex_style); +void xf_SetWindowActions(xfContext* xfc, xfAppWindow* appWindow); +void xf_UpdateWindowArea(xfContext* xfc, xfAppWindow* appWindow, int x, int y, int width, + int height); +UINT xf_AppUpdateWindowFromSurface(xfContext* xfc, gdiGfxSurface* surface); + +void xf_DestroyWindow(xfContext* xfc, xfAppWindow* appWindow); +void xf_SetWindowMinMaxInfo(xfContext* xfc, xfAppWindow* appWindow, int maxWidth, int maxHeight, + int maxPosX, int maxPosY, int minTrackWidth, int minTrackHeight, + int maxTrackWidth, int maxTrackHeight); +void xf_StartLocalMoveSize(xfContext* xfc, xfAppWindow* appWindow, int direction, int x, int y); +void xf_EndLocalMoveSize(xfContext* xfc, xfAppWindow* appWindow); +xfAppWindow* xf_AppWindowFromX11Window(xfContext* xfc, Window wnd); + +const char* window_styles_to_string(UINT32 style, char* buffer, size_t length); +const char* window_styles_ex_to_string(UINT32 styleEx, char* buffer, size_t length); + +#endif /* FREERDP_CLIENT_X11_WINDOW_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/X11/xfreerdp.h b/local-test-freerdp-full-01/afc-freerdp/client/X11/xfreerdp.h new file mode 100644 index 0000000000000000000000000000000000000000..639060a313ea3d48fc97d1276745dba7f89f8aa1 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/X11/xfreerdp.h @@ -0,0 +1,413 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Client + * + * Copyright 2011 Marc-Andre Moreau + * Copyright 2016 Thincast Technologies GmbH + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FREERDP_CLIENT_X11_FREERDP_H +#define FREERDP_CLIENT_X11_FREERDP_H + +#include + +typedef struct xf_context xfContext; + +#ifdef WITH_XCURSOR +#include +#endif + +#ifdef WITH_XI +#include +#endif + +#include + +#include "xf_window.h" +#include "xf_monitor.h" +#include "xf_channels.h" + +#if defined(CHANNEL_TSMF_CLIENT) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(XcursorUInt) +typedef unsigned int XcursorUInt; +#endif + +#if !defined(XcursorPixel) +typedef XcursorUInt XcursorPixel; +#endif + +struct xf_FullscreenMonitors +{ + INT32 top; + INT32 bottom; + INT32 left; + INT32 right; +}; +typedef struct xf_FullscreenMonitors xfFullscreenMonitors; + +struct xf_WorkArea +{ + INT32 x; + INT32 y; + UINT32 width; + UINT32 height; +}; +typedef struct xf_WorkArea xfWorkArea; + +struct xf_pointer +{ + rdpPointer pointer; + XcursorPixel* cursorPixels; + UINT32 nCursors; + UINT32 mCursors; + UINT32* cursorWidths; + UINT32* cursorHeights; + Cursor* cursors; + Cursor cursor; +}; +typedef struct xf_pointer xfPointer; + +struct xf_bitmap +{ + rdpBitmap bitmap; + Pixmap pixmap; + XImage* image; +}; +typedef struct xf_bitmap xfBitmap; + +struct xf_glyph +{ + rdpGlyph glyph; + Pixmap pixmap; +}; +typedef struct xf_glyph xfGlyph; + +typedef struct xf_clipboard xfClipboard; +typedef struct s_xfDispContext xfDispContext; +typedef struct s_xfVideoContext xfVideoContext; +typedef struct xf_rail_icon_cache xfRailIconCache; + +/* Number of buttons that are mapped from X11 to RDP button events. */ +#define NUM_BUTTONS_MAPPED 11 + +typedef struct +{ + UINT32 button; + UINT16 flags; +} button_map; + +#if defined(WITH_XI) +#define MAX_CONTACTS 20 + +typedef struct touch_contact +{ + int id; + int count; + double pos_x; + double pos_y; + double last_x; + double last_y; + +} touchContact; + +#endif + +struct xf_context +{ + rdpClientContext common; + + GC gc; + int xfds; + int depth; + + GC gc_mono; + BOOL invert; + Screen* screen; + XImage* image; + Pixmap primary; + Pixmap drawing; + Visual* visual; + Display* display; + Drawable drawable; + Pixmap bitmap_mono; + Colormap colormap; + int screen_number; + int scanline_pad; + BOOL big_endian; + BOOL fullscreen; + BOOL decorations; + BOOL grab_keyboard; + BOOL unobscured; + BOOL debug; + HANDLE x11event; + xfWindow* window; + xfAppWindow* appWindow; + xfPointer* pointer; + xfWorkArea workArea; + xfFullscreenMonitors fullscreenMonitors; + int current_desktop; + BOOL remote_app; + HANDLE mutex; + BOOL UseXThreads; + BOOL cursorHidden; + + UINT32 bitmap_size; + BYTE* bitmap_buffer; + + BOOL frame_begin; + + int XInputOpcode; + + int savedWidth; + int savedHeight; + int savedPosX; + int savedPosY; + +#ifdef WITH_XRENDER + int scaledWidth; + int scaledHeight; + int offset_x; + int offset_y; +#endif + + BOOL focused; + BOOL mouse_active; + BOOL fullscreen_toggle; + UINT32 KeyboardLayout; + BOOL KeyboardState[256]; + XModifierKeymap* modifierMap; + wArrayList* keyCombinations; + wArrayList* xevents; + BOOL actionScriptExists; + + int attribs_mask; + XSetWindowAttributes attribs; + BOOL complex_regions; + VIRTUAL_SCREEN vscreen; +#if defined(CHANNEL_TSMF_CLIENT) + void* xv_context; +#endif + + Atom* supportedAtoms; + unsigned long supportedAtomCount; + + Atom UTF8_STRING; + + Atom _XWAYLAND_MAY_GRAB_KEYBOARD; + + Atom _NET_WM_ICON; + Atom _MOTIF_WM_HINTS; + Atom _NET_NUMBER_OF_DESKTOPS; + Atom _NET_CURRENT_DESKTOP; + Atom _NET_WORKAREA; + + Atom _NET_SUPPORTED; + Atom _NET_SUPPORTING_WM_CHECK; + + Atom _NET_WM_STATE; + Atom _NET_WM_STATE_MODAL; + Atom _NET_WM_STATE_STICKY; + Atom _NET_WM_STATE_MAXIMIZED_VERT; + Atom _NET_WM_STATE_MAXIMIZED_HORZ; + Atom _NET_WM_STATE_SHADED; + Atom _NET_WM_STATE_SKIP_TASKBAR; + Atom _NET_WM_STATE_SKIP_PAGER; + Atom _NET_WM_STATE_HIDDEN; + Atom _NET_WM_STATE_FULLSCREEN; + Atom _NET_WM_STATE_ABOVE; + Atom _NET_WM_STATE_BELOW; + Atom _NET_WM_STATE_DEMANDS_ATTENTION; + + Atom _NET_WM_FULLSCREEN_MONITORS; + + Atom _NET_WM_NAME; + Atom _NET_WM_PID; + + Atom _NET_WM_WINDOW_TYPE; + Atom _NET_WM_WINDOW_TYPE_NORMAL; + Atom _NET_WM_WINDOW_TYPE_DIALOG; + Atom _NET_WM_WINDOW_TYPE_UTILITY; + Atom _NET_WM_WINDOW_TYPE_POPUP; + Atom _NET_WM_WINDOW_TYPE_POPUP_MENU; + Atom _NET_WM_WINDOW_TYPE_DROPDOWN_MENU; + + Atom _NET_WM_MOVERESIZE; + Atom _NET_MOVERESIZE_WINDOW; + + Atom WM_STATE; + Atom WM_PROTOCOLS; + Atom WM_DELETE_WINDOW; + + /* Allow actions */ + Atom NET_WM_ALLOWED_ACTIONS; + + Atom NET_WM_ACTION_CLOSE; + Atom NET_WM_ACTION_MINIMIZE; + Atom NET_WM_ACTION_MOVE; + Atom NET_WM_ACTION_RESIZE; + Atom NET_WM_ACTION_MAXIMIZE_HORZ; + Atom NET_WM_ACTION_MAXIMIZE_VERT; + Atom NET_WM_ACTION_FULLSCREEN; + Atom NET_WM_ACTION_CHANGE_DESKTOP; + + /* Channels */ +#if defined(CHANNEL_TSMF_CLIENT) + TsmfClientContext* tsmf; +#endif + + xfClipboard* clipboard; + CliprdrClientContext* cliprdr; + xfVideoContext* xfVideo; + xfDispContext* xfDisp; + + RailClientContext* rail; + wHashTable* railWindows; + xfRailIconCache* railIconCache; + + BOOL xkbAvailable; + BOOL xrenderAvailable; + + /* value to be sent over wire for each logical client mouse button */ + button_map button_map[NUM_BUTTONS_MAPPED]; + BYTE savedMaximizedState; + UINT32 locked; + BOOL wasRightCtrlAlreadyPressed; + BOOL ungrabKeyboardWithRightCtrl; + +#if defined(WITH_XI) + touchContact contacts[MAX_CONTACTS]; + int active_contacts; + int lastEvType; + XIDeviceEvent lastEvent; + double firstDist; + double lastDist; + double z_vector; + double px_vector; + double py_vector; +#endif + BOOL xi_rawevent; + BOOL xi_event; + HANDLE pipethread; + wLog* log; + FREERDP_REMAP_TABLE* remap_table; +}; + +BOOL xf_create_window(xfContext* xfc); +BOOL xf_create_image(xfContext* xfc); +void xf_toggle_fullscreen(xfContext* xfc); +void xf_minimize(xfContext* xfc); + +enum XF_EXIT_CODE +{ + /* section 0-15: protocol-independent codes */ + XF_EXIT_SUCCESS = 0, + XF_EXIT_DISCONNECT = 1, + XF_EXIT_LOGOFF = 2, + XF_EXIT_IDLE_TIMEOUT = 3, + XF_EXIT_LOGON_TIMEOUT = 4, + XF_EXIT_CONN_REPLACED = 5, + XF_EXIT_OUT_OF_MEMORY = 6, + XF_EXIT_CONN_DENIED = 7, + XF_EXIT_CONN_DENIED_FIPS = 8, + XF_EXIT_USER_PRIVILEGES = 9, + XF_EXIT_FRESH_CREDENTIALS_REQUIRED = 10, + XF_EXIT_DISCONNECT_BY_USER = 11, + + /* section 16-31: license error set */ + XF_EXIT_LICENSE_INTERNAL = 16, + XF_EXIT_LICENSE_NO_LICENSE_SERVER = 17, + XF_EXIT_LICENSE_NO_LICENSE = 18, + XF_EXIT_LICENSE_BAD_CLIENT_MSG = 19, + XF_EXIT_LICENSE_HWID_DOESNT_MATCH = 20, + XF_EXIT_LICENSE_BAD_CLIENT = 21, + XF_EXIT_LICENSE_CANT_FINISH_PROTOCOL = 22, + XF_EXIT_LICENSE_CLIENT_ENDED_PROTOCOL = 23, + XF_EXIT_LICENSE_BAD_CLIENT_ENCRYPTION = 24, + XF_EXIT_LICENSE_CANT_UPGRADE = 25, + XF_EXIT_LICENSE_NO_REMOTE_CONNECTIONS = 26, + + /* section 32-127: RDP protocol error set */ + XF_EXIT_RDP = 32, + + /* section 128-254: xfreerdp specific exit codes */ + XF_EXIT_PARSE_ARGUMENTS = 128, + XF_EXIT_MEMORY = 129, + XF_EXIT_PROTOCOL = 130, + XF_EXIT_CONN_FAILED = 131, + XF_EXIT_AUTH_FAILURE = 132, + XF_EXIT_NEGO_FAILURE = 133, + XF_EXIT_LOGON_FAILURE = 134, + XF_EXIT_ACCOUNT_LOCKED_OUT = 135, + XF_EXIT_PRE_CONNECT_FAILED = 136, + XF_EXIT_CONNECT_UNDEFINED = 137, + XF_EXIT_POST_CONNECT_FAILED = 138, + XF_EXIT_DNS_ERROR = 139, + XF_EXIT_DNS_NAME_NOT_FOUND = 140, + XF_EXIT_CONNECT_FAILED = 141, + XF_EXIT_MCS_CONNECT_INITIAL_ERROR = 142, + XF_EXIT_TLS_CONNECT_FAILED = 143, + XF_EXIT_INSUFFICIENT_PRIVILEGES = 144, + XF_EXIT_CONNECT_CANCELLED = 145, + + XF_EXIT_CONNECT_TRANSPORT_FAILED = 147, + XF_EXIT_CONNECT_PASSWORD_EXPIRED = 148, + XF_EXIT_CONNECT_PASSWORD_MUST_CHANGE = 149, + XF_EXIT_CONNECT_KDC_UNREACHABLE = 150, + XF_EXIT_CONNECT_ACCOUNT_DISABLED = 151, + XF_EXIT_CONNECT_PASSWORD_CERTAINLY_EXPIRED = 152, + XF_EXIT_CONNECT_CLIENT_REVOKED = 153, + XF_EXIT_CONNECT_WRONG_PASSWORD = 154, + XF_EXIT_CONNECT_ACCESS_DENIED = 155, + XF_EXIT_CONNECT_ACCOUNT_RESTRICTION = 156, + XF_EXIT_CONNECT_ACCOUNT_EXPIRED = 157, + XF_EXIT_CONNECT_LOGON_TYPE_NOT_GRANTED = 158, + XF_EXIT_CONNECT_NO_OR_MISSING_CREDENTIALS = 159, + + XF_EXIT_UNKNOWN = 255, +}; + +#define xf_lock_x11(xfc) xf_lock_x11_(xfc, __func__) +#define xf_unlock_x11(xfc) xf_unlock_x11_(xfc, __func__) + +void xf_lock_x11_(xfContext* xfc, const char* fkt); +void xf_unlock_x11_(xfContext* xfc, const char* fkt); + +BOOL xf_picture_transform_required(xfContext* xfc); + +#define xf_draw_screen(_xfc, _x, _y, _w, _h) \ + xf_draw_screen_((_xfc), (_x), (_y), (_w), (_h), __func__, __FILE__, __LINE__) +void xf_draw_screen_(xfContext* xfc, int x, int y, int w, int h, const char* fkt, const char* file, + int line); + +BOOL xf_keyboard_update_modifier_map(xfContext* xfc); + +int xf_exit_code_from_disconnect_reason(DWORD reason); + +#endif /* FREERDP_CLIENT_X11_FREERDP_H */ diff --git a/local-test-freerdp-full-01/afc-freerdp/client/common/CMakeLists.txt b/local-test-freerdp-full-01/afc-freerdp/client/common/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fedac6c5e63625308214fa8654181ca81f3dc212 --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/common/CMakeLists.txt @@ -0,0 +1,91 @@ +# FreeRDP: A Remote Desktop Protocol Implementation +# FreeRDP Client Common +# +# Copyright 2012 Marc-Andre Moreau +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set(MODULE_NAME "freerdp-client") +set(MODULE_PREFIX "FREERDP_CLIENT") + +# Policy CMP0022: INTERFACE_LINK_LIBRARIES defines the link +# interface. Run "cmake --help-policy CMP0022" for policy details. Use the +# cmake_policy command to set the policy and suppress this warning. +if(POLICY CMP0022) + cmake_policy(SET CMP0022 NEW) +endif() + +set(SRCS + client.c + cmdline.c + cmdline.h + file.c + client_cliprdr_file.c + geometry.c + smartcard_cli.c +) + +foreach(FREERDP_CHANNELS_CLIENT_SRC ${FREERDP_CHANNELS_CLIENT_SRCS}) + get_filename_component(NINC ${FREERDP_CHANNELS_CLIENT_SRC} PATH) + include_directories(${NINC}) + list(APPEND SRCS "${FREERDP_CHANNELS_CLIENT_SRC}") +endforeach() + +if(NOT APPLE AND NOT WIN32 AND NOT ANDROID) + set(OPT_FUSE_DEFAULT ON) +else() + set(OPT_FUSE_DEFAULT OFF) +endif() + +option(WITH_FUSE "Build clipboard with FUSE file copy support" ${OPT_FUSE_DEFAULT}) +if(WITH_FUSE) + find_package(PkgConfig REQUIRED) + + pkg_check_modules(FUSE3 REQUIRED fuse3) + include_directories(SYSTEM ${FUSE3_INCLUDE_DIRS}) + add_compile_definitions(WITH_FUSE) + list(APPEND LIBS ${FUSE3_LIBRARIES}) + + add_compile_definitions(_FILE_OFFSET_BITS=64) +endif() + +include_directories(SYSTEM ${OPENSSL_INCLUDE_DIR}) + +addtargetwithresourcefile(${MODULE_NAME} FALSE "${FREERDP_VERSION}" SRCS) + +list(APPEND LIBS freerdp winpr) + +include(CheckLibraryExists) +check_library_exists(m lround "" HAVE_LIB_M) +if(HAVE_LIB_M) + list(APPEND LIBS m) +endif() + +target_include_directories(${MODULE_NAME} INTERFACE $) +target_link_libraries(${MODULE_NAME} PRIVATE ${FREERDP_CHANNELS_CLIENT_LIBS}) +target_link_libraries(${MODULE_NAME} PUBLIC ${LIBS}) + +install(TARGETS ${MODULE_NAME} COMPONENT libraries EXPORT FreeRDP-ClientTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "Client/Common") + +if(BUILD_TESTING_INTERNAL OR BUILD_TESTING) + add_subdirectory(test) +endif() + +if(WITH_MANPAGES) + add_subdirectory(man) +endif() diff --git a/local-test-freerdp-full-01/afc-freerdp/client/common/client.c b/local-test-freerdp-full-01/afc-freerdp/client/common/client.c new file mode 100644 index 0000000000000000000000000000000000000000..4dbe3e075a708257553b6f48617354a801a7944d --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/common/client.c @@ -0,0 +1,2249 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Client Common + * + * Copyright 2012 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CHANNEL_AINPUT_CLIENT) +#include +#include +#endif + +#if defined(CHANNEL_VIDEO_CLIENT) +#include +#include +#endif + +#if defined(CHANNEL_RDPGFX_CLIENT) +#include +#include +#include +#endif + +#if defined(CHANNEL_GEOMETRY_CLIENT) +#include +#include +#endif + +#if defined(CHANNEL_GEOMETRY_CLIENT) || defined(CHANNEL_VIDEO_CLIENT) +#include +#endif + +#ifdef WITH_AAD +#include +#include +#endif + +#include +#define TAG CLIENT_TAG("common") + +static void set_default_callbacks(freerdp* instance) +{ + WINPR_ASSERT(instance); + instance->AuthenticateEx = client_cli_authenticate_ex; + instance->ChooseSmartcard = client_cli_choose_smartcard; + instance->VerifyCertificateEx = client_cli_verify_certificate_ex; + instance->VerifyChangedCertificateEx = client_cli_verify_changed_certificate_ex; + instance->PresentGatewayMessage = client_cli_present_gateway_message; + instance->LogonErrorInfo = client_cli_logon_error_info; + instance->GetAccessToken = client_cli_get_access_token; + instance->RetryDialog = client_common_retry_dialog; +} + +static BOOL freerdp_client_common_new(freerdp* instance, rdpContext* context) +{ + RDP_CLIENT_ENTRY_POINTS* pEntryPoints = NULL; + + WINPR_ASSERT(instance); + WINPR_ASSERT(context); + + instance->LoadChannels = freerdp_client_load_channels; + set_default_callbacks(instance); + + pEntryPoints = instance->pClientEntryPoints; + WINPR_ASSERT(pEntryPoints); + return IFCALLRESULT(TRUE, pEntryPoints->ClientNew, instance, context); +} + +static void freerdp_client_common_free(freerdp* instance, rdpContext* context) +{ + RDP_CLIENT_ENTRY_POINTS* pEntryPoints = NULL; + + WINPR_ASSERT(instance); + WINPR_ASSERT(context); + + pEntryPoints = instance->pClientEntryPoints; + WINPR_ASSERT(pEntryPoints); + IFCALL(pEntryPoints->ClientFree, instance, context); +} + +/* Common API */ + +rdpContext* freerdp_client_context_new(const RDP_CLIENT_ENTRY_POINTS* pEntryPoints) +{ + freerdp* instance = NULL; + rdpContext* context = NULL; + + if (!pEntryPoints) + return NULL; + + IFCALL(pEntryPoints->GlobalInit); + instance = freerdp_new(); + + if (!instance) + return NULL; + + instance->ContextSize = pEntryPoints->ContextSize; + instance->ContextNew = freerdp_client_common_new; + instance->ContextFree = freerdp_client_common_free; + instance->pClientEntryPoints = (RDP_CLIENT_ENTRY_POINTS*)malloc(pEntryPoints->Size); + + if (!instance->pClientEntryPoints) + goto out_fail; + + CopyMemory(instance->pClientEntryPoints, pEntryPoints, pEntryPoints->Size); + + if (!freerdp_context_new_ex(instance, pEntryPoints->settings)) + goto out_fail2; + + context = instance->context; + context->instance = instance; + +#if defined(WITH_CHANNELS) + if (freerdp_register_addin_provider(freerdp_channels_load_static_addin_entry, 0) != + CHANNEL_RC_OK) + goto out_fail2; +#endif + + return context; +out_fail2: + free(instance->pClientEntryPoints); +out_fail: + freerdp_free(instance); + return NULL; +} + +void freerdp_client_context_free(rdpContext* context) +{ + freerdp* instance = NULL; + + if (!context) + return; + + instance = context->instance; + + if (instance) + { + RDP_CLIENT_ENTRY_POINTS* pEntryPoints = instance->pClientEntryPoints; + freerdp_context_free(instance); + + if (pEntryPoints) + IFCALL(pEntryPoints->GlobalUninit); + + free(instance->pClientEntryPoints); + freerdp_free(instance); + } +} + +int freerdp_client_start(rdpContext* context) +{ + RDP_CLIENT_ENTRY_POINTS* pEntryPoints = NULL; + + if (!context || !context->instance || !context->instance->pClientEntryPoints) + return ERROR_BAD_ARGUMENTS; + + if (freerdp_settings_get_bool(context->settings, FreeRDP_UseCommonStdioCallbacks)) + set_default_callbacks(context->instance); + + pEntryPoints = context->instance->pClientEntryPoints; + return IFCALLRESULT(CHANNEL_RC_OK, pEntryPoints->ClientStart, context); +} + +int freerdp_client_stop(rdpContext* context) +{ + RDP_CLIENT_ENTRY_POINTS* pEntryPoints = NULL; + + if (!context || !context->instance || !context->instance->pClientEntryPoints) + return ERROR_BAD_ARGUMENTS; + + pEntryPoints = context->instance->pClientEntryPoints; + return IFCALLRESULT(CHANNEL_RC_OK, pEntryPoints->ClientStop, context); +} + +freerdp* freerdp_client_get_instance(rdpContext* context) +{ + if (!context || !context->instance) + return NULL; + + return context->instance; +} + +HANDLE freerdp_client_get_thread(rdpContext* context) +{ + if (!context) + return NULL; + + return ((rdpClientContext*)context)->thread; +} + +static BOOL freerdp_client_settings_post_process(rdpSettings* settings) +{ + /* Moved GatewayUseSameCredentials logic outside of cmdline.c, so + * that the rdp file also triggers this functionality */ + if (freerdp_settings_get_bool(settings, FreeRDP_GatewayEnabled)) + { + if (freerdp_settings_get_bool(settings, FreeRDP_GatewayUseSameCredentials)) + { + const char* Username = freerdp_settings_get_string(settings, FreeRDP_Username); + const char* Domain = freerdp_settings_get_string(settings, FreeRDP_Domain); + if (Username) + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayUsername, Username)) + goto out_error; + } + + if (Domain) + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayDomain, Domain)) + goto out_error; + } + + if (freerdp_settings_get_string(settings, FreeRDP_Password)) + { + if (!freerdp_settings_set_string( + settings, FreeRDP_GatewayPassword, + freerdp_settings_get_string(settings, FreeRDP_Password))) + goto out_error; + } + } + } + + /* Moved logic for Multimon and Span monitors to force fullscreen, so + * that the rdp file also triggers this functionality */ + if (freerdp_settings_get_bool(settings, FreeRDP_SpanMonitors)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_UseMultimon, TRUE)) + goto out_error; + if (!freerdp_settings_set_bool(settings, FreeRDP_Fullscreen, TRUE)) + goto out_error; + } + else if (freerdp_settings_get_bool(settings, FreeRDP_UseMultimon)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_Fullscreen, TRUE)) + goto out_error; + } + + /* deal with the smartcard / smartcard logon stuff */ + if (freerdp_settings_get_bool(settings, FreeRDP_SmartcardLogon)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_TlsSecurity, TRUE)) + goto out_error; + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectSmartCards, TRUE)) + goto out_error; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + goto out_error; + if (!freerdp_settings_set_bool(settings, FreeRDP_PasswordIsSmartcardPin, TRUE)) + goto out_error; + } + + return TRUE; +out_error: + return FALSE; +} + +int freerdp_client_settings_parse_command_line(rdpSettings* settings, int argc, char** argv, + BOOL allowUnknown) + +{ + return freerdp_client_settings_parse_command_line_ex(settings, argc, argv, allowUnknown, NULL, + 0, NULL, NULL); +} + +int freerdp_client_settings_parse_command_line_ex( + rdpSettings* settings, int argc, char** argv, BOOL allowUnknown, COMMAND_LINE_ARGUMENT_A* args, + size_t count, freerdp_command_line_handle_option_t handle_option, void* handle_userdata) +{ + int status = 0; + + if (argc < 1) + return 0; + + if (!argv) + return -1; + + status = freerdp_client_settings_parse_command_line_arguments_ex( + settings, argc, argv, allowUnknown, args, count, handle_option, handle_userdata); + + if (status < 0) + return status; + + /* This function will call logic that is applicable to the settings + * from command line parsing AND the rdp file parsing */ + if (!freerdp_client_settings_post_process(settings)) + status = -1; + + const char* name = (argc > 0) ? argv[0] : "argc < 1"; + WLog_DBG(TAG, "This is [%s] %s %s", name, freerdp_get_version_string(), + freerdp_get_build_config()); + return status; +} + +int freerdp_client_settings_parse_connection_file(rdpSettings* settings, const char* filename) +{ + rdpFile* file = NULL; + int ret = -1; + file = freerdp_client_rdp_file_new(); + + if (!file) + return -1; + + if (!freerdp_client_parse_rdp_file(file, filename)) + goto out; + + if (!freerdp_client_populate_settings_from_rdp_file(file, settings)) + goto out; + + ret = 0; +out: + freerdp_client_rdp_file_free(file); + return ret; +} + +int freerdp_client_settings_parse_connection_file_buffer(rdpSettings* settings, const BYTE* buffer, + size_t size) +{ + rdpFile* file = NULL; + int status = -1; + file = freerdp_client_rdp_file_new(); + + if (!file) + return -1; + + if (freerdp_client_parse_rdp_file_buffer(file, buffer, size) && + freerdp_client_populate_settings_from_rdp_file(file, settings)) + { + status = 0; + } + + freerdp_client_rdp_file_free(file); + return status; +} + +int freerdp_client_settings_write_connection_file(const rdpSettings* settings, const char* filename, + BOOL unicode) +{ + rdpFile* file = NULL; + int ret = -1; + file = freerdp_client_rdp_file_new(); + + if (!file) + return -1; + + if (!freerdp_client_populate_rdp_file_from_settings(file, settings)) + goto out; + + if (!freerdp_client_write_rdp_file(file, filename, unicode)) + goto out; + + ret = 0; +out: + freerdp_client_rdp_file_free(file); + return ret; +} + +int freerdp_client_settings_parse_assistance_file(rdpSettings* settings, int argc, char* argv[]) +{ + int status = 0; + int ret = -1; + char* filename = NULL; + char* password = NULL; + rdpAssistanceFile* file = NULL; + + if (!settings || !argv || (argc < 2)) + return -1; + + filename = argv[1]; + + for (int x = 2; x < argc; x++) + { + const char* key = strstr(argv[x], "assistance:"); + + if (key) + password = strchr(key, ':') + 1; + } + + file = freerdp_assistance_file_new(); + + if (!file) + return -1; + + status = freerdp_assistance_parse_file(file, filename, password); + + if (status < 0) + goto out; + + if (!freerdp_assistance_populate_settings_from_assistance_file(file, settings)) + goto out; + + ret = 0; +out: + freerdp_assistance_file_free(file); + return ret; +} + +/** Callback set in the rdp_freerdp structure, and used to get the user's password, + * if required to establish the connection. + * This function is actually called in credssp_ntlmssp_client_init() + * @see rdp_server_accept_nego() and rdp_check_fds() + * @param instance - pointer to the rdp_freerdp structure that contains the connection settings + * @param username - unused + * @param password - on return: pointer to a character string that will be filled by the password + * entered by the user. Note that this character string will be allocated inside the function, and + * needs to be deallocated by the caller using free(), even in case this function fails. + * @param domain - unused + * @return TRUE if a password was successfully entered. See freerdp_passphrase_read() for more + * details. + */ +static BOOL client_cli_authenticate_raw(freerdp* instance, rdp_auth_reason reason, char** username, + char** password, char** domain) +{ + static const size_t password_size = 512; + const char* auth[] = { "Username: ", "Domain: ", "Password: " }; + const char* authPin[] = { "Username: ", "Domain: ", "Smartcard-Pin: " }; + const char* gw[] = { "GatewayUsername: ", "GatewayDomain: ", "GatewayPassword: " }; + const char** prompt = NULL; + BOOL pinOnly = FALSE; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + switch (reason) + { + case AUTH_SMARTCARD_PIN: + prompt = authPin; + pinOnly = TRUE; + break; + case AUTH_TLS: + case AUTH_RDP: + case AUTH_NLA: + prompt = auth; + break; + case GW_AUTH_HTTP: + case GW_AUTH_RDG: + case GW_AUTH_RPC: + prompt = gw; + break; + default: + return FALSE; + } + + if (!username || !password || !domain) + return FALSE; + + if (!*username && !pinOnly) + { + size_t username_size = 0; + printf("%s", prompt[0]); + (void)fflush(stdout); + + if (freerdp_interruptible_get_line(instance->context, username, &username_size, stdin) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "freerdp_interruptible_get_line returned %s [%d]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + goto fail; + } + + if (*username) + { + *username = StrSep(username, "\r"); + *username = StrSep(username, "\n"); + } + } + + if (!*domain && !pinOnly) + { + size_t domain_size = 0; + printf("%s", prompt[1]); + (void)fflush(stdout); + + if (freerdp_interruptible_get_line(instance->context, domain, &domain_size, stdin) < 0) + { + char ebuffer[256] = { 0 }; + WLog_ERR(TAG, "freerdp_interruptible_get_line returned %s [%d]", + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + goto fail; + } + + if (*domain) + { + *domain = StrSep(domain, "\r"); + *domain = StrSep(domain, "\n"); + } + } + + if (!*password) + { + *password = calloc(password_size, sizeof(char)); + + if (!*password) + goto fail; + + const BOOL fromStdin = + freerdp_settings_get_bool(instance->context->settings, FreeRDP_CredentialsFromStdin); + if (freerdp_passphrase_read(instance->context, prompt[2], *password, password_size, + fromStdin) == NULL) + goto fail; + } + + return TRUE; +fail: + free(*username); + free(*domain); + free(*password); + *username = NULL; + *domain = NULL; + *password = NULL; + return FALSE; +} + +BOOL client_cli_authenticate_ex(freerdp* instance, char** username, char** password, char** domain, + rdp_auth_reason reason) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(username); + WINPR_ASSERT(password); + WINPR_ASSERT(domain); + + switch (reason) + { + case AUTH_NLA: + break; + + case AUTH_TLS: + case AUTH_RDP: + case AUTH_SMARTCARD_PIN: /* in this case password is pin code */ + if ((*username) && (*password)) + return TRUE; + break; + case GW_AUTH_HTTP: + case GW_AUTH_RDG: + case GW_AUTH_RPC: + break; + default: + return FALSE; + } + + return client_cli_authenticate_raw(instance, reason, username, password, domain); +} + +BOOL client_cli_choose_smartcard(freerdp* instance, SmartcardCertInfo** cert_list, DWORD count, + DWORD* choice, BOOL gateway) +{ + unsigned long answer = 0; + char* p = NULL; + + printf("Multiple smartcards are available for use:\n"); + for (DWORD i = 0; i < count; i++) + { + const SmartcardCertInfo* cert = cert_list[i]; + char* reader = ConvertWCharToUtf8Alloc(cert->reader, NULL); + char* container_name = ConvertWCharToUtf8Alloc(cert->containerName, NULL); + + printf("[%" PRIu32 + "] %s\n\tReader: %s\n\tUser: %s@%s\n\tSubject: %s\n\tIssuer: %s\n\tUPN: %s\n", + i, container_name, reader, cert->userHint, cert->domainHint, cert->subject, + cert->issuer, cert->upn); + + free(reader); + free(container_name); + } + + while (1) + { + char input[10] = { 0 }; + + printf("\nChoose a smartcard to use for %s (0 - %" PRIu32 "): ", + gateway ? "gateway authentication" : "logon", count - 1); + (void)fflush(stdout); + if (!fgets(input, 10, stdin)) + { + WLog_ERR(TAG, "could not read from stdin"); + return FALSE; + } + + answer = strtoul(input, &p, 10); + if ((*p == '\n' && p != input) && answer < count) + { + *choice = (UINT32)answer; + return TRUE; + } + } +} + +#if defined(WITH_FREERDP_DEPRECATED) +BOOL client_cli_authenticate(freerdp* instance, char** username, char** password, char** domain) +{ + if (freerdp_settings_get_bool(instance->settings, FreeRDP_SmartcardLogon)) + { + WLog_INFO(TAG, "Authentication via smartcard"); + return TRUE; + } + + return client_cli_authenticate_raw(instance, FALSE, username, password, domain); +} + +BOOL client_cli_gw_authenticate(freerdp* instance, char** username, char** password, char** domain) +{ + return client_cli_authenticate_raw(instance, TRUE, username, password, domain); +} +#endif + +static DWORD client_cli_accept_certificate(freerdp* instance) +{ + int answer = 0; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + const rdpSettings* settings = instance->context->settings; + WINPR_ASSERT(settings); + + const BOOL fromStdin = freerdp_settings_get_bool(settings, FreeRDP_CredentialsFromStdin); + if (fromStdin) + return 0; + + while (1) + { + printf("Do you trust the above certificate? (Y/T/N) "); + (void)fflush(stdout); + answer = freerdp_interruptible_getc(instance->context, stdin); + + if ((answer == EOF) || feof(stdin)) + { + printf("\nError: Could not read answer from stdin.\n"); + return 0; + } + + switch (answer) + { + case 'y': + case 'Y': + answer = freerdp_interruptible_getc(instance->context, stdin); + if (answer == EOF) + return 0; + return 1; + + case 't': + case 'T': + answer = freerdp_interruptible_getc(instance->context, stdin); + if (answer == EOF) + return 0; + return 2; + + case 'n': + case 'N': + answer = freerdp_interruptible_getc(instance->context, stdin); + if (answer == EOF) + return 0; + return 0; + + default: + break; + } + + printf("\n"); + } +} + +/** Callback set in the rdp_freerdp structure, and used to make a certificate validation + * when the connection requires it. + * This function will actually be called by tls_verify_certificate(). + * @see rdp_client_connect() and freerdp_tls_connect() + * @deprecated Use client_cli_verify_certificate_ex + * @param instance - pointer to the rdp_freerdp structure that contains the connection settings + * @param common_name + * @param subject + * @param issuer + * @param fingerprint + * @param host_mismatch Indicates the certificate host does not match. + * @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise. + */ +#if defined(WITH_FREERDP_DEPRECATED) +DWORD client_cli_verify_certificate(freerdp* instance, const char* common_name, const char* subject, + const char* issuer, const char* fingerprint, BOOL host_mismatch) +{ + WINPR_UNUSED(common_name); + WINPR_UNUSED(host_mismatch); + + printf("WARNING: This callback is deprecated, migrate to client_cli_verify_certificate_ex\n"); + printf("Certificate details:\n"); + printf("\tSubject: %s\n", subject); + printf("\tIssuer: %s\n", issuer); + printf("\tThumbprint: %s\n", fingerprint); + printf("The above X.509 certificate could not be verified, possibly because you do not have\n" + "the CA certificate in your certificate store, or the certificate has expired.\n" + "Please look at the OpenSSL documentation on how to add a private CA to the store.\n"); + return client_cli_accept_certificate(instance); +} +#endif + +static char* client_cli_pem_cert(const char* pem) +{ + rdpCertificate* cert = freerdp_certificate_new_from_pem(pem); + if (!cert) + return NULL; + + char* fp = freerdp_certificate_get_fingerprint(cert); + char* start = freerdp_certificate_get_validity(cert, TRUE); + char* end = freerdp_certificate_get_validity(cert, FALSE); + freerdp_certificate_free(cert); + + char* str = NULL; + size_t slen = 0; + winpr_asprintf(&str, &slen, + "\tValid from: %s\n" + "\tValid to: %s\n" + "\tThumbprint: %s\n", + start, end, fp); + free(fp); + free(start); + free(end); + return str; +} + +/** Callback set in the rdp_freerdp structure, and used to make a certificate validation + * when the connection requires it. + * This function will actually be called by tls_verify_certificate(). + * @see rdp_client_connect() and freerdp_tls_connect() + * @param instance pointer to the rdp_freerdp structure that contains the connection settings + * @param host The host currently connecting to + * @param port The port currently connecting to + * @param common_name The common name of the certificate, should match host or an alias of it + * @param subject The subject of the certificate + * @param issuer The certificate issuer name + * @param fingerprint The fingerprint of the certificate + * @param flags See VERIFY_CERT_FLAG_* for possible values. + * + * @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise. + */ +DWORD client_cli_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port, + const char* common_name, const char* subject, + const char* issuer, const char* fingerprint, DWORD flags) +{ + const char* type = "RDP-Server"; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + if (flags & VERIFY_CERT_FLAG_GATEWAY) + type = "RDP-Gateway"; + + if (flags & VERIFY_CERT_FLAG_REDIRECT) + type = "RDP-Redirect"; + + printf("Certificate details for %s:%" PRIu16 " (%s):\n", host, port, type); + printf("\tCommon Name: %s\n", common_name); + printf("\tSubject: %s\n", subject); + printf("\tIssuer: %s\n", issuer); + /* Newer versions of FreeRDP allow exposing the whole PEM by setting + * FreeRDP_CertificateCallbackPreferPEM to TRUE + */ + if (flags & VERIFY_CERT_FLAG_FP_IS_PEM) + { + char* str = client_cli_pem_cert(fingerprint); + printf("%s", str); + free(str); + } + else + printf("\tThumbprint: %s\n", fingerprint); + + printf("The above X.509 certificate could not be verified, possibly because you do not have\n" + "the CA certificate in your certificate store, or the certificate has expired.\n" + "Please look at the OpenSSL documentation on how to add a private CA to the store.\n"); + return client_cli_accept_certificate(instance); +} + +/** Callback set in the rdp_freerdp structure, and used to make a certificate validation + * when a stored certificate does not match the remote counterpart. + * This function will actually be called by tls_verify_certificate(). + * @see rdp_client_connect() and freerdp_tls_connect() + * @deprecated Use client_cli_verify_changed_certificate_ex + * @param instance - pointer to the rdp_freerdp structure that contains the connection settings + * @param common_name + * @param subject + * @param issuer + * @param fingerprint + * @param old_subject + * @param old_issuer + * @param old_fingerprint + * @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise. + */ +#if defined(WITH_FREERDP_DEPRECATED) +DWORD client_cli_verify_changed_certificate(freerdp* instance, const char* common_name, + const char* subject, const char* issuer, + const char* fingerprint, const char* old_subject, + const char* old_issuer, const char* old_fingerprint) +{ + WINPR_UNUSED(common_name); + + printf("WARNING: This callback is deprecated, migrate to " + "client_cli_verify_changed_certificate_ex\n"); + printf("!!! Certificate has changed !!!\n"); + printf("\n"); + printf("New Certificate details:\n"); + printf("\tSubject: %s\n", subject); + printf("\tIssuer: %s\n", issuer); + printf("\tThumbprint: %s\n", fingerprint); + printf("\n"); + printf("Old Certificate details:\n"); + printf("\tSubject: %s\n", old_subject); + printf("\tIssuer: %s\n", old_issuer); + printf("\tThumbprint: %s\n", old_fingerprint); + printf("\n"); + printf("The above X.509 certificate does not match the certificate used for previous " + "connections.\n" + "This may indicate that the certificate has been tampered with.\n" + "Please contact the administrator of the RDP server and clarify.\n"); + return client_cli_accept_certificate(instance); +} +#endif + +/** Callback set in the rdp_freerdp structure, and used to make a certificate validation + * when a stored certificate does not match the remote counterpart. + * This function will actually be called by tls_verify_certificate(). + * @see rdp_client_connect() and freerdp_tls_connect() + * @param instance pointer to the rdp_freerdp structure that contains the connection + * settings + * @param host The host currently connecting to + * @param port The port currently connecting to + * @param common_name The common name of the certificate, should match host or an alias of it + * @param subject The subject of the certificate + * @param issuer The certificate issuer name + * @param fingerprint The fingerprint of the certificate + * @param old_subject The subject of the previous certificate + * @param old_issuer The previous certificate issuer name + * @param old_fingerprint The fingerprint of the previous certificate + * @param flags See VERIFY_CERT_FLAG_* for possible values. + * + * @return 1 if the certificate is trusted, 2 if temporary trusted, 0 otherwise. + */ +DWORD client_cli_verify_changed_certificate_ex(freerdp* instance, const char* host, UINT16 port, + const char* common_name, const char* subject, + const char* issuer, const char* fingerprint, + const char* old_subject, const char* old_issuer, + const char* old_fingerprint, DWORD flags) +{ + const char* type = "RDP-Server"; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + if (flags & VERIFY_CERT_FLAG_GATEWAY) + type = "RDP-Gateway"; + + if (flags & VERIFY_CERT_FLAG_REDIRECT) + type = "RDP-Redirect"; + + printf("!!!Certificate for %s:%" PRIu16 " (%s) has changed!!!\n", host, port, type); + printf("\n"); + printf("New Certificate details:\n"); + printf("\tCommon Name: %s\n", common_name); + printf("\tSubject: %s\n", subject); + printf("\tIssuer: %s\n", issuer); + /* Newer versions of FreeRDP allow exposing the whole PEM by setting + * FreeRDP_CertificateCallbackPreferPEM to TRUE + */ + if (flags & VERIFY_CERT_FLAG_FP_IS_PEM) + { + char* str = client_cli_pem_cert(fingerprint); + printf("%s", str); + free(str); + } + else + printf("\tThumbprint: %s\n", fingerprint); + printf("\n"); + printf("Old Certificate details:\n"); + printf("\tSubject: %s\n", old_subject); + printf("\tIssuer: %s\n", old_issuer); + /* Newer versions of FreeRDP allow exposing the whole PEM by setting + * FreeRDP_CertificateCallbackPreferPEM to TRUE + */ + if (flags & VERIFY_CERT_FLAG_FP_IS_PEM) + { + char* str = client_cli_pem_cert(old_fingerprint); + printf("%s", str); + free(str); + } + else + printf("\tThumbprint: %s\n", old_fingerprint); + printf("\n"); + if (flags & VERIFY_CERT_FLAG_MATCH_LEGACY_SHA1) + { + printf("\tA matching entry with legacy SHA1 was found in local known_hosts2 store.\n"); + printf("\tIf you just upgraded from a FreeRDP version before 2.0 this is expected.\n"); + printf("\tThe hashing algorithm has been upgraded from SHA1 to SHA256.\n"); + printf("\tAll manually accepted certificates must be reconfirmed!\n"); + printf("\n"); + } + printf("The above X.509 certificate does not match the certificate used for previous " + "connections.\n" + "This may indicate that the certificate has been tampered with.\n" + "Please contact the administrator of the RDP server and clarify.\n"); + return client_cli_accept_certificate(instance); +} + +BOOL client_cli_present_gateway_message(freerdp* instance, UINT32 type, BOOL isDisplayMandatory, + BOOL isConsentMandatory, size_t length, + const WCHAR* message) +{ + int answer = 0; + const char* msgType = (type == GATEWAY_MESSAGE_CONSENT) ? "Consent message" : "Service message"; + + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + WINPR_ASSERT(instance->context->settings); + + if (!isDisplayMandatory && !isConsentMandatory) + return TRUE; + + printf("%s:\n", msgType); +#if defined(WIN32) + printf("%.*S\n", (int)length, message); +#else + { + LPSTR msg = ConvertWCharNToUtf8Alloc(message, length / sizeof(WCHAR), NULL); + if (!msg) + { + printf("Failed to convert message!\n"); + return FALSE; + } + printf("%s\n", msg); + free(msg); + } +#endif + + while (isConsentMandatory) + { + printf("I understand and agree to the terms of this policy (Y/N) \n"); + (void)fflush(stdout); + answer = freerdp_interruptible_getc(instance->context, stdin); + + if ((answer == EOF) || feof(stdin)) + { + printf("\nError: Could not read answer from stdin.\n"); + return FALSE; + } + + switch (answer) + { + case 'y': + case 'Y': + answer = freerdp_interruptible_getc(instance->context, stdin); + if (answer == EOF) + return FALSE; + return TRUE; + + case 'n': + case 'N': + (void)freerdp_interruptible_getc(instance->context, stdin); + return FALSE; + + default: + break; + } + + printf("\n"); + } + + return TRUE; +} + +static char* extract_authorization_code(char* url) +{ + WINPR_ASSERT(url); + + for (char* p = strchr(url, '?'); p++ != NULL; p = strchr(p, '&')) + { + if (strncmp(p, "code=", 5) != 0) + continue; + + char* end = NULL; + p += 5; + + end = strchr(p, '&'); + if (end) + *end = '\0'; + + return p; + } + + return NULL; +} + +#if defined(WITH_AAD) +static BOOL client_cli_get_rdsaad_access_token(freerdp* instance, const char* scope, + const char* req_cnf, char** token) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + size_t size = 0; + char* url = NULL; + char* token_request = NULL; + char* redirect_uri = NULL; + size_t redirec_uri_len = 0; + + WINPR_ASSERT(scope); + WINPR_ASSERT(req_cnf); + WINPR_ASSERT(token); + + BOOL rc = FALSE; + *token = NULL; + + const char* client_id = + freerdp_settings_get_string(instance->context->settings, FreeRDP_GatewayAvdClientID); + if (!client_id) + goto cleanup; + + winpr_asprintf(&redirect_uri, &redirec_uri_len, + "ms-appx-web%%3a%%2f%%2fMicrosoft.AAD.BrokerPlugin%%2f%s", client_id); + if (!redirect_uri) + goto cleanup; + + const char* ep = freerdp_utils_aad_get_wellknown_string(instance->context, + AAD_WELLKNOWN_authorization_endpoint); + printf("Browse to: %s?client_id=%s&response_type=" + "code&scope=%s&redirect_uri=%s" + "\n", + ep, client_id, scope, redirect_uri); + printf("Paste redirect URL here: \n"); + + if (freerdp_interruptible_get_line(instance->context, &url, &size, stdin) < 0) + goto cleanup; + + char* code = extract_authorization_code(url); + if (!code) + goto cleanup; + + if (winpr_asprintf(&token_request, &size, + "grant_type=authorization_code&code=%s&client_id=%s&scope=%s&redirect_uri=%" + "s&req_cnf=%s", + code, client_id, scope, redirect_uri, req_cnf) <= 0) + goto cleanup; + + rc = client_common_get_access_token(instance, token_request, token); + +cleanup: + free(redirect_uri); + free(token_request); + free(url); + return rc && (*token != NULL); +} + +static BOOL client_cli_get_avd_access_token(freerdp* instance, char** token) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + size_t size = 0; + char* url = NULL; + char* token_request = NULL; + char* redirect_uri = NULL; + size_t redirec_uri_len = 0; + const char* scope = "https%3A%2F%2Fwww.wvd.microsoft.com%2F.default"; + + WINPR_ASSERT(token); + + BOOL rc = FALSE; + + *token = NULL; + + const char* client_id = + freerdp_settings_get_string(instance->context->settings, FreeRDP_GatewayAvdClientID); + const char* base = freerdp_settings_get_string(instance->context->settings, + FreeRDP_GatewayAzureActiveDirectory); + const BOOL useTenant = + freerdp_settings_get_bool(instance->context->settings, FreeRDP_GatewayAvdUseTenantid); + const char* tenantid = "common"; + if (useTenant) + tenantid = + freerdp_settings_get_string(instance->context->settings, FreeRDP_GatewayAvdAadtenantid); + if (!base || !tenantid || !client_id) + goto cleanup; + + winpr_asprintf(&redirect_uri, &redirec_uri_len, + "https%%3A%%2F%%2F%s%%2F%s%%2Foauth2%%2Fnativeclient", base, tenantid); + if (!redirect_uri) + goto cleanup; + + const char* ep = freerdp_utils_aad_get_wellknown_string(instance->context, + AAD_WELLKNOWN_authorization_endpoint); + printf("Browse to: %s?client_id=%s&response_type=" + "code&scope=%s&redirect_uri=%s" + "\n", + ep, client_id, scope, redirect_uri); + printf("Paste redirect URL here: \n"); + + if (freerdp_interruptible_get_line(instance->context, &url, &size, stdin) < 0) + goto cleanup; + + char* code = extract_authorization_code(url); + if (!code) + goto cleanup; + + if (winpr_asprintf( + &token_request, &size, + "grant_type=authorization_code&code=%s&client_id=%s&scope=%s&redirect_uri=%s", code, + client_id, scope, redirect_uri) <= 0) + goto cleanup; + + rc = client_common_get_access_token(instance, token_request, token); + +cleanup: + free(redirect_uri); + free(token_request); + free(url); + return rc && (*token != NULL); +} +#endif + +BOOL client_cli_get_access_token(freerdp* instance, AccessTokenType tokenType, char** token, + size_t count, ...) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(token); + +#if !defined(WITH_AAD) + WLog_ERR(TAG, "Build does not support AAD authentication"); + return FALSE; +#else + switch (tokenType) + { + case ACCESS_TOKEN_TYPE_AAD: + { + if (count < 2) + { + WLog_ERR(TAG, + "ACCESS_TOKEN_TYPE_AAD expected 2 additional arguments, but got %" PRIuz + ", aborting", + count); + return FALSE; + } + else if (count > 2) + WLog_WARN(TAG, + "ACCESS_TOKEN_TYPE_AAD expected 2 additional arguments, but got %" PRIuz + ", ignoring", + count); + va_list ap = { 0 }; + va_start(ap, count); + const char* scope = va_arg(ap, const char*); + const char* req_cnf = va_arg(ap, const char*); + const BOOL rc = client_cli_get_rdsaad_access_token(instance, scope, req_cnf, token); + va_end(ap); + return rc; + } + case ACCESS_TOKEN_TYPE_AVD: + if (count != 0) + WLog_WARN(TAG, + "ACCESS_TOKEN_TYPE_AVD expected 0 additional arguments, but got %" PRIuz + ", ignoring", + count); + return client_cli_get_avd_access_token(instance, token); + default: + WLog_ERR(TAG, "Unexpected value for AccessTokenType [%" PRIuz "], aborting", tokenType); + return FALSE; + } +#endif +} + +BOOL client_common_get_access_token(freerdp* instance, const char* request, char** token) +{ +#ifdef WITH_AAD + WINPR_ASSERT(request); + WINPR_ASSERT(token); + + BOOL ret = FALSE; + long resp_code = 0; + BYTE* response = NULL; + size_t response_length = 0; + + wLog* log = WLog_Get(TAG); + + const char* token_ep = + freerdp_utils_aad_get_wellknown_string(instance->context, AAD_WELLKNOWN_token_endpoint); + if (!freerdp_http_request(token_ep, request, &resp_code, &response, &response_length)) + { + WLog_ERR(TAG, "access token request failed"); + return FALSE; + } + + if (resp_code != HTTP_STATUS_OK) + { + char buffer[64] = { 0 }; + + WLog_Print(log, WLOG_ERROR, + "Server unwilling to provide access token; returned status code %s", + freerdp_http_status_string_format(resp_code, buffer, sizeof(buffer))); + if (response_length > 0) + WLog_Print(log, WLOG_ERROR, "[status message] %s", response); + goto cleanup; + } + + *token = freerdp_utils_aad_get_access_token(log, (const char*)response, response_length); + if (*token) + ret = TRUE; + +cleanup: + free(response); + return ret; +#else + return FALSE; +#endif +} + +SSIZE_T client_common_retry_dialog(freerdp* instance, const char* what, size_t current, + void* userarg) +{ + WINPR_UNUSED(instance); + WINPR_ASSERT(instance->context); + WINPR_UNUSED(userarg); + WINPR_ASSERT(instance); + WINPR_ASSERT(what); + + if ((strcmp(what, "arm-transport") != 0) && (strcmp(what, "connection") != 0)) + { + WLog_ERR(TAG, "Unknown module %s, aborting", what); + return -1; + } + + if (current == 0) + { + if (strcmp(what, "arm-transport") == 0) + WLog_INFO(TAG, "[%s] Starting your VM. It may take up to 5 minutes", what); + } + + const rdpSettings* settings = instance->context->settings; + const BOOL enabled = freerdp_settings_get_bool(settings, FreeRDP_AutoReconnectionEnabled); + if (!enabled) + { + WLog_WARN(TAG, "Automatic reconnection disabled, terminating. Try to connect again later"); + return -1; + } + + const size_t max = freerdp_settings_get_uint32(settings, FreeRDP_AutoReconnectMaxRetries); + const size_t delay = freerdp_settings_get_uint32(settings, FreeRDP_TcpConnectTimeout); + if (current >= max) + { + WLog_ERR(TAG, + "[%s] retries exceeded. Your VM failed to start. Try again later or contact your " + "tech support for help if this keeps happening.", + what); + return -1; + } + + WLog_INFO(TAG, "[%s] retry %" PRIuz "/%" PRIuz ", delaying %" PRIuz "ms before next attempt", + what, current, max, delay); + return WINPR_ASSERTING_INT_CAST(SSIZE_T, delay); +} + +BOOL client_auto_reconnect(freerdp* instance) +{ + return client_auto_reconnect_ex(instance, NULL); +} + +BOOL client_auto_reconnect_ex(freerdp* instance, BOOL (*window_events)(freerdp* instance)) +{ + BOOL retry = TRUE; + UINT32 error = 0; + UINT32 numRetries = 0; + rdpSettings* settings = NULL; + + if (!instance) + return FALSE; + + WINPR_ASSERT(instance->context); + + settings = instance->context->settings; + WINPR_ASSERT(settings); + + const UINT32 maxRetries = + freerdp_settings_get_uint32(settings, FreeRDP_AutoReconnectMaxRetries); + + /* Only auto reconnect on network disconnects. */ + error = freerdp_error_info(instance); + switch (error) + { + case ERRINFO_GRAPHICS_SUBSYSTEM_FAILED: + /* A network disconnect was detected */ + WLog_WARN(TAG, "Disconnected by server hitting a bug or resource limit [%s]", + freerdp_get_error_info_string(error)); + break; + case ERRINFO_SUCCESS: + /* A network disconnect was detected */ + WLog_INFO(TAG, "Network disconnect!"); + break; + default: + return FALSE; + } + + if (!freerdp_settings_get_bool(settings, FreeRDP_AutoReconnectionEnabled)) + { + /* No auto-reconnect - just quit */ + return FALSE; + } + + switch (freerdp_get_last_error(instance->context)) + { + case FREERDP_ERROR_CONNECT_CANCELLED: + WLog_WARN(TAG, "Connection aborted by user"); + return FALSE; + default: + break; + } + + /* Perform an auto-reconnect. */ + while (retry) + { + /* Quit retrying if max retries has been exceeded */ + if ((maxRetries > 0) && (numRetries++ >= maxRetries)) + { + return FALSE; + } + + /* Attempt the next reconnect */ + WLog_INFO(TAG, "Attempting reconnect (%" PRIu32 " of %" PRIu32 ")", numRetries, maxRetries); + + IFCALL(instance->RetryDialog, instance, "connection", numRetries, NULL); + + if (freerdp_reconnect(instance)) + return TRUE; + + switch (freerdp_get_last_error(instance->context)) + { + case FREERDP_ERROR_CONNECT_CANCELLED: + WLog_WARN(TAG, "Autoreconnect aborted by user"); + return FALSE; + default: + break; + } + for (UINT32 x = 0; x < 50; x++) + { + if (!IFCALLRESULT(TRUE, window_events, instance)) + return FALSE; + + Sleep(10); + } + } + + WLog_ERR(TAG, "Maximum reconnect retries exceeded"); + return FALSE; +} + +int freerdp_client_common_stop(rdpContext* context) +{ + rdpClientContext* cctx = (rdpClientContext*)context; + WINPR_ASSERT(cctx); + + freerdp_abort_connect_context(&cctx->context); + + if (cctx->thread) + { + (void)WaitForSingleObject(cctx->thread, INFINITE); + (void)CloseHandle(cctx->thread); + cctx->thread = NULL; + } + + return 0; +} + +#if defined(CHANNEL_ENCOMSP_CLIENT) +BOOL freerdp_client_encomsp_toggle_control(EncomspClientContext* encomsp) +{ + rdpClientContext* cctx = NULL; + BOOL state = 0; + + if (!encomsp) + return FALSE; + + cctx = (rdpClientContext*)encomsp->custom; + + state = cctx->controlToggle; + cctx->controlToggle = !cctx->controlToggle; + return freerdp_client_encomsp_set_control(encomsp, state); +} + +BOOL freerdp_client_encomsp_set_control(EncomspClientContext* encomsp, BOOL control) +{ + ENCOMSP_CHANGE_PARTICIPANT_CONTROL_LEVEL_PDU pdu = { 0 }; + + if (!encomsp) + return FALSE; + + pdu.ParticipantId = encomsp->participantId; + pdu.Flags = ENCOMSP_REQUEST_VIEW; + + if (control) + pdu.Flags |= ENCOMSP_REQUEST_INTERACT; + + encomsp->ChangeParticipantControlLevel(encomsp, &pdu); + + return TRUE; +} + +static UINT +client_encomsp_participant_created(EncomspClientContext* context, + const ENCOMSP_PARTICIPANT_CREATED_PDU* participantCreated) +{ + rdpClientContext* cctx = NULL; + rdpSettings* settings = NULL; + BOOL request = 0; + + if (!context || !context->custom || !participantCreated) + return ERROR_INVALID_PARAMETER; + + cctx = (rdpClientContext*)context->custom; + WINPR_ASSERT(cctx); + + settings = cctx->context.settings; + WINPR_ASSERT(settings); + + if (participantCreated->Flags & ENCOMSP_IS_PARTICIPANT) + context->participantId = participantCreated->ParticipantId; + + request = freerdp_settings_get_bool(settings, FreeRDP_RemoteAssistanceRequestControl); + if (request && (participantCreated->Flags & ENCOMSP_MAY_VIEW) && + !(participantCreated->Flags & ENCOMSP_MAY_INTERACT)) + { + if (!freerdp_client_encomsp_set_control(context, TRUE)) + return ERROR_INTERNAL_ERROR; + + /* if auto-request-control setting is enabled then only request control once upon connect, + * otherwise it will auto request control again every time server turns off control which + * is a bit annoying */ + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteAssistanceRequestControl, FALSE)) + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} + +static void client_encomsp_init(rdpClientContext* cctx, EncomspClientContext* encomsp) +{ + cctx->encomsp = encomsp; + encomsp->custom = (void*)cctx; + encomsp->ParticipantCreated = client_encomsp_participant_created; +} + +static void client_encomsp_uninit(rdpClientContext* cctx, EncomspClientContext* encomsp) +{ + if (encomsp) + { + encomsp->custom = NULL; + encomsp->ParticipantCreated = NULL; + } + + if (cctx) + cctx->encomsp = NULL; +} +#endif + +void freerdp_client_OnChannelConnectedEventHandler(void* context, + const ChannelConnectedEventArgs* e) +{ + rdpClientContext* cctx = (rdpClientContext*)context; + + WINPR_ASSERT(cctx); + WINPR_ASSERT(e); + + if (0) + { + } +#if defined(CHANNEL_AINPUT_CLIENT) + else if (strcmp(e->name, AINPUT_DVC_CHANNEL_NAME) == 0) + cctx->ainput = (AInputClientContext*)e->pInterface; +#endif +#if defined(CHANNEL_RDPEI_CLIENT) + else if (strcmp(e->name, RDPEI_DVC_CHANNEL_NAME) == 0) + { + cctx->rdpei = (RdpeiClientContext*)e->pInterface; + } +#endif +#if defined(CHANNEL_RDPGFX_CLIENT) + else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) + { + gdi_graphics_pipeline_init(cctx->context.gdi, (RdpgfxClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_GEOMETRY_CLIENT) + else if (strcmp(e->name, GEOMETRY_DVC_CHANNEL_NAME) == 0) + { + gdi_video_geometry_init(cctx->context.gdi, (GeometryClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_VIDEO_CLIENT) + else if (strcmp(e->name, VIDEO_CONTROL_DVC_CHANNEL_NAME) == 0) + { + gdi_video_control_init(cctx->context.gdi, (VideoClientContext*)e->pInterface); + } + else if (strcmp(e->name, VIDEO_DATA_DVC_CHANNEL_NAME) == 0) + { + gdi_video_data_init(cctx->context.gdi, (VideoClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_ENCOMSP_CLIENT) + else if (strcmp(e->name, ENCOMSP_SVC_CHANNEL_NAME) == 0) + { + client_encomsp_init(cctx, (EncomspClientContext*)e->pInterface); + } +#endif +} + +void freerdp_client_OnChannelDisconnectedEventHandler(void* context, + const ChannelDisconnectedEventArgs* e) +{ + rdpClientContext* cctx = (rdpClientContext*)context; + + WINPR_ASSERT(cctx); + WINPR_ASSERT(e); + + if (0) + { + } +#if defined(CHANNEL_AINPUT_CLIENT) + else if (strcmp(e->name, AINPUT_DVC_CHANNEL_NAME) == 0) + cctx->ainput = NULL; +#endif +#if defined(CHANNEL_RDPEI_CLIENT) + else if (strcmp(e->name, RDPEI_DVC_CHANNEL_NAME) == 0) + { + cctx->rdpei = NULL; + } +#endif +#if defined(CHANNEL_RDPGFX_CLIENT) + else if (strcmp(e->name, RDPGFX_DVC_CHANNEL_NAME) == 0) + { + gdi_graphics_pipeline_uninit(cctx->context.gdi, (RdpgfxClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_GEOMETRY_CLIENT) + else if (strcmp(e->name, GEOMETRY_DVC_CHANNEL_NAME) == 0) + { + gdi_video_geometry_uninit(cctx->context.gdi, (GeometryClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_VIDEO_CLIENT) + else if (strcmp(e->name, VIDEO_CONTROL_DVC_CHANNEL_NAME) == 0) + { + gdi_video_control_uninit(cctx->context.gdi, (VideoClientContext*)e->pInterface); + } + else if (strcmp(e->name, VIDEO_DATA_DVC_CHANNEL_NAME) == 0) + { + gdi_video_data_uninit(cctx->context.gdi, (VideoClientContext*)e->pInterface); + } +#endif +#if defined(CHANNEL_ENCOMSP_CLIENT) + else if (strcmp(e->name, ENCOMSP_SVC_CHANNEL_NAME) == 0) + { + client_encomsp_uninit(cctx, (EncomspClientContext*)e->pInterface); + } +#endif +} + +BOOL freerdp_client_send_wheel_event(rdpClientContext* cctx, UINT16 mflags) +{ + BOOL handled = FALSE; + + WINPR_ASSERT(cctx); + +#if defined(CHANNEL_AINPUT_CLIENT) + if (cctx->ainput) + { + UINT rc = 0; + UINT64 flags = 0; + INT32 x = 0; + INT32 y = 0; + INT32 value = mflags & 0xFF; + + if (mflags & PTR_FLAGS_WHEEL_NEGATIVE) + value = -1 * (0x100 - value); + + /* We have discrete steps, scale this so we can also support high + * resolution wheels. */ + value *= 0x10000; + + if (mflags & PTR_FLAGS_WHEEL) + { + flags |= AINPUT_FLAGS_WHEEL; + y = value; + } + + if (mflags & PTR_FLAGS_HWHEEL) + { + flags |= AINPUT_FLAGS_WHEEL; + x = value; + } + + WINPR_ASSERT(cctx->ainput->AInputSendInputEvent); + rc = cctx->ainput->AInputSendInputEvent(cctx->ainput, flags, x, y); + if (rc == CHANNEL_RC_OK) + handled = TRUE; + } +#endif + + if (!handled) + freerdp_input_send_mouse_event(cctx->context.input, mflags, 0, 0); + + return TRUE; +} + +#if defined(CHANNEL_AINPUT_CLIENT) +static INLINE BOOL ainput_send_diff_event(rdpClientContext* cctx, UINT64 flags, INT32 x, INT32 y) +{ + UINT rc = 0; + + WINPR_ASSERT(cctx); + WINPR_ASSERT(cctx->ainput); + WINPR_ASSERT(cctx->ainput->AInputSendInputEvent); + + rc = cctx->ainput->AInputSendInputEvent(cctx->ainput, flags, x, y); + + return rc == CHANNEL_RC_OK; +} +#endif + +BOOL freerdp_client_send_button_event(rdpClientContext* cctx, BOOL relative, UINT16 mflags, INT32 x, + INT32 y) +{ + BOOL handled = FALSE; + + WINPR_ASSERT(cctx); + + const BOOL haveRelative = + freerdp_settings_get_bool(cctx->context.settings, FreeRDP_HasRelativeMouseEvent); + if (relative && haveRelative) + { + return freerdp_input_send_rel_mouse_event(cctx->context.input, mflags, + WINPR_ASSERTING_INT_CAST(int16_t, x), + WINPR_ASSERTING_INT_CAST(int16_t, y)); + } + +#if defined(CHANNEL_AINPUT_CLIENT) + if (cctx->ainput) + { + UINT64 flags = 0; + + if (cctx->mouse_grabbed && freerdp_client_use_relative_mouse_events(cctx)) + flags |= AINPUT_FLAGS_HAVE_REL; + + if (relative) + flags |= AINPUT_FLAGS_REL; + + if (mflags & PTR_FLAGS_DOWN) + flags |= AINPUT_FLAGS_DOWN; + if (mflags & PTR_FLAGS_BUTTON1) + flags |= AINPUT_FLAGS_BUTTON1; + if (mflags & PTR_FLAGS_BUTTON2) + flags |= AINPUT_FLAGS_BUTTON2; + if (mflags & PTR_FLAGS_BUTTON3) + flags |= AINPUT_FLAGS_BUTTON3; + if (mflags & PTR_FLAGS_MOVE) + flags |= AINPUT_FLAGS_MOVE; + handled = ainput_send_diff_event(cctx, flags, x, y); + } +#endif + + if (!handled) + { + if (relative) + { + cctx->lastX += x; + cctx->lastY += y; + WLog_WARN(TAG, "Relative mouse input channel not available, sending absolute!"); + } + else + { + cctx->lastX = x; + cctx->lastY = y; + } + freerdp_input_send_mouse_event(cctx->context.input, mflags, (UINT16)cctx->lastX, + (UINT16)cctx->lastY); + } + return TRUE; +} + +BOOL freerdp_client_send_extended_button_event(rdpClientContext* cctx, BOOL relative, UINT16 mflags, + INT32 x, INT32 y) +{ + BOOL handled = FALSE; + WINPR_ASSERT(cctx); + + const BOOL haveRelative = + freerdp_settings_get_bool(cctx->context.settings, FreeRDP_HasRelativeMouseEvent); + if (relative && haveRelative) + { + return freerdp_input_send_rel_mouse_event(cctx->context.input, mflags, + WINPR_ASSERTING_INT_CAST(int16_t, x), + WINPR_ASSERTING_INT_CAST(int16_t, y)); + } + +#if defined(CHANNEL_AINPUT_CLIENT) + if (cctx->ainput) + { + UINT64 flags = 0; + + if (relative) + flags |= AINPUT_FLAGS_REL; + if (mflags & PTR_XFLAGS_DOWN) + flags |= AINPUT_FLAGS_DOWN; + if (mflags & PTR_XFLAGS_BUTTON1) + flags |= AINPUT_XFLAGS_BUTTON1; + if (mflags & PTR_XFLAGS_BUTTON2) + flags |= AINPUT_XFLAGS_BUTTON2; + + handled = ainput_send_diff_event(cctx, flags, x, y); + } +#endif + + if (!handled) + { + if (relative) + { + cctx->lastX += x; + cctx->lastY += y; + WLog_WARN(TAG, "Relative mouse input channel not available, sending absolute!"); + } + else + { + cctx->lastX = x; + cctx->lastY = y; + } + freerdp_input_send_extended_mouse_event(cctx->context.input, mflags, (UINT16)cctx->lastX, + (UINT16)cctx->lastY); + } + + return TRUE; +} + +static BOOL freerdp_handle_touch_up(rdpClientContext* cctx, const FreeRDP_TouchContact* contact) +{ + WINPR_ASSERT(cctx); + WINPR_ASSERT(contact); + +#if defined(CHANNEL_RDPEI_CLIENT) + RdpeiClientContext* rdpei = cctx->rdpei; + + if (!rdpei) + { + UINT16 flags = 0; + flags |= PTR_FLAGS_BUTTON1; + + WINPR_ASSERT(contact->x <= UINT16_MAX); + WINPR_ASSERT(contact->y <= UINT16_MAX); + return freerdp_client_send_button_event(cctx, FALSE, flags, contact->x, contact->y); + } + else + { + int contactId = 0; + + if (rdpei->TouchRawEvent) + { + const UINT32 flags = RDPINPUT_CONTACT_FLAG_UP; + const UINT32 contactFlags = ((contact->flags & FREERDP_TOUCH_HAS_PRESSURE) != 0) + ? CONTACT_DATA_PRESSURE_PRESENT + : 0; + // Ensure contact position is unchanged from "engaged" to "out of range" state + rdpei->TouchRawEvent(rdpei, contact->id, contact->x, contact->y, &contactId, + RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT, + contactFlags, contact->pressure); + rdpei->TouchRawEvent(rdpei, contact->id, contact->x, contact->y, &contactId, flags, + contactFlags, contact->pressure); + } + else + { + WINPR_ASSERT(rdpei->TouchEnd); + rdpei->TouchEnd(rdpei, contact->id, contact->x, contact->y, &contactId); + } + } +#else + WLog_WARN(TAG, "Touch event detected but RDPEI support not compiled in. Recompile with " + "-DWITH_CHANNELS=ON"); +#endif + + return TRUE; +} + +static BOOL freerdp_handle_touch_down(rdpClientContext* cctx, const FreeRDP_TouchContact* contact) +{ + WINPR_ASSERT(cctx); + WINPR_ASSERT(contact); + +#if defined(CHANNEL_RDPEI_CLIENT) + RdpeiClientContext* rdpei = cctx->rdpei; + + // Emulate mouse click if touch is not possible, like in login screen + if (!rdpei) + { + UINT16 flags = 0; + flags |= PTR_FLAGS_DOWN; + flags |= PTR_FLAGS_MOVE; + flags |= PTR_FLAGS_BUTTON1; + + WINPR_ASSERT(contact->x <= UINT16_MAX); + WINPR_ASSERT(contact->y <= UINT16_MAX); + return freerdp_client_send_button_event(cctx, FALSE, flags, contact->x, contact->y); + } + else + { + int contactId = 0; + + if (rdpei->TouchRawEvent) + { + const UINT32 flags = RDPINPUT_CONTACT_FLAG_DOWN | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT; + const UINT32 contactFlags = ((contact->flags & FREERDP_TOUCH_HAS_PRESSURE) != 0) + ? CONTACT_DATA_PRESSURE_PRESENT + : 0; + rdpei->TouchRawEvent(rdpei, contact->id, contact->x, contact->y, &contactId, flags, + contactFlags, contact->pressure); + } + else + { + WINPR_ASSERT(rdpei->TouchBegin); + rdpei->TouchBegin(rdpei, contact->id, contact->x, contact->y, &contactId); + } + } +#else + WLog_WARN(TAG, "Touch event detected but RDPEI support not compiled in. Recompile with " + "-DWITH_CHANNELS=ON"); +#endif + + return TRUE; +} + +static BOOL freerdp_handle_touch_motion(rdpClientContext* cctx, const FreeRDP_TouchContact* contact) +{ + WINPR_ASSERT(cctx); + WINPR_ASSERT(contact); + +#if defined(CHANNEL_RDPEI_CLIENT) + RdpeiClientContext* rdpei = cctx->rdpei; + + if (!rdpei) + { + UINT16 flags = 0; + flags |= PTR_FLAGS_MOVE; + + WINPR_ASSERT(contact->x <= UINT16_MAX); + WINPR_ASSERT(contact->y <= UINT16_MAX); + return freerdp_client_send_button_event(cctx, FALSE, flags, contact->x, contact->y); + } + else + { + int contactId = 0; + + if (rdpei->TouchRawEvent) + { + const UINT32 flags = RDPINPUT_CONTACT_FLAG_UPDATE | RDPINPUT_CONTACT_FLAG_INRANGE | + RDPINPUT_CONTACT_FLAG_INCONTACT; + const UINT32 contactFlags = ((contact->flags & FREERDP_TOUCH_HAS_PRESSURE) != 0) + ? CONTACT_DATA_PRESSURE_PRESENT + : 0; + rdpei->TouchRawEvent(rdpei, contact->id, contact->x, contact->y, &contactId, flags, + contactFlags, contact->pressure); + } + else + { + WINPR_ASSERT(rdpei->TouchUpdate); + rdpei->TouchUpdate(rdpei, contact->id, contact->x, contact->y, &contactId); + } + } +#else + WLog_WARN(TAG, "Touch event detected but RDPEI support not compiled in. Recompile with " + "-DWITH_CHANNELS=ON"); +#endif + + return TRUE; +} + +static BOOL freerdp_client_touch_update(rdpClientContext* cctx, UINT32 flags, INT32 touchId, + UINT32 pressure, INT32 x, INT32 y, + FreeRDP_TouchContact* pcontact) +{ + WINPR_ASSERT(cctx); + WINPR_ASSERT(pcontact); + + for (size_t i = 0; i < ARRAYSIZE(cctx->contacts); i++) + { + FreeRDP_TouchContact* contact = &cctx->contacts[i]; + + const BOOL newcontact = ((contact->id == 0) && ((flags & FREERDP_TOUCH_DOWN) != 0)); + if (newcontact || (contact->id == touchId)) + { + contact->id = touchId; + contact->flags = flags; + contact->pressure = pressure; + contact->x = x; + contact->y = y; + + *pcontact = *contact; + + const BOOL resetcontact = (flags & FREERDP_TOUCH_UP) != 0; + if (resetcontact) + { + FreeRDP_TouchContact empty = { 0 }; + *contact = empty; + } + return TRUE; + } + } + + return FALSE; +} + +BOOL freerdp_client_handle_touch(rdpClientContext* cctx, UINT32 flags, INT32 finger, + UINT32 pressure, INT32 x, INT32 y) +{ + const UINT32 mask = FREERDP_TOUCH_DOWN | FREERDP_TOUCH_UP | FREERDP_TOUCH_MOTION; + WINPR_ASSERT(cctx); + + FreeRDP_TouchContact contact = { 0 }; + + if (!freerdp_client_touch_update(cctx, flags, finger, pressure, x, y, &contact)) + return FALSE; + + switch (flags & mask) + { + case FREERDP_TOUCH_DOWN: + return freerdp_handle_touch_down(cctx, &contact); + case FREERDP_TOUCH_UP: + return freerdp_handle_touch_up(cctx, &contact); + case FREERDP_TOUCH_MOTION: + return freerdp_handle_touch_motion(cctx, &contact); + default: + WLog_WARN(TAG, "Unhandled FreeRDPTouchEventType %d, ignoring", flags); + return FALSE; + } +} + +BOOL freerdp_client_load_channels(freerdp* instance) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->context); + + if (!freerdp_client_load_addins(instance->context->channels, instance->context->settings)) + { + WLog_ERR(TAG, "Failed to load addins [%08" PRIx32 "]", GetLastError()); + return FALSE; + } + return TRUE; +} + +int client_cli_logon_error_info(freerdp* instance, UINT32 data, UINT32 type) +{ + const char* str_data = freerdp_get_logon_error_info_data(data); + const char* str_type = freerdp_get_logon_error_info_type(type); + + if (!instance || !instance->context) + return -1; + + WLog_INFO(TAG, "Logon Error Info %s [%s]", str_data, str_type); + return 1; +} + +static FreeRDP_PenDevice* freerdp_client_get_pen(rdpClientContext* cctx, INT32 deviceid, + size_t* pos) +{ + WINPR_ASSERT(cctx); + + for (size_t i = 0; i < ARRAYSIZE(cctx->pens); i++) + { + FreeRDP_PenDevice* pen = &cctx->pens[i]; + if (deviceid == pen->deviceid) + { + if (pos) + *pos = i; + return pen; + } + } + return NULL; +} + +static BOOL freerdp_client_register_pen(rdpClientContext* cctx, UINT32 flags, INT32 deviceid, + double pressure) +{ + static const INT32 null_deviceid = 0; + + WINPR_ASSERT(cctx); + WINPR_ASSERT((flags & FREERDP_PEN_REGISTER) != 0); + if (freerdp_client_is_pen(cctx, deviceid)) + { + WLog_WARN(TAG, "trying to double register pen device %" PRId32, deviceid); + return FALSE; + } + + size_t pos = 0; + FreeRDP_PenDevice* pen = freerdp_client_get_pen(cctx, null_deviceid, &pos); + if (pen) + { + const FreeRDP_PenDevice empty = { 0 }; + *pen = empty; + + pen->deviceid = deviceid; + pen->max_pressure = pressure; + pen->flags = flags; + + WLog_DBG(TAG, "registered pen at index %" PRIuz, pos); + return TRUE; + } + + WLog_WARN(TAG, "No free slot for an additional pen device, skipping"); + return TRUE; +} + +BOOL freerdp_client_handle_pen(rdpClientContext* cctx, UINT32 flags, INT32 deviceid, ...) +{ + if ((flags & FREERDP_PEN_REGISTER) != 0) + { + va_list args; + + va_start(args, deviceid); + double pressure = va_arg(args, double); + va_end(args); + return freerdp_client_register_pen(cctx, flags, deviceid, pressure); + } + size_t pos = 0; + FreeRDP_PenDevice* pen = freerdp_client_get_pen(cctx, deviceid, &pos); + if (!pen) + { + WLog_WARN(TAG, "unregistered pen device %" PRId32 " event 0x%08" PRIx32, deviceid, flags); + return FALSE; + } + + UINT32 fieldFlags = RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT; + UINT32 penFlags = + ((pen->flags & FREERDP_PEN_IS_INVERTED) != 0) ? RDPINPUT_PEN_FLAG_INVERTED : 0; + + RdpeiClientContext* rdpei = cctx->rdpei; + WINPR_ASSERT(rdpei); + + UINT32 normalizedpressure = 1024; + INT32 x = 0; + INT32 y = 0; + UINT16 rotation = 0; + INT16 tiltX = 0; + INT16 tiltY = 0; + va_list args; + va_start(args, deviceid); + + x = va_arg(args, INT32); + y = va_arg(args, INT32); + if ((flags & FREERDP_PEN_HAS_PRESSURE) != 0) + { + const double pressure = va_arg(args, double); + const double np = (pressure * 1024.0) / pen->max_pressure; + normalizedpressure = (UINT32)lround(np); + WLog_DBG(TAG, "pen pressure %lf -> %" PRIu32, pressure, normalizedpressure); + fieldFlags |= RDPINPUT_PEN_CONTACT_PRESSURE_PRESENT; + } + if ((flags & FREERDP_PEN_HAS_ROTATION) != 0) + { + const unsigned arg = va_arg(args, unsigned); + rotation = WINPR_ASSERTING_INT_CAST(UINT16, arg); + fieldFlags |= RDPINPUT_PEN_CONTACT_ROTATION_PRESENT; + } + if ((flags & FREERDP_PEN_HAS_TILTX) != 0) + { + const int arg = va_arg(args, int); + tiltX = WINPR_ASSERTING_INT_CAST(INT16, arg); + fieldFlags |= RDPINPUT_PEN_CONTACT_TILTX_PRESENT; + } + if ((flags & FREERDP_PEN_HAS_TILTY) != 0) + { + const int arg = va_arg(args, int); + tiltY = WINPR_ASSERTING_INT_CAST(INT16, arg); + fieldFlags |= RDPINPUT_PEN_CONTACT_TILTY_PRESENT; + } + va_end(args); + + if ((flags & FREERDP_PEN_PRESS) != 0) + { + // Ensure that only one button is pressed + if (pen->pressed) + flags = FREERDP_PEN_MOTION | + (flags & (UINT32) ~(FREERDP_PEN_PRESS | FREERDP_PEN_BARREL_PRESSED)); + else if ((flags & FREERDP_PEN_BARREL_PRESSED) != 0) + pen->flags |= FREERDP_PEN_BARREL_PRESSED; + } + else if ((flags & FREERDP_PEN_RELEASE) != 0) + { + if (!pen->pressed || + ((flags & FREERDP_PEN_BARREL_PRESSED) ^ (pen->flags & FREERDP_PEN_BARREL_PRESSED))) + flags = FREERDP_PEN_MOTION | + (flags & (UINT32) ~(FREERDP_PEN_RELEASE | FREERDP_PEN_BARREL_PRESSED)); + else + pen->flags &= (UINT32)~FREERDP_PEN_BARREL_PRESSED; + } + + flags |= pen->flags; + if ((flags & FREERDP_PEN_ERASER_PRESSED) != 0) + penFlags |= RDPINPUT_PEN_FLAG_ERASER_PRESSED; + if ((flags & FREERDP_PEN_BARREL_PRESSED) != 0) + penFlags |= RDPINPUT_PEN_FLAG_BARREL_PRESSED; + + pen->last_x = x; + pen->last_y = y; + if ((flags & FREERDP_PEN_PRESS) != 0) + { + WLog_DBG(TAG, "Pen press %" PRId32, deviceid); + pen->hovering = FALSE; + pen->pressed = TRUE; + + WINPR_ASSERT(rdpei->PenBegin); + const UINT rc = rdpei->PenBegin(rdpei, deviceid, fieldFlags, x, y, penFlags, + normalizedpressure, rotation, tiltX, tiltY); + return rc == CHANNEL_RC_OK; + } + else if ((flags & FREERDP_PEN_MOTION) != 0) + { + UINT rc = ERROR_INTERNAL_ERROR; + if (pen->pressed) + { + WLog_DBG(TAG, "Pen update %" PRId32, deviceid); + + // TODO: what if no rotation is supported but tilt is? + WINPR_ASSERT(rdpei->PenUpdate); + rc = rdpei->PenUpdate(rdpei, deviceid, fieldFlags, x, y, penFlags, normalizedpressure, + rotation, tiltX, tiltY); + } + else if (pen->hovering) + { + WLog_DBG(TAG, "Pen hover update %" PRId32, deviceid); + + WINPR_ASSERT(rdpei->PenHoverUpdate); + rc = rdpei->PenHoverUpdate(rdpei, deviceid, RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT, x, y, + penFlags, normalizedpressure, rotation, tiltX, tiltY); + } + else + { + WLog_DBG(TAG, "Pen hover begin %" PRId32, deviceid); + pen->hovering = TRUE; + + WINPR_ASSERT(rdpei->PenHoverBegin); + rc = rdpei->PenHoverBegin(rdpei, deviceid, RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT, x, y, + penFlags, normalizedpressure, rotation, tiltX, tiltY); + } + return rc == CHANNEL_RC_OK; + } + else if ((flags & FREERDP_PEN_RELEASE) != 0) + { + WLog_DBG(TAG, "Pen release %" PRId32, deviceid); + pen->pressed = FALSE; + pen->hovering = TRUE; + + WINPR_ASSERT(rdpei->PenUpdate); + const UINT rc = rdpei->PenUpdate(rdpei, deviceid, fieldFlags, x, y, penFlags, + normalizedpressure, rotation, tiltX, tiltY); + if (rc != CHANNEL_RC_OK) + return FALSE; + WINPR_ASSERT(rdpei->PenEnd); + const UINT re = rdpei->PenEnd(rdpei, deviceid, RDPINPUT_PEN_CONTACT_PENFLAGS_PRESENT, x, y, + penFlags, normalizedpressure, rotation, tiltX, tiltY); + return re == CHANNEL_RC_OK; + } + + WLog_WARN(TAG, "Invalid pen %" PRId32 " flags 0x%08" PRIx32, deviceid, flags); + return FALSE; +} + +BOOL freerdp_client_pen_cancel_all(rdpClientContext* cctx) +{ + WINPR_ASSERT(cctx); + + RdpeiClientContext* rdpei = cctx->rdpei; + + if (!rdpei) + return FALSE; + + for (size_t i = 0; i < ARRAYSIZE(cctx->pens); i++) + { + FreeRDP_PenDevice* pen = &cctx->pens[i]; + if (pen->hovering) + { + WLog_DBG(TAG, "unhover pen %" PRId32, pen->deviceid); + pen->hovering = FALSE; + rdpei->PenHoverCancel(rdpei, pen->deviceid, 0, pen->last_x, pen->last_y); + } + } + return TRUE; +} + +BOOL freerdp_client_is_pen(rdpClientContext* cctx, INT32 deviceid) +{ + WINPR_ASSERT(cctx); + + if (deviceid == 0) + return FALSE; + + for (size_t x = 0; x < ARRAYSIZE(cctx->pens); x++) + { + const FreeRDP_PenDevice* pen = &cctx->pens[x]; + if (pen->deviceid == deviceid) + return TRUE; + } + + return FALSE; +} + +BOOL freerdp_client_use_relative_mouse_events(rdpClientContext* ccontext) +{ + WINPR_ASSERT(ccontext); + + const rdpSettings* settings = ccontext->context.settings; + const BOOL useRelative = freerdp_settings_get_bool(settings, FreeRDP_MouseUseRelativeMove); + const BOOL haveRelative = freerdp_settings_get_bool(settings, FreeRDP_HasRelativeMouseEvent); + BOOL ainput = FALSE; +#if defined(CHANNEL_AINPUT_CLIENT) + ainput = ccontext->ainput != NULL; +#endif + + return useRelative && (haveRelative || ainput); +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/common/client_cliprdr_file.c b/local-test-freerdp-full-01/afc-freerdp/client/common/client_cliprdr_file.c new file mode 100644 index 0000000000000000000000000000000000000000..6509cc712f4f9a133fd47cfb92e4f6c49dbf8ecd --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/common/client_cliprdr_file.c @@ -0,0 +1,2566 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * X11 Clipboard Redirection + * + * Copyright 2010-2011 Vic Lee + * Copyright 2015 Thincast Technologies GmbH + * Copyright 2015 DI (FH) Martin Haimberger + * Copyright 2023 Armin Novak + * Copyright 2023 Pascal Nowack + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#ifdef WITH_FUSE +#define FUSE_USE_VERSION 30 +#include +#endif + +#if defined(WITH_FUSE) +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#define MAX_CLIP_DATA_DIR_LEN 10 +#define NO_CLIP_DATA_ID (UINT64_C(1) << 32) +#define WIN32_FILETIME_TO_UNIX_EPOCH INT64_C(11644473600) + +#ifdef WITH_DEBUG_CLIPRDR +#define DEBUG_CLIPRDR(log, ...) WLog_Print(log, WLOG_DEBUG, __VA_ARGS__) +#else +#define DEBUG_CLIPRDR(log, ...) \ + do \ + { \ + } while (0) +#endif + +#if defined(WITH_FUSE) +typedef enum eFuseLowlevelOperationType +{ + FUSE_LL_OPERATION_NONE, + FUSE_LL_OPERATION_LOOKUP, + FUSE_LL_OPERATION_GETATTR, + FUSE_LL_OPERATION_READ, +} FuseLowlevelOperationType; + +typedef struct sCliprdrFuseFile CliprdrFuseFile; + +struct sCliprdrFuseFile +{ + CliprdrFuseFile* parent; + wArrayList* children; + + char* filename; + char* filename_with_root; + UINT32 list_idx; + fuse_ino_t ino; + + BOOL is_directory; + BOOL is_readonly; + + BOOL has_size; + UINT64 size; + + BOOL has_last_write_time; + INT64 last_write_time_unix; + + BOOL has_clip_data_id; + UINT32 clip_data_id; +}; + +typedef struct +{ + CliprdrFileContext* file_context; + + CliprdrFuseFile* clip_data_dir; + + BOOL has_clip_data_id; + UINT32 clip_data_id; +} CliprdrFuseClipDataEntry; + +typedef struct +{ + CliprdrFileContext* file_context; + + wArrayList* fuse_files; + + BOOL all_files; + BOOL has_clip_data_id; + UINT32 clip_data_id; +} FuseFileClearContext; + +typedef struct +{ + FuseLowlevelOperationType operation_type; + CliprdrFuseFile* fuse_file; + fuse_req_t fuse_req; + UINT32 stream_id; +} CliprdrFuseRequest; + +typedef struct +{ + CliprdrFuseFile* parent; + char* parent_path; +} CliprdrFuseFindParentContext; +#endif + +typedef struct +{ + char* name; + FILE* fp; + INT64 size; + CliprdrFileContext* context; +} CliprdrLocalFile; + +typedef struct +{ + UINT32 lockId; + BOOL locked; + size_t count; + CliprdrLocalFile* files; + CliprdrFileContext* context; +} CliprdrLocalStream; + +struct cliprdr_file_context +{ +#if defined(WITH_FUSE) + /* FUSE related**/ + HANDLE fuse_start_sync; + HANDLE fuse_stop_sync; + HANDLE fuse_thread; + struct fuse_session* fuse_sess; +#if FUSE_USE_VERSION < 30 + struct fuse_chan* ch; +#endif + + wHashTable* inode_table; + wHashTable* clip_data_table; + wHashTable* request_table; + + CliprdrFuseFile* root_dir; + CliprdrFuseClipDataEntry* clip_data_entry_without_id; + UINT32 current_clip_data_id; + + fuse_ino_t next_ino; + UINT32 next_clip_data_id; + UINT32 next_stream_id; +#endif + + /* File clipping */ + BOOL file_formats_registered; + UINT32 file_capability_flags; + + UINT32 local_lock_id; + + wHashTable* local_streams; + wLog* log; + void* clipboard; + CliprdrClientContext* context; + char* path; + char* exposed_path; + BYTE server_data_hash[WINPR_SHA256_DIGEST_LENGTH]; + BYTE client_data_hash[WINPR_SHA256_DIGEST_LENGTH]; +}; + +#if defined(WITH_FUSE) +static void fuse_file_free(void* data) +{ + CliprdrFuseFile* fuse_file = data; + + if (!fuse_file) + return; + + ArrayList_Free(fuse_file->children); + free(fuse_file->filename_with_root); + + free(fuse_file); +} + +static CliprdrFuseFile* fuse_file_new(void) +{ + CliprdrFuseFile* fuse_file = NULL; + + fuse_file = calloc(1, sizeof(CliprdrFuseFile)); + if (!fuse_file) + return NULL; + + fuse_file->children = ArrayList_New(FALSE); + if (!fuse_file->children) + { + free(fuse_file); + return NULL; + } + + return fuse_file; +} + +static void clip_data_entry_free(void* data) +{ + CliprdrFuseClipDataEntry* clip_data_entry = data; + + if (!clip_data_entry) + return; + + if (clip_data_entry->has_clip_data_id) + { + CliprdrFileContext* file_context = clip_data_entry->file_context; + CLIPRDR_UNLOCK_CLIPBOARD_DATA unlock_clipboard_data = { 0 }; + + WINPR_ASSERT(file_context); + + unlock_clipboard_data.common.msgType = CB_UNLOCK_CLIPDATA; + unlock_clipboard_data.clipDataId = clip_data_entry->clip_data_id; + + file_context->context->ClientUnlockClipboardData(file_context->context, + &unlock_clipboard_data); + clip_data_entry->has_clip_data_id = FALSE; + + WLog_Print(file_context->log, WLOG_DEBUG, "Destroyed ClipDataEntry with id %u", + clip_data_entry->clip_data_id); + } + + free(clip_data_entry); +} + +static BOOL does_server_support_clipdata_locking(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + + if (cliprdr_file_context_remote_get_flags(file_context) & CB_CAN_LOCK_CLIPDATA) + return TRUE; + + return FALSE; +} + +static UINT32 get_next_free_clip_data_id(CliprdrFileContext* file_context) +{ + UINT32 clip_data_id = 0; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + clip_data_id = file_context->next_clip_data_id; + while (clip_data_id == 0 || + HashTable_GetItemValue(file_context->clip_data_table, (void*)(uintptr_t)clip_data_id)) + ++clip_data_id; + + file_context->next_clip_data_id = clip_data_id + 1; + HashTable_Unlock(file_context->inode_table); + + return clip_data_id; +} + +static CliprdrFuseClipDataEntry* clip_data_entry_new(CliprdrFileContext* file_context, + BOOL needs_clip_data_id) +{ + CliprdrFuseClipDataEntry* clip_data_entry = NULL; + CLIPRDR_LOCK_CLIPBOARD_DATA lock_clipboard_data = { 0 }; + + WINPR_ASSERT(file_context); + + clip_data_entry = calloc(1, sizeof(CliprdrFuseClipDataEntry)); + if (!clip_data_entry) + return NULL; + + clip_data_entry->file_context = file_context; + clip_data_entry->clip_data_id = get_next_free_clip_data_id(file_context); + + if (!needs_clip_data_id) + return clip_data_entry; + + lock_clipboard_data.common.msgType = CB_LOCK_CLIPDATA; + lock_clipboard_data.clipDataId = clip_data_entry->clip_data_id; + + if (file_context->context->ClientLockClipboardData(file_context->context, &lock_clipboard_data)) + { + HashTable_Lock(file_context->inode_table); + clip_data_entry_free(clip_data_entry); + HashTable_Unlock(file_context->inode_table); + return NULL; + } + clip_data_entry->has_clip_data_id = TRUE; + + WLog_Print(file_context->log, WLOG_DEBUG, "Created ClipDataEntry with id %u", + clip_data_entry->clip_data_id); + + return clip_data_entry; +} + +static BOOL should_remove_fuse_file(CliprdrFuseFile* fuse_file, BOOL all_files, + BOOL has_clip_data_id, UINT32 clip_data_id) +{ + if (all_files) + return TRUE; + + if (fuse_file->ino == FUSE_ROOT_ID) + return FALSE; + if (!fuse_file->has_clip_data_id && !has_clip_data_id) + return TRUE; + if (fuse_file->has_clip_data_id && has_clip_data_id && + (fuse_file->clip_data_id == clip_data_id)) + return TRUE; + + return FALSE; +} + +static BOOL maybe_clear_fuse_request(const void* key, void* value, void* arg) +{ + CliprdrFuseRequest* fuse_request = value; + FuseFileClearContext* clear_context = arg; + CliprdrFileContext* file_context = clear_context->file_context; + CliprdrFuseFile* fuse_file = fuse_request->fuse_file; + + WINPR_ASSERT(file_context); + + if (!should_remove_fuse_file(fuse_file, clear_context->all_files, + clear_context->has_clip_data_id, clear_context->clip_data_id)) + return TRUE; + + DEBUG_CLIPRDR(file_context->log, "Clearing FileContentsRequest for file \"%s\"", + fuse_file->filename_with_root); + + fuse_reply_err(fuse_request->fuse_req, EIO); + HashTable_Remove(file_context->request_table, key); + + return TRUE; +} + +static BOOL maybe_steal_inode(const void* key, void* value, void* arg) +{ + CliprdrFuseFile* fuse_file = value; + FuseFileClearContext* clear_context = arg; + CliprdrFileContext* file_context = clear_context->file_context; + + WINPR_ASSERT(file_context); + + if (should_remove_fuse_file(fuse_file, clear_context->all_files, + clear_context->has_clip_data_id, clear_context->clip_data_id)) + { + if (!ArrayList_Append(clear_context->fuse_files, fuse_file)) + WLog_Print(file_context->log, WLOG_ERROR, + "Failed to append FUSE file to list for deletion"); + + HashTable_Remove(file_context->inode_table, key); + } + + return TRUE; +} + +static BOOL notify_delete_child(void* data, size_t index, va_list ap) +{ + CliprdrFuseFile* child = data; + + WINPR_ASSERT(child); + + CliprdrFileContext* file_context = va_arg(ap, CliprdrFileContext*); + CliprdrFuseFile* parent = va_arg(ap, CliprdrFuseFile*); + + WINPR_ASSERT(file_context); + WINPR_ASSERT(parent); + + WINPR_ASSERT(file_context->fuse_sess); + fuse_lowlevel_notify_delete(file_context->fuse_sess, parent->ino, child->ino, child->filename, + strlen(child->filename)); + + return TRUE; +} + +static BOOL invalidate_inode(void* data, size_t index, va_list ap) +{ + CliprdrFuseFile* fuse_file = data; + + WINPR_ASSERT(fuse_file); + + CliprdrFileContext* file_context = va_arg(ap, CliprdrFileContext*); + WINPR_ASSERT(file_context); + WINPR_ASSERT(file_context->fuse_sess); + + ArrayList_ForEach(fuse_file->children, notify_delete_child, file_context, fuse_file); + + DEBUG_CLIPRDR(file_context->log, "Invalidating inode %lu for file \"%s\"", fuse_file->ino, + fuse_file->filename); + fuse_lowlevel_notify_inval_inode(file_context->fuse_sess, fuse_file->ino, 0, 0); + WLog_Print(file_context->log, WLOG_DEBUG, "Inode %lu invalidated", fuse_file->ino); + + return TRUE; +} + +static void clear_selection(CliprdrFileContext* file_context, BOOL all_selections, + CliprdrFuseClipDataEntry* clip_data_entry) +{ + FuseFileClearContext clear_context = { 0 }; + CliprdrFuseFile* root_dir = NULL; + CliprdrFuseFile* clip_data_dir = NULL; + + WINPR_ASSERT(file_context); + + root_dir = file_context->root_dir; + WINPR_ASSERT(root_dir); + + clear_context.file_context = file_context; + clear_context.fuse_files = ArrayList_New(FALSE); + WINPR_ASSERT(clear_context.fuse_files); + + wObject* aobj = ArrayList_Object(clear_context.fuse_files); + WINPR_ASSERT(aobj); + aobj->fnObjectFree = fuse_file_free; + + if (clip_data_entry) + { + clip_data_dir = clip_data_entry->clip_data_dir; + clip_data_entry->clip_data_dir = NULL; + + WINPR_ASSERT(clip_data_dir); + + ArrayList_Remove(root_dir->children, clip_data_dir); + + clear_context.has_clip_data_id = clip_data_dir->has_clip_data_id; + clear_context.clip_data_id = clip_data_dir->clip_data_id; + } + clear_context.all_files = all_selections; + + if (clip_data_entry && clip_data_entry->has_clip_data_id) + WLog_Print(file_context->log, WLOG_DEBUG, "Clearing selection for clipDataId %u", + clip_data_entry->clip_data_id); + else + WLog_Print(file_context->log, WLOG_DEBUG, "Clearing selection%s", + all_selections ? "s" : ""); + + HashTable_Foreach(file_context->request_table, maybe_clear_fuse_request, &clear_context); + HashTable_Foreach(file_context->inode_table, maybe_steal_inode, &clear_context); + HashTable_Unlock(file_context->inode_table); + + if (file_context->fuse_sess) + { + /* + * fuse_lowlevel_notify_inval_inode() is a blocking operation. If we receive a + * FUSE request (e.g. read()), then FUSE would block in read(), since the + * mutex of the inode_table would still be locked, if we wouldn't unlock it + * here. + * So, to avoid a deadlock here, unlock the mutex and reply all incoming + * operations with -ENOENT until the invalidation process is complete. + */ + ArrayList_ForEach(clear_context.fuse_files, invalidate_inode, file_context); + if (clip_data_dir) + { + fuse_lowlevel_notify_delete(file_context->fuse_sess, file_context->root_dir->ino, + clip_data_dir->ino, clip_data_dir->filename, + strlen(clip_data_dir->filename)); + } + } + ArrayList_Free(clear_context.fuse_files); + + HashTable_Lock(file_context->inode_table); + if (clip_data_entry && clip_data_entry->has_clip_data_id) + WLog_Print(file_context->log, WLOG_DEBUG, "Selection cleared for clipDataId %u", + clip_data_entry->clip_data_id); + else + WLog_Print(file_context->log, WLOG_DEBUG, "Selection%s cleared", all_selections ? "s" : ""); +} + +static void clear_entry_selection(CliprdrFuseClipDataEntry* clip_data_entry) +{ + WINPR_ASSERT(clip_data_entry); + + if (!clip_data_entry->clip_data_dir) + return; + + clear_selection(clip_data_entry->file_context, FALSE, clip_data_entry); +} + +static void clear_no_cdi_entry(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + + WINPR_ASSERT(file_context->inode_table); + HashTable_Lock(file_context->inode_table); + if (file_context->clip_data_entry_without_id) + { + clear_entry_selection(file_context->clip_data_entry_without_id); + + clip_data_entry_free(file_context->clip_data_entry_without_id); + file_context->clip_data_entry_without_id = NULL; + } + HashTable_Unlock(file_context->inode_table); +} + +static BOOL clear_clip_data_entries(const void* key, void* value, void* arg) +{ + clear_entry_selection(value); + + return TRUE; +} + +static void clear_cdi_entries(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + HashTable_Foreach(file_context->clip_data_table, clear_clip_data_entries, NULL); + + HashTable_Clear(file_context->clip_data_table); + HashTable_Unlock(file_context->inode_table); +} + +static UINT prepare_clip_data_entry_with_id(CliprdrFileContext* file_context) +{ + CliprdrFuseClipDataEntry* clip_data_entry = NULL; + + WINPR_ASSERT(file_context); + + clip_data_entry = clip_data_entry_new(file_context, TRUE); + if (!clip_data_entry) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to create clipDataEntry"); + return ERROR_INTERNAL_ERROR; + } + + HashTable_Lock(file_context->inode_table); + if (!HashTable_Insert(file_context->clip_data_table, + (void*)(uintptr_t)clip_data_entry->clip_data_id, clip_data_entry)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert clipDataEntry"); + clip_data_entry_free(clip_data_entry); + HashTable_Unlock(file_context->inode_table); + return ERROR_INTERNAL_ERROR; + } + HashTable_Unlock(file_context->inode_table); + + // HashTable_Insert owns clip_data_entry + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + file_context->current_clip_data_id = clip_data_entry->clip_data_id; + + return CHANNEL_RC_OK; +} + +static UINT prepare_clip_data_entry_without_id(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + WINPR_ASSERT(!file_context->clip_data_entry_without_id); + + file_context->clip_data_entry_without_id = clip_data_entry_new(file_context, FALSE); + if (!file_context->clip_data_entry_without_id) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to create clipDataEntry"); + return ERROR_INTERNAL_ERROR; + } + + return CHANNEL_RC_OK; +} +#endif + +UINT cliprdr_file_context_notify_new_server_format_list(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + WINPR_ASSERT(file_context->context); + +#if defined(WITH_FUSE) + clear_no_cdi_entry(file_context); + /* TODO: assign timeouts to old locks instead */ + clear_cdi_entries(file_context); + + if (does_server_support_clipdata_locking(file_context)) + return prepare_clip_data_entry_with_id(file_context); + else + return prepare_clip_data_entry_without_id(file_context); +#else + return CHANNEL_RC_OK; +#endif +} + +UINT cliprdr_file_context_notify_new_client_format_list(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + WINPR_ASSERT(file_context->context); + +#if defined(WITH_FUSE) + clear_no_cdi_entry(file_context); + /* TODO: assign timeouts to old locks instead */ + clear_cdi_entries(file_context); +#endif + + return CHANNEL_RC_OK; +} + +static CliprdrLocalStream* cliprdr_local_stream_new(CliprdrFileContext* context, UINT32 streamID, + const char* data, size_t size); +static void cliprdr_file_session_terminate(CliprdrFileContext* file, BOOL stop_thread); +static BOOL local_stream_discard(const void* key, void* value, void* arg); + +static void writelog(wLog* log, DWORD level, const char* fname, const char* fkt, size_t line, ...) +{ + if (!WLog_IsLevelActive(log, level)) + return; + + va_list ap = { 0 }; + va_start(ap, line); + WLog_PrintMessageVA(log, WLOG_MESSAGE_TEXT, level, line, fname, fkt, ap); + va_end(ap); +} + +#if defined(WITH_FUSE) +static void cliprdr_file_fuse_lookup(fuse_req_t req, fuse_ino_t parent, const char* name); +static void cliprdr_file_fuse_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi); +static void cliprdr_file_fuse_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info* fi); +static void cliprdr_file_fuse_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off, + struct fuse_file_info* fi); +static void cliprdr_file_fuse_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi); +static void cliprdr_file_fuse_opendir(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi); + +static const struct fuse_lowlevel_ops cliprdr_file_fuse_oper = { + .lookup = cliprdr_file_fuse_lookup, + .getattr = cliprdr_file_fuse_getattr, + .readdir = cliprdr_file_fuse_readdir, + .open = cliprdr_file_fuse_open, + .read = cliprdr_file_fuse_read, + .opendir = cliprdr_file_fuse_opendir, +}; + +static CliprdrFuseFile* get_fuse_file_by_ino(CliprdrFileContext* file_context, fuse_ino_t fuse_ino) +{ + WINPR_ASSERT(file_context); + + return HashTable_GetItemValue(file_context->inode_table, (void*)(uintptr_t)fuse_ino); +} + +static CliprdrFuseFile* get_fuse_file_by_name_from_parent(CliprdrFileContext* file_context, + CliprdrFuseFile* parent, const char* name) +{ + WINPR_ASSERT(file_context); + WINPR_ASSERT(parent); + + for (size_t i = 0; i < ArrayList_Count(parent->children); ++i) + { + CliprdrFuseFile* child = ArrayList_GetItem(parent->children, i); + + WINPR_ASSERT(child); + + if (strcmp(name, child->filename) == 0) + return child; + } + + DEBUG_CLIPRDR(file_context->log, "Requested file \"%s\" in directory \"%s\" does not exist", + name, parent->filename); + + return NULL; +} + +static CliprdrFuseRequest* cliprdr_fuse_request_new(CliprdrFileContext* file_context, + CliprdrFuseFile* fuse_file, fuse_req_t fuse_req, + FuseLowlevelOperationType operation_type) +{ + CliprdrFuseRequest* fuse_request = NULL; + UINT32 stream_id = file_context->next_stream_id; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(fuse_file); + + fuse_request = calloc(1, sizeof(CliprdrFuseRequest)); + if (!fuse_request) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to allocate FUSE request for file \"%s\"", + fuse_file->filename_with_root); + return NULL; + } + + fuse_request->fuse_file = fuse_file; + fuse_request->fuse_req = fuse_req; + fuse_request->operation_type = operation_type; + + while (stream_id == 0 || + HashTable_GetItemValue(file_context->request_table, (void*)(uintptr_t)stream_id)) + ++stream_id; + fuse_request->stream_id = stream_id; + + file_context->next_stream_id = stream_id + 1; + + if (!HashTable_Insert(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id, + fuse_request)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to track FUSE request for file \"%s\"", + fuse_file->filename_with_root); + free(fuse_request); + return NULL; + } + + return fuse_request; +} + +static BOOL request_file_size_async(CliprdrFileContext* file_context, CliprdrFuseFile* fuse_file, + fuse_req_t fuse_req, FuseLowlevelOperationType operation_type) +{ + CliprdrFuseRequest* fuse_request = NULL; + CLIPRDR_FILE_CONTENTS_REQUEST file_contents_request = { 0 }; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(fuse_file); + + fuse_request = cliprdr_fuse_request_new(file_context, fuse_file, fuse_req, operation_type); + if (!fuse_request) + return FALSE; + + file_contents_request.common.msgType = CB_FILECONTENTS_REQUEST; + file_contents_request.streamId = fuse_request->stream_id; + file_contents_request.listIndex = fuse_file->list_idx; + file_contents_request.dwFlags = FILECONTENTS_SIZE; + file_contents_request.cbRequested = 0x8; + file_contents_request.haveClipDataId = fuse_file->has_clip_data_id; + file_contents_request.clipDataId = fuse_file->clip_data_id; + + if (file_context->context->ClientFileContentsRequest(file_context->context, + &file_contents_request)) + { + WLog_Print(file_context->log, WLOG_ERROR, + "Failed to send FileContentsRequest for file \"%s\"", + fuse_file->filename_with_root); + HashTable_Remove(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id); + return FALSE; + } + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + DEBUG_CLIPRDR(file_context->log, "Requested file size for file \"%s\" with stream id %u", + fuse_file->filename, fuse_request->stream_id); + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + return TRUE; +} + +static void write_file_attributes(CliprdrFuseFile* fuse_file, struct stat* attr) +{ + memset(attr, 0, sizeof(struct stat)); + + if (!fuse_file) + return; + + attr->st_ino = fuse_file->ino; + if (fuse_file->is_directory) + { + attr->st_mode = S_IFDIR | (fuse_file->is_readonly ? 0555 : 0755); + attr->st_nlink = 2; + } + else + { + attr->st_mode = S_IFREG | (fuse_file->is_readonly ? 0444 : 0644); + attr->st_nlink = 1; + attr->st_size = WINPR_ASSERTING_INT_CAST(off_t, fuse_file->size); + } + attr->st_uid = getuid(); + attr->st_gid = getgid(); + attr->st_atime = attr->st_mtime = attr->st_ctime = + (fuse_file->has_last_write_time ? fuse_file->last_write_time_unix : time(NULL)); +} + +static void cliprdr_file_fuse_lookup(fuse_req_t fuse_req, fuse_ino_t parent_ino, const char* name) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* parent = NULL; + CliprdrFuseFile* fuse_file = NULL; + struct fuse_entry_param entry = { 0 }; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(parent = get_fuse_file_by_ino(file_context, parent_ino)) || !parent->is_directory) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + if (!(fuse_file = get_fuse_file_by_name_from_parent(file_context, parent, name))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + + DEBUG_CLIPRDR(file_context->log, "lookup() has been called for \"%s\"", name); + DEBUG_CLIPRDR(file_context->log, "Parent is \"%s\", child is \"%s\"", + parent->filename_with_root, fuse_file->filename_with_root); + + if (!fuse_file->is_directory && !fuse_file->has_size) + { + BOOL result = 0; + + result = + request_file_size_async(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_LOOKUP); + HashTable_Unlock(file_context->inode_table); + + if (!result) + fuse_reply_err(fuse_req, EIO); + + return; + } + + entry.ino = fuse_file->ino; + write_file_attributes(fuse_file, &entry.attr); + entry.attr_timeout = 1.0; + entry.entry_timeout = 1.0; + HashTable_Unlock(file_context->inode_table); + + fuse_reply_entry(fuse_req, &entry); +} + +static void cliprdr_file_fuse_getattr(fuse_req_t fuse_req, fuse_ino_t fuse_ino, + struct fuse_file_info* file_info) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* fuse_file = NULL; + struct stat attr = { 0 }; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + + DEBUG_CLIPRDR(file_context->log, "getattr() has been called for file \"%s\"", + fuse_file->filename_with_root); + + if (!fuse_file->is_directory && !fuse_file->has_size) + { + BOOL result = 0; + + result = + request_file_size_async(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_GETATTR); + HashTable_Unlock(file_context->inode_table); + + if (!result) + fuse_reply_err(fuse_req, EIO); + + return; + } + + write_file_attributes(fuse_file, &attr); + HashTable_Unlock(file_context->inode_table); + + fuse_reply_attr(fuse_req, &attr, 1.0); +} + +static void cliprdr_file_fuse_open(fuse_req_t fuse_req, fuse_ino_t fuse_ino, + struct fuse_file_info* file_info) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* fuse_file = NULL; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + if (fuse_file->is_directory) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, EISDIR); + return; + } + HashTable_Unlock(file_context->inode_table); + + if ((file_info->flags & O_ACCMODE) != O_RDONLY) + { + fuse_reply_err(fuse_req, EACCES); + return; + } + + /* Important for KDE to get file correctly */ + file_info->direct_io = 1; + + fuse_reply_open(fuse_req, file_info); +} + +static BOOL request_file_range_async(CliprdrFileContext* file_context, CliprdrFuseFile* fuse_file, + fuse_req_t fuse_req, off_t offset, size_t requested_size) +{ + CLIPRDR_FILE_CONTENTS_REQUEST file_contents_request = { 0 }; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(fuse_file); + + if (requested_size > UINT32_MAX) + return FALSE; + + CliprdrFuseRequest* fuse_request = + cliprdr_fuse_request_new(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_READ); + if (!fuse_request) + return FALSE; + + file_contents_request.common.msgType = CB_FILECONTENTS_REQUEST; + file_contents_request.streamId = fuse_request->stream_id; + file_contents_request.listIndex = fuse_file->list_idx; + file_contents_request.dwFlags = FILECONTENTS_RANGE; + file_contents_request.nPositionLow = (UINT32)(offset & 0xFFFFFFFF); + file_contents_request.nPositionHigh = (UINT32)((offset >> 32) & 0xFFFFFFFF); + file_contents_request.cbRequested = (UINT32)requested_size; + file_contents_request.haveClipDataId = fuse_file->has_clip_data_id; + file_contents_request.clipDataId = fuse_file->clip_data_id; + + if (file_context->context->ClientFileContentsRequest(file_context->context, + &file_contents_request)) + { + WLog_Print(file_context->log, WLOG_ERROR, + "Failed to send FileContentsRequest for file \"%s\"", + fuse_file->filename_with_root); + HashTable_Remove(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id); + return FALSE; + } + + // file_context->request_table owns fuse_request + // NOLINTBEGIN(clang-analyzer-unix.Malloc) + DEBUG_CLIPRDR( + file_context->log, + "Requested file range (%zu Bytes at offset %lu) for file \"%s\" with stream id %u", + requested_size, offset, fuse_file->filename, fuse_request->stream_id); + + return TRUE; + // NOLINTEND(clang-analyzer-unix.Malloc) +} + +static void cliprdr_file_fuse_read(fuse_req_t fuse_req, fuse_ino_t fuse_ino, size_t size, + off_t offset, struct fuse_file_info* file_info) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* fuse_file = NULL; + BOOL result = 0; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + if (fuse_file->is_directory) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, EISDIR); + return; + } + if (!fuse_file->has_size || (offset < 0) || ((size_t)offset > fuse_file->size)) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, EINVAL); + return; + } + + size = MIN(size, 8ULL * 1024ULL * 1024ULL); + + result = request_file_range_async(file_context, fuse_file, fuse_req, offset, size); + HashTable_Unlock(file_context->inode_table); + + if (!result) + fuse_reply_err(fuse_req, EIO); +} + +static void cliprdr_file_fuse_opendir(fuse_req_t fuse_req, fuse_ino_t fuse_ino, + struct fuse_file_info* file_info) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* fuse_file = NULL; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + if (!fuse_file->is_directory) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOTDIR); + return; + } + HashTable_Unlock(file_context->inode_table); + + if ((file_info->flags & O_ACCMODE) != O_RDONLY) + { + fuse_reply_err(fuse_req, EACCES); + return; + } + + fuse_reply_open(fuse_req, file_info); +} + +static void cliprdr_file_fuse_readdir(fuse_req_t fuse_req, fuse_ino_t fuse_ino, size_t max_size, + off_t offset, struct fuse_file_info* file_info) +{ + CliprdrFileContext* file_context = fuse_req_userdata(fuse_req); + CliprdrFuseFile* fuse_file = NULL; + CliprdrFuseFile* child = NULL; + struct stat attr = { 0 }; + size_t written_size = 0; + size_t entry_size = 0; + char* filename = NULL; + char* buf = NULL; + + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOENT); + return; + } + if (!fuse_file->is_directory) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOTDIR); + return; + } + + DEBUG_CLIPRDR(file_context->log, "Reading directory \"%s\" at offset %lu", + fuse_file->filename_with_root, offset); + + if ((offset < 0) || ((size_t)offset >= ArrayList_Count(fuse_file->children))) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_buf(fuse_req, NULL, 0); + return; + } + + buf = calloc(max_size, sizeof(char)); + if (!buf) + { + HashTable_Unlock(file_context->inode_table); + fuse_reply_err(fuse_req, ENOMEM); + return; + } + written_size = 0; + + for (off_t i = offset; i < 2; ++i) + { + if (i == 0) + { + write_file_attributes(fuse_file, &attr); + filename = "."; + } + else if (i == 1) + { + write_file_attributes(fuse_file->parent, &attr); + attr.st_ino = fuse_file->parent ? attr.st_ino : FUSE_ROOT_ID; + attr.st_mode = fuse_file->parent ? attr.st_mode : 0555; + filename = ".."; + } + else + { + WINPR_ASSERT(FALSE); + } + + /** + * buf needs to be large enough to hold the entry. If it's not, then the + * entry is not filled in but the size of the entry is still returned. + */ + entry_size = fuse_add_direntry(fuse_req, buf + written_size, max_size - written_size, + filename, &attr, i + 1); + if (entry_size > max_size - written_size) + break; + + written_size += entry_size; + } + + for (size_t j = 0, i = 2; j < ArrayList_Count(fuse_file->children); ++j, ++i) + { + if (i < (size_t)offset) + continue; + + child = ArrayList_GetItem(fuse_file->children, j); + + write_file_attributes(child, &attr); + entry_size = + fuse_add_direntry(fuse_req, buf + written_size, max_size - written_size, + child->filename, &attr, WINPR_ASSERTING_INT_CAST(off_t, i + 1)); + if (entry_size > max_size - written_size) + break; + + written_size += entry_size; + } + HashTable_Unlock(file_context->inode_table); + + fuse_reply_buf(fuse_req, buf, written_size); + free(buf); +} + +static void fuse_abort(int sig, const char* signame, void* context) +{ + CliprdrFileContext* file = (CliprdrFileContext*)context; + + if (file) + { + WLog_Print(file->log, WLOG_INFO, "signal %s [%d] aborting session", signame, sig); + cliprdr_file_session_terminate(file, FALSE); + } +} + +static DWORD WINAPI cliprdr_file_fuse_thread(LPVOID arg) +{ + CliprdrFileContext* file = (CliprdrFileContext*)arg; + + WINPR_ASSERT(file); + + DEBUG_CLIPRDR(file->log, "Starting fuse with mountpoint '%s'", file->path); + + struct fuse_args args = FUSE_ARGS_INIT(0, NULL); + fuse_opt_add_arg(&args, file->path); + file->fuse_sess = fuse_session_new(&args, &cliprdr_file_fuse_oper, + sizeof(cliprdr_file_fuse_oper), (void*)file); + (void)SetEvent(file->fuse_start_sync); + + if (file->fuse_sess != NULL) + { + freerdp_add_signal_cleanup_handler(file, fuse_abort); + if (0 == fuse_session_mount(file->fuse_sess, file->path)) + { + fuse_session_loop(file->fuse_sess); + fuse_session_unmount(file->fuse_sess); + } + freerdp_del_signal_cleanup_handler(file, fuse_abort); + + WLog_Print(file->log, WLOG_DEBUG, "Waiting for FUSE stop sync"); + if (WaitForSingleObject(file->fuse_stop_sync, INFINITE) == WAIT_FAILED) + WLog_Print(file->log, WLOG_ERROR, "Failed to wait for stop sync"); + fuse_session_destroy(file->fuse_sess); + } + fuse_opt_free_args(&args); + + DEBUG_CLIPRDR(file->log, "Quitting fuse with mountpoint '%s'", file->path); + + ExitThread(0); + return 0; +} + +static UINT cliprdr_file_context_server_file_contents_response( + CliprdrClientContext* cliprdr_context, + const CLIPRDR_FILE_CONTENTS_RESPONSE* file_contents_response) +{ + CliprdrFileContext* file_context = NULL; + CliprdrFuseRequest* fuse_request = NULL; + struct fuse_entry_param entry = { 0 }; + + WINPR_ASSERT(cliprdr_context); + WINPR_ASSERT(file_contents_response); + + file_context = cliprdr_context->custom; + WINPR_ASSERT(file_context); + + HashTable_Lock(file_context->inode_table); + fuse_request = HashTable_GetItemValue(file_context->request_table, + (void*)(uintptr_t)file_contents_response->streamId); + if (!fuse_request) + { + HashTable_Unlock(file_context->inode_table); + return CHANNEL_RC_OK; + } + + if (!(file_contents_response->common.msgFlags & CB_RESPONSE_OK)) + { + WLog_Print(file_context->log, WLOG_WARN, + "FileContentsRequests for file \"%s\" was unsuccessful", + fuse_request->fuse_file->filename); + + fuse_reply_err(fuse_request->fuse_req, EIO); + HashTable_Remove(file_context->request_table, + (void*)(uintptr_t)file_contents_response->streamId); + HashTable_Unlock(file_context->inode_table); + return CHANNEL_RC_OK; + } + + if ((fuse_request->operation_type == FUSE_LL_OPERATION_LOOKUP || + fuse_request->operation_type == FUSE_LL_OPERATION_GETATTR) && + file_contents_response->cbRequested != sizeof(UINT64)) + { + WLog_Print(file_context->log, WLOG_WARN, + "Received invalid file size for file \"%s\" from the client", + fuse_request->fuse_file->filename); + fuse_reply_err(fuse_request->fuse_req, EIO); + HashTable_Remove(file_context->request_table, + (void*)(uintptr_t)file_contents_response->streamId); + HashTable_Unlock(file_context->inode_table); + return CHANNEL_RC_OK; + } + + if (fuse_request->operation_type == FUSE_LL_OPERATION_LOOKUP || + fuse_request->operation_type == FUSE_LL_OPERATION_GETATTR) + { + DEBUG_CLIPRDR(file_context->log, "Received file size for file \"%s\" with stream id %u", + fuse_request->fuse_file->filename, file_contents_response->streamId); + + fuse_request->fuse_file->size = *((const UINT64*)file_contents_response->requestedData); + fuse_request->fuse_file->has_size = TRUE; + + entry.ino = fuse_request->fuse_file->ino; + write_file_attributes(fuse_request->fuse_file, &entry.attr); + entry.attr_timeout = 1.0; + entry.entry_timeout = 1.0; + } + else if (fuse_request->operation_type == FUSE_LL_OPERATION_READ) + { + DEBUG_CLIPRDR(file_context->log, "Received file range for file \"%s\" with stream id %u", + fuse_request->fuse_file->filename, file_contents_response->streamId); + } + HashTable_Unlock(file_context->inode_table); + + switch (fuse_request->operation_type) + { + case FUSE_LL_OPERATION_NONE: + break; + case FUSE_LL_OPERATION_LOOKUP: + fuse_reply_entry(fuse_request->fuse_req, &entry); + break; + case FUSE_LL_OPERATION_GETATTR: + fuse_reply_attr(fuse_request->fuse_req, &entry.attr, entry.attr_timeout); + break; + case FUSE_LL_OPERATION_READ: + fuse_reply_buf(fuse_request->fuse_req, + (const char*)file_contents_response->requestedData, + file_contents_response->cbRequested); + break; + default: + break; + } + + HashTable_Remove(file_context->request_table, + (void*)(uintptr_t)file_contents_response->streamId); + + return CHANNEL_RC_OK; +} +#endif + +static UINT cliprdr_file_context_send_file_contents_failure( + CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) +{ + CLIPRDR_FILE_CONTENTS_RESPONSE response = { 0 }; + + WINPR_ASSERT(file); + WINPR_ASSERT(fileContentsRequest); + + const UINT64 offset = (((UINT64)fileContentsRequest->nPositionHigh) << 32) | + ((UINT64)fileContentsRequest->nPositionLow); + writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__, + "server file contents request [lockID %" PRIu32 ", streamID %" PRIu32 + ", index %" PRIu32 "] offset %" PRIu64 ", size %" PRIu32 " failed", + fileContentsRequest->clipDataId, fileContentsRequest->streamId, + fileContentsRequest->listIndex, offset, fileContentsRequest->cbRequested); + + response.common.msgFlags = CB_RESPONSE_FAIL; + response.streamId = fileContentsRequest->streamId; + + WINPR_ASSERT(file->context); + WINPR_ASSERT(file->context->ClientFileContentsResponse); + return file->context->ClientFileContentsResponse(file->context, &response); +} + +static UINT +cliprdr_file_context_send_contents_response(CliprdrFileContext* file, + const CLIPRDR_FILE_CONTENTS_REQUEST* request, + const void* data, size_t size) +{ + if (size > UINT32_MAX) + return ERROR_INVALID_PARAMETER; + + CLIPRDR_FILE_CONTENTS_RESPONSE response = { .streamId = request->streamId, + .requestedData = data, + .cbRequested = (UINT32)size, + .common.msgFlags = CB_RESPONSE_OK }; + + WINPR_ASSERT(request); + WINPR_ASSERT(file); + + WLog_Print(file->log, WLOG_DEBUG, "send contents response streamID=%" PRIu32 ", size=%" PRIu32, + response.streamId, response.cbRequested); + WINPR_ASSERT(file->context); + WINPR_ASSERT(file->context->ClientFileContentsResponse); + return file->context->ClientFileContentsResponse(file->context, &response); +} + +static BOOL dump_streams(const void* key, void* value, void* arg) +{ + const UINT32* ukey = key; + CliprdrLocalStream* cur = value; + + writelog(cur->context->log, WLOG_WARN, __FILE__, __func__, __LINE__, + "[key %" PRIu32 "] lockID %" PRIu32 ", count %" PRIuz ", locked %d", *ukey, + cur->lockId, cur->count, cur->locked); + for (size_t x = 0; x < cur->count; x++) + { + const CliprdrLocalFile* file = &cur->files[x]; + writelog(cur->context->log, WLOG_WARN, __FILE__, __func__, __LINE__, "file [%" PRIuz "] ", + x, file->name, file->size); + } + return TRUE; +} + +static CliprdrLocalFile* file_info_for_request(CliprdrFileContext* file, UINT32 lockId, + UINT32 listIndex) +{ + WINPR_ASSERT(file); + + CliprdrLocalStream* cur = HashTable_GetItemValue(file->local_streams, &lockId); + if (cur) + { + if (listIndex < cur->count) + { + CliprdrLocalFile* f = &cur->files[listIndex]; + return f; + } + else + { + writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__, + "invalid entry index for lockID %" PRIu32 ", index %" PRIu32 " [count %" PRIu32 + "] [locked %d]", + lockId, listIndex, cur->count, cur->locked); + } + } + else + { + writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__, + "missing entry for lockID %" PRIu32 ", index %" PRIu32, lockId, listIndex); + HashTable_Foreach(file->local_streams, dump_streams, file); + } + + return NULL; +} + +static CliprdrLocalFile* file_for_request(CliprdrFileContext* file, UINT32 lockId, UINT32 listIndex) +{ + CliprdrLocalFile* f = file_info_for_request(file, lockId, listIndex); + if (f) + { + if (!f->fp) + { + const char* name = f->name; + f->fp = winpr_fopen(name, "rb"); + } + if (!f->fp) + { + char ebuffer[256] = { 0 }; + writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__, + "[lockID %" PRIu32 ", index %" PRIu32 + "] failed to open file '%s' [size %" PRId64 "] %s [%d]", + lockId, listIndex, f->name, f->size, + winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno); + return NULL; + } + } + + return f; +} + +static void cliprdr_local_file_try_close(CliprdrLocalFile* file, UINT res, UINT64 offset, + UINT64 size) +{ + WINPR_ASSERT(file); + + if (res != 0) + { + WINPR_ASSERT(file->context); + WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s after error %" PRIu32, + file->name, res); + } + else if (((file->size > 0) && (offset + size >= (UINT64)file->size))) + { + WINPR_ASSERT(file->context); + WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s after read", file->name); + } + else + { + // TODO: we need to keep track of open files to avoid running out of file descriptors + // TODO: for the time being just close again. + } + if (file->fp) + (void)fclose(file->fp); + file->fp = NULL; +} + +static UINT cliprdr_file_context_server_file_size_request( + CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) +{ + WINPR_ASSERT(fileContentsRequest); + + if (fileContentsRequest->cbRequested != sizeof(UINT64)) + { + WLog_Print(file->log, WLOG_WARN, "unexpected FILECONTENTS_SIZE request: %" PRIu32 " bytes", + fileContentsRequest->cbRequested); + } + + HashTable_Lock(file->local_streams); + + UINT res = CHANNEL_RC_OK; + CliprdrLocalFile* rfile = + file_for_request(file, fileContentsRequest->clipDataId, fileContentsRequest->listIndex); + if (!rfile) + res = cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest); + else + { + if (_fseeki64(rfile->fp, 0, SEEK_END) < 0) + res = cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest); + else + { + const INT64 size = _ftelli64(rfile->fp); + rfile->size = size; + cliprdr_local_file_try_close(rfile, res, 0, 0); + + res = cliprdr_file_context_send_contents_response(file, fileContentsRequest, &size, + sizeof(size)); + } + } + + HashTable_Unlock(file->local_streams); + return res; +} + +static UINT cliprdr_file_context_server_file_range_request( + CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) +{ + BYTE* data = NULL; + + WINPR_ASSERT(fileContentsRequest); + + HashTable_Lock(file->local_streams); + const UINT64 offset = (((UINT64)fileContentsRequest->nPositionHigh) << 32) | + ((UINT64)fileContentsRequest->nPositionLow); + + CliprdrLocalFile* rfile = + file_for_request(file, fileContentsRequest->clipDataId, fileContentsRequest->listIndex); + if (!rfile) + goto fail; + + if (_fseeki64(rfile->fp, WINPR_ASSERTING_INT_CAST(int64_t, offset), SEEK_SET) < 0) + goto fail; + + data = malloc(fileContentsRequest->cbRequested); + if (!data) + goto fail; + + const size_t r = fread(data, 1, fileContentsRequest->cbRequested, rfile->fp); + const UINT rc = cliprdr_file_context_send_contents_response(file, fileContentsRequest, data, r); + free(data); + + cliprdr_local_file_try_close(rfile, rc, offset, fileContentsRequest->cbRequested); + HashTable_Unlock(file->local_streams); + return rc; +fail: + if (rfile) + cliprdr_local_file_try_close(rfile, ERROR_INTERNAL_ERROR, offset, + fileContentsRequest->cbRequested); + free(data); + HashTable_Unlock(file->local_streams); + return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest); +} + +static void cliprdr_local_stream_free(void* obj); + +static UINT change_lock(CliprdrFileContext* file, UINT32 lockId, BOOL lock) +{ + UINT rc = CHANNEL_RC_OK; + + WINPR_ASSERT(file); + + HashTable_Lock(file->local_streams); + + { + CliprdrLocalStream* stream = HashTable_GetItemValue(file->local_streams, &lockId); + if (lock && !stream) + { + stream = cliprdr_local_stream_new(file, lockId, NULL, 0); + if (!HashTable_Insert(file->local_streams, &lockId, stream)) + { + rc = ERROR_INTERNAL_ERROR; + cliprdr_local_stream_free(stream); + stream = NULL; + } + file->local_lock_id = lockId; + } + if (stream) + { + stream->locked = lock; + stream->lockId = lockId; + } + } + + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert ownership stream + if (!lock) + { + if (!HashTable_Foreach(file->local_streams, local_stream_discard, file)) + rc = ERROR_INTERNAL_ERROR; + } + + HashTable_Unlock(file->local_streams); + return rc; +} + +static UINT cliprdr_file_context_lock(CliprdrClientContext* context, + const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(lockClipboardData); + CliprdrFileContext* file = (context->custom); + return change_lock(file, lockClipboardData->clipDataId, TRUE); +} + +static UINT cliprdr_file_context_unlock(CliprdrClientContext* context, + const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData) +{ + WINPR_ASSERT(context); + WINPR_ASSERT(unlockClipboardData); + CliprdrFileContext* file = (context->custom); + return change_lock(file, unlockClipboardData->clipDataId, FALSE); +} + +static UINT cliprdr_file_context_server_file_contents_request( + CliprdrClientContext* context, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest) +{ + UINT error = NO_ERROR; + + WINPR_ASSERT(context); + WINPR_ASSERT(fileContentsRequest); + + CliprdrFileContext* file = (context->custom); + WINPR_ASSERT(file); + + /* + * MS-RDPECLIP 2.2.5.3 File Contents Request PDU (CLIPRDR_FILECONTENTS_REQUEST): + * The FILECONTENTS_SIZE and FILECONTENTS_RANGE flags MUST NOT be set at the same time. + */ + if ((fileContentsRequest->dwFlags & (FILECONTENTS_SIZE | FILECONTENTS_RANGE)) == + (FILECONTENTS_SIZE | FILECONTENTS_RANGE)) + { + WLog_Print(file->log, WLOG_ERROR, "invalid CLIPRDR_FILECONTENTS_REQUEST.dwFlags"); + return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest); + } + + if (fileContentsRequest->dwFlags & FILECONTENTS_SIZE) + error = cliprdr_file_context_server_file_size_request(file, fileContentsRequest); + + if (fileContentsRequest->dwFlags & FILECONTENTS_RANGE) + error = cliprdr_file_context_server_file_range_request(file, fileContentsRequest); + + if (error) + { + WLog_Print(file->log, WLOG_ERROR, "failed to handle CLIPRDR_FILECONTENTS_REQUEST: 0x%08X", + error); + return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest); + } + + return CHANNEL_RC_OK; +} + +BOOL cliprdr_file_context_init(CliprdrFileContext* file, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(cliprdr); + + cliprdr->custom = file; + file->context = cliprdr; + + cliprdr->ServerLockClipboardData = cliprdr_file_context_lock; + cliprdr->ServerUnlockClipboardData = cliprdr_file_context_unlock; + cliprdr->ServerFileContentsRequest = cliprdr_file_context_server_file_contents_request; +#if defined(WITH_FUSE) + cliprdr->ServerFileContentsResponse = cliprdr_file_context_server_file_contents_response; +#endif + + return TRUE; +} + +#if defined(WITH_FUSE) +static void clear_all_selections(CliprdrFileContext* file_context) +{ + WINPR_ASSERT(file_context); + WINPR_ASSERT(file_context->inode_table); + + HashTable_Lock(file_context->inode_table); + clear_selection(file_context, TRUE, NULL); + + HashTable_Clear(file_context->clip_data_table); + HashTable_Unlock(file_context->inode_table); +} +#endif + +BOOL cliprdr_file_context_uninit(CliprdrFileContext* file, CliprdrClientContext* cliprdr) +{ + WINPR_ASSERT(file); + WINPR_ASSERT(cliprdr); + + // Clear all data before the channel is closed + // the cleanup handlers are dependent on a working channel. +#if defined(WITH_FUSE) + if (file->inode_table) + { + clear_no_cdi_entry(file); + clear_all_selections(file); + } +#endif + + HashTable_Clear(file->local_streams); + + file->context = NULL; +#if defined(WITH_FUSE) + cliprdr->ServerFileContentsResponse = NULL; +#endif + + return TRUE; +} + +static BOOL cliprdr_file_content_changed_and_update(void* ihash, size_t hsize, const void* data, + size_t size) +{ + + BYTE hash[WINPR_SHA256_DIGEST_LENGTH] = { 0 }; + + if (hsize < sizeof(hash)) + return FALSE; + + if (!winpr_Digest(WINPR_MD_SHA256, data, size, hash, sizeof(hash))) + return FALSE; + + const BOOL changed = memcmp(hash, ihash, sizeof(hash)) != 0; + if (changed) + memcpy(ihash, hash, sizeof(hash)); + return changed; +} + +static BOOL cliprdr_file_client_content_changed_and_update(CliprdrFileContext* file, + const void* data, size_t size) +{ + WINPR_ASSERT(file); + return cliprdr_file_content_changed_and_update(file->client_data_hash, + sizeof(file->client_data_hash), data, size); +} + +#if defined(WITH_FUSE) +static fuse_ino_t get_next_free_inode(CliprdrFileContext* file_context) +{ + fuse_ino_t ino = 0; + + WINPR_ASSERT(file_context); + + ino = file_context->next_ino; + while (ino == 0 || ino == FUSE_ROOT_ID || + HashTable_GetItemValue(file_context->inode_table, (void*)(uintptr_t)ino)) + ++ino; + + file_context->next_ino = ino + 1; + + return ino; +} + +static CliprdrFuseFile* clip_data_dir_new(CliprdrFileContext* file_context, BOOL has_clip_data_id, + UINT32 clip_data_id) +{ + CliprdrFuseFile* root_dir = NULL; + CliprdrFuseFile* clip_data_dir = NULL; + size_t path_length = 0; + + WINPR_ASSERT(file_context); + + clip_data_dir = fuse_file_new(); + if (!clip_data_dir) + return NULL; + + path_length = 1 + MAX_CLIP_DATA_DIR_LEN + 1; + + clip_data_dir->filename_with_root = calloc(path_length, sizeof(char)); + if (!clip_data_dir->filename_with_root) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to allocate filename"); + fuse_file_free(clip_data_dir); + return NULL; + } + + if (has_clip_data_id) + (void)_snprintf(clip_data_dir->filename_with_root, path_length, "/%u", + (unsigned)clip_data_id); + else + (void)_snprintf(clip_data_dir->filename_with_root, path_length, "/%" PRIu64, + NO_CLIP_DATA_ID); + + clip_data_dir->filename = strrchr(clip_data_dir->filename_with_root, '/') + 1; + + clip_data_dir->ino = get_next_free_inode(file_context); + clip_data_dir->is_directory = TRUE; + clip_data_dir->is_readonly = TRUE; + clip_data_dir->has_clip_data_id = has_clip_data_id; + clip_data_dir->clip_data_id = clip_data_id; + + root_dir = file_context->root_dir; + if (!ArrayList_Append(root_dir->children, clip_data_dir)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to append FUSE file"); + fuse_file_free(clip_data_dir); + return NULL; + } + clip_data_dir->parent = root_dir; + + if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)clip_data_dir->ino, + clip_data_dir)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into inode table"); + ArrayList_Remove(root_dir->children, clip_data_dir); + fuse_file_free(clip_data_dir); + return NULL; + } + + return clip_data_dir; +} + +static char* get_parent_path(const char* filepath) +{ + const char* base = strrchr(filepath, '/'); + WINPR_ASSERT(base); + + while ((base > filepath) && (*base == '/')) + --base; + + WINPR_ASSERT(base >= filepath); + const size_t parent_path_length = 1ULL + (size_t)(base - filepath); + char* parent_path = calloc(parent_path_length + 1, sizeof(char)); + if (!parent_path) + return NULL; + + memcpy(parent_path, filepath, parent_path_length); + + return parent_path; +} + +static BOOL is_fuse_file_not_parent(const void* key, void* value, void* arg) +{ + CliprdrFuseFile* fuse_file = value; + CliprdrFuseFindParentContext* find_context = arg; + + if (!fuse_file->is_directory) + return TRUE; + + if (strcmp(find_context->parent_path, fuse_file->filename_with_root) == 0) + { + find_context->parent = fuse_file; + return FALSE; + } + + return TRUE; +} + +static CliprdrFuseFile* get_parent_directory(CliprdrFileContext* file_context, const char* path) +{ + CliprdrFuseFindParentContext find_context = { 0 }; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(path); + + find_context.parent_path = get_parent_path(path); + if (!find_context.parent_path) + return NULL; + + WINPR_ASSERT(!find_context.parent); + + if (HashTable_Foreach(file_context->inode_table, is_fuse_file_not_parent, &find_context)) + { + free(find_context.parent_path); + return NULL; + } + WINPR_ASSERT(find_context.parent); + + free(find_context.parent_path); + + return find_context.parent; +} + +static BOOL set_selection_for_clip_data_entry(CliprdrFileContext* file_context, + CliprdrFuseClipDataEntry* clip_data_entry, + const FILEDESCRIPTORW* files, UINT32 n_files) +{ + CliprdrFuseFile* clip_data_dir = NULL; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(clip_data_entry); + WINPR_ASSERT(files); + + clip_data_dir = clip_data_entry->clip_data_dir; + WINPR_ASSERT(clip_data_dir); + + if (clip_data_entry->has_clip_data_id) + WLog_Print(file_context->log, WLOG_DEBUG, "Setting selection for clipDataId %u", + clip_data_entry->clip_data_id); + else + WLog_Print(file_context->log, WLOG_DEBUG, "Setting selection"); + + // NOLINTBEGIN(clang-analyzer-unix.Malloc) HashTable_Insert owns fuse_file + for (UINT32 i = 0; i < n_files; ++i) + { + const FILEDESCRIPTORW* file = &files[i]; + CliprdrFuseFile* fuse_file = NULL; + char* filename = NULL; + size_t path_length = 0; + + fuse_file = fuse_file_new(); + if (!fuse_file) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to create FUSE file"); + clear_entry_selection(clip_data_entry); + return FALSE; + } + + filename = ConvertWCharToUtf8Alloc(file->cFileName, NULL); + if (!filename) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to convert filename"); + fuse_file_free(fuse_file); + clear_entry_selection(clip_data_entry); + return FALSE; + } + + for (size_t j = 0; filename[j]; ++j) + { + if (filename[j] == '\\') + filename[j] = '/'; + } + + path_length = strlen(clip_data_dir->filename_with_root) + 1 + strlen(filename) + 1; + fuse_file->filename_with_root = calloc(path_length, sizeof(char)); + if (!fuse_file->filename_with_root) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to allocate filename"); + free(filename); + fuse_file_free(fuse_file); + clear_entry_selection(clip_data_entry); + return FALSE; + } + + (void)_snprintf(fuse_file->filename_with_root, path_length, "%s/%s", + clip_data_dir->filename_with_root, filename); + free(filename); + + fuse_file->filename = strrchr(fuse_file->filename_with_root, '/') + 1; + + fuse_file->parent = get_parent_directory(file_context, fuse_file->filename_with_root); + if (!fuse_file->parent) + { + WLog_Print(file_context->log, WLOG_ERROR, "Found no parent for FUSE file"); + fuse_file_free(fuse_file); + clear_entry_selection(clip_data_entry); + return FALSE; + } + + if (!ArrayList_Append(fuse_file->parent->children, fuse_file)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to append FUSE file"); + fuse_file_free(fuse_file); + clear_entry_selection(clip_data_entry); + return FALSE; + } + + fuse_file->list_idx = i; + fuse_file->ino = get_next_free_inode(file_context); + fuse_file->has_clip_data_id = clip_data_entry->has_clip_data_id; + fuse_file->clip_data_id = clip_data_entry->clip_data_id; + if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + fuse_file->is_directory = TRUE; + if (file->dwFileAttributes & FILE_ATTRIBUTE_READONLY) + fuse_file->is_readonly = TRUE; + if (file->dwFlags & FD_FILESIZE) + { + fuse_file->size = ((UINT64)file->nFileSizeHigh << 32) + file->nFileSizeLow; + fuse_file->has_size = TRUE; + } + if (file->dwFlags & FD_WRITESTIME) + { + INT64 filetime = 0; + + filetime = file->ftLastWriteTime.dwHighDateTime; + filetime <<= 32; + filetime += file->ftLastWriteTime.dwLowDateTime; + + fuse_file->last_write_time_unix = + 1LL * filetime / (10LL * 1000LL * 1000LL) - WIN32_FILETIME_TO_UNIX_EPOCH; + fuse_file->has_last_write_time = TRUE; + } + + if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)fuse_file->ino, + fuse_file)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into inode table"); + fuse_file_free(fuse_file); + clear_entry_selection(clip_data_entry); + return FALSE; + } + } + // NOLINTEND(clang-analyzer-unix.Malloc) HashTable_Insert owns fuse_file + + if (clip_data_entry->has_clip_data_id) + WLog_Print(file_context->log, WLOG_DEBUG, "Selection set for clipDataId %u", + clip_data_entry->clip_data_id); + else + WLog_Print(file_context->log, WLOG_DEBUG, "Selection set"); + + return TRUE; +} + +static BOOL update_exposed_path(CliprdrFileContext* file_context, wClipboard* clip, + CliprdrFuseClipDataEntry* clip_data_entry) +{ + wClipboardDelegate* delegate = NULL; + CliprdrFuseFile* clip_data_dir = NULL; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(clip); + WINPR_ASSERT(clip_data_entry); + + delegate = ClipboardGetDelegate(clip); + WINPR_ASSERT(delegate); + + clip_data_dir = clip_data_entry->clip_data_dir; + WINPR_ASSERT(clip_data_dir); + + free(file_context->exposed_path); + file_context->exposed_path = GetCombinedPath(file_context->path, clip_data_dir->filename); + if (file_context->exposed_path) + WLog_Print(file_context->log, WLOG_DEBUG, "Updated exposed path to \"%s\"", + file_context->exposed_path); + + delegate->basePath = file_context->exposed_path; + + return delegate->basePath != NULL; +} +#endif + +BOOL cliprdr_file_context_update_server_data(CliprdrFileContext* file_context, wClipboard* clip, + const void* data, size_t size) +{ +#if defined(WITH_FUSE) + CliprdrFuseClipDataEntry* clip_data_entry = NULL; + FILEDESCRIPTORW* files = NULL; + UINT32 n_files = 0; + BOOL rc = FALSE; + + WINPR_ASSERT(file_context); + WINPR_ASSERT(clip); + if (size > UINT32_MAX) + return FALSE; + + if (cliprdr_parse_file_list(data, (UINT32)size, &files, &n_files)) + { + WLog_Print(file_context->log, WLOG_ERROR, "Failed to parse file list"); + return FALSE; + } + + HashTable_Lock(file_context->inode_table); + HashTable_Lock(file_context->clip_data_table); + if (does_server_support_clipdata_locking(file_context)) + clip_data_entry = HashTable_GetItemValue( + file_context->clip_data_table, (void*)(uintptr_t)file_context->current_clip_data_id); + else + clip_data_entry = file_context->clip_data_entry_without_id; + + WINPR_ASSERT(clip_data_entry); + + clear_entry_selection(clip_data_entry); + WINPR_ASSERT(!clip_data_entry->clip_data_dir); + + clip_data_entry->clip_data_dir = + clip_data_dir_new(file_context, does_server_support_clipdata_locking(file_context), + file_context->current_clip_data_id); + if (!clip_data_entry->clip_data_dir) + goto fail; + if (!update_exposed_path(file_context, clip, clip_data_entry)) + goto fail; + if (!set_selection_for_clip_data_entry(file_context, clip_data_entry, files, n_files)) + goto fail; + + rc = TRUE; + +fail: + HashTable_Unlock(file_context->clip_data_table); + HashTable_Unlock(file_context->inode_table); + free(files); + return rc; +#else + return FALSE; +#endif +} + +void* cliprdr_file_context_get_context(CliprdrFileContext* file) +{ + WINPR_ASSERT(file); + return file->clipboard; +} + +void cliprdr_file_session_terminate(CliprdrFileContext* file, BOOL stop_thread) +{ + if (!file) + return; + +#if defined(WITH_FUSE) + WINPR_ASSERT(file->fuse_stop_sync); + + WLog_Print(file->log, WLOG_DEBUG, "Setting FUSE exit flag"); + if (file->fuse_sess) + fuse_session_exit(file->fuse_sess); + + if (stop_thread) + { + WLog_Print(file->log, WLOG_DEBUG, "Setting FUSE stop event"); + (void)SetEvent(file->fuse_stop_sync); + } +#endif + /* not elegant but works for umounting FUSE + fuse_chan must receive an oper buf to unblock fuse_session_receive_buf function. + */ +#if defined(WITH_FUSE) + WLog_Print(file->log, WLOG_DEBUG, "Forcing FUSE to check exit flag"); +#endif + (void)winpr_PathFileExists(file->path); +} + +void cliprdr_file_context_free(CliprdrFileContext* file) +{ + if (!file) + return; + +#if defined(WITH_FUSE) + if (file->inode_table) + { + clear_no_cdi_entry(file); + clear_all_selections(file); + } + + if (file->fuse_thread) + { + WINPR_ASSERT(file->fuse_stop_sync); + + WLog_Print(file->log, WLOG_DEBUG, "Stopping FUSE thread"); + cliprdr_file_session_terminate(file, TRUE); + + WLog_Print(file->log, WLOG_DEBUG, "Waiting on FUSE thread"); + (void)WaitForSingleObject(file->fuse_thread, INFINITE); + (void)CloseHandle(file->fuse_thread); + } + if (file->fuse_stop_sync) + (void)CloseHandle(file->fuse_stop_sync); + if (file->fuse_start_sync) + (void)CloseHandle(file->fuse_start_sync); + + HashTable_Free(file->request_table); + HashTable_Free(file->clip_data_table); + HashTable_Free(file->inode_table); +#endif + HashTable_Free(file->local_streams); + winpr_RemoveDirectory(file->path); + free(file->path); + free(file->exposed_path); + free(file); +} + +static BOOL create_base_path(CliprdrFileContext* file) +{ + WINPR_ASSERT(file); + + char base[64] = { 0 }; + (void)_snprintf(base, sizeof(base), "com.freerdp.client.cliprdr.%" PRIu32, + GetCurrentProcessId()); + + file->path = GetKnownSubPath(KNOWN_PATH_TEMP, base); + if (!file->path) + return FALSE; + + if (!winpr_PathFileExists(file->path) && !winpr_PathMakePath(file->path, 0)) + { + WLog_Print(file->log, WLOG_ERROR, "Failed to create directory '%s'", file->path); + return FALSE; + } + return TRUE; +} + +static void cliprdr_local_file_free(CliprdrLocalFile* file) +{ + const CliprdrLocalFile empty = { 0 }; + if (!file) + return; + if (file->fp) + { + WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s, discarding entry", file->name); + (void)fclose(file->fp); + } + free(file->name); + *file = empty; +} + +static BOOL cliprdr_local_file_new(CliprdrFileContext* context, CliprdrLocalFile* f, + const char* path) +{ + const CliprdrLocalFile empty = { 0 }; + WINPR_ASSERT(f); + WINPR_ASSERT(context); + WINPR_ASSERT(path); + + *f = empty; + f->context = context; + f->name = winpr_str_url_decode(path, strlen(path)); + if (!f->name) + goto fail; + + return TRUE; +fail: + cliprdr_local_file_free(f); + return FALSE; +} + +static void cliprdr_local_files_free(CliprdrLocalStream* stream) +{ + WINPR_ASSERT(stream); + + for (size_t x = 0; x < stream->count; x++) + cliprdr_local_file_free(&stream->files[x]); + free(stream->files); + + stream->files = NULL; + stream->count = 0; +} + +static void cliprdr_local_stream_free(void* obj) +{ + CliprdrLocalStream* stream = (CliprdrLocalStream*)obj; + if (stream) + cliprdr_local_files_free(stream); + + free(stream); +} + +static BOOL append_entry(CliprdrLocalStream* stream, const char* path) +{ + CliprdrLocalFile* tmp = realloc(stream->files, sizeof(CliprdrLocalFile) * (stream->count + 1)); + if (!tmp) + return FALSE; + stream->files = tmp; + CliprdrLocalFile* f = &stream->files[stream->count++]; + + return cliprdr_local_file_new(stream->context, f, path); +} + +static BOOL is_directory(const char* path) +{ + WCHAR* wpath = ConvertUtf8ToWCharAlloc(path, NULL); + if (!wpath) + return FALSE; + + HANDLE hFile = + CreateFileW(wpath, 0, FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + free(wpath); + + if (hFile == INVALID_HANDLE_VALUE) + return FALSE; + + BY_HANDLE_FILE_INFORMATION fileInformation = { 0 }; + const BOOL status = GetFileInformationByHandle(hFile, &fileInformation); + (void)CloseHandle(hFile); + if (!status) + return FALSE; + + return (fileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? TRUE : FALSE; +} + +static BOOL add_directory(CliprdrLocalStream* stream, const char* path) +{ + char* wildcardpath = GetCombinedPath(path, "*"); + if (!wildcardpath) + return FALSE; + WCHAR* wpath = ConvertUtf8ToWCharAlloc(wildcardpath, NULL); + free(wildcardpath); + if (!wpath) + return FALSE; + + WIN32_FIND_DATAW FindFileData = { 0 }; + HANDLE hFind = FindFirstFileW(wpath, &FindFileData); + free(wpath); + + if (hFind == INVALID_HANDLE_VALUE) + return FALSE; + + BOOL rc = FALSE; + char* next = NULL; + + WCHAR dotbuffer[6] = { 0 }; + WCHAR dotdotbuffer[6] = { 0 }; + const WCHAR* dot = InitializeConstWCharFromUtf8(".", dotbuffer, ARRAYSIZE(dotbuffer)); + const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer)); + do + { + if (_wcscmp(FindFileData.cFileName, dot) == 0) + continue; + if (_wcscmp(FindFileData.cFileName, dotdot) == 0) + continue; + + char cFileName[MAX_PATH] = { 0 }; + (void)ConvertWCharNToUtf8(FindFileData.cFileName, ARRAYSIZE(FindFileData.cFileName), + cFileName, ARRAYSIZE(cFileName)); + + free(next); + next = GetCombinedPath(path, cFileName); + if (!next) + goto fail; + + if (!append_entry(stream, next)) + goto fail; + if (is_directory(next)) + { + if (!add_directory(stream, next)) + goto fail; + } + } while (FindNextFileW(hFind, &FindFileData)); + + rc = TRUE; +fail: + free(next); + FindClose(hFind); + + return rc; +} + +static BOOL cliprdr_local_stream_update(CliprdrLocalStream* stream, const char* data, size_t size) +{ + BOOL rc = FALSE; + WINPR_ASSERT(stream); + if (size == 0) + return TRUE; + + cliprdr_local_files_free(stream); + + stream->files = calloc(size, sizeof(CliprdrLocalFile)); + if (!stream->files) + return FALSE; + + char* copy = strndup(data, size); + if (!copy) + return FALSE; + + char* saveptr = NULL; + char* ptr = strtok_s(copy, "\r\n", &saveptr); + while (ptr) + { + const char* name = ptr; + if (strncmp("file:///", ptr, 8) == 0) + name = &ptr[7]; + else if (strncmp("file:/", ptr, 6) == 0) + name = &ptr[5]; + + if (!append_entry(stream, name)) + goto fail; + + if (is_directory(name)) + { + const BOOL res = add_directory(stream, name); + if (!res) + goto fail; + } + ptr = strtok_s(NULL, "\r\n", &saveptr); + } + + rc = TRUE; +fail: + free(copy); + return rc; +} + +CliprdrLocalStream* cliprdr_local_stream_new(CliprdrFileContext* context, UINT32 streamID, + const char* data, size_t size) +{ + WINPR_ASSERT(context); + CliprdrLocalStream* stream = calloc(1, sizeof(CliprdrLocalStream)); + if (!stream) + return NULL; + + stream->context = context; + if (!cliprdr_local_stream_update(stream, data, size)) + goto fail; + + stream->lockId = streamID; + return stream; + +fail: + cliprdr_local_stream_free(stream); + return NULL; +} + +static UINT32 UINTPointerHash(const void* id) +{ + WINPR_ASSERT(id); + return *((const UINT32*)id); +} + +static BOOL UINTPointerCompare(const void* pointer1, const void* pointer2) +{ + if (!pointer1 || !pointer2) + return pointer1 == pointer2; + + const UINT32* a = pointer1; + const UINT32* b = pointer2; + return *a == *b; +} + +static void* UINTPointerClone(const void* other) +{ + const UINT32* src = other; + if (!src) + return NULL; + + UINT32* copy = calloc(1, sizeof(UINT32)); + if (!copy) + return NULL; + + *copy = *src; + return copy; +} + +#if defined(WITH_FUSE) +static CliprdrFuseFile* fuse_file_new_root(CliprdrFileContext* file_context) +{ + CliprdrFuseFile* root_dir = NULL; + + root_dir = fuse_file_new(); + if (!root_dir) + return NULL; + + root_dir->filename_with_root = calloc(2, sizeof(char)); + if (!root_dir->filename_with_root) + { + fuse_file_free(root_dir); + return NULL; + } + + (void)_snprintf(root_dir->filename_with_root, 2, "/"); + root_dir->filename = root_dir->filename_with_root; + + root_dir->ino = FUSE_ROOT_ID; + root_dir->is_directory = TRUE; + root_dir->is_readonly = TRUE; + + if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)root_dir->ino, root_dir)) + { + fuse_file_free(root_dir); + return NULL; + } + + return root_dir; +} +#endif + +CliprdrFileContext* cliprdr_file_context_new(void* context) +{ + CliprdrFileContext* file = calloc(1, sizeof(CliprdrFileContext)); + if (!file) + return NULL; + + file->log = WLog_Get(CLIENT_TAG("common.cliprdr.file")); + file->clipboard = context; + + file->local_streams = HashTable_New(FALSE); + if (!file->local_streams) + goto fail; + + if (!HashTable_SetHashFunction(file->local_streams, UINTPointerHash)) + goto fail; + + wObject* hkobj = HashTable_KeyObject(file->local_streams); + WINPR_ASSERT(hkobj); + hkobj->fnObjectEquals = UINTPointerCompare; + hkobj->fnObjectFree = free; + hkobj->fnObjectNew = UINTPointerClone; + + wObject* hobj = HashTable_ValueObject(file->local_streams); + WINPR_ASSERT(hobj); + hobj->fnObjectFree = cliprdr_local_stream_free; + +#if defined(WITH_FUSE) + file->inode_table = HashTable_New(FALSE); + file->clip_data_table = HashTable_New(FALSE); + file->request_table = HashTable_New(FALSE); + if (!file->inode_table || !file->clip_data_table || !file->request_table) + goto fail; + + { + wObject* ctobj = HashTable_ValueObject(file->request_table); + WINPR_ASSERT(ctobj); + ctobj->fnObjectFree = free; + } + { + wObject* ctobj = HashTable_ValueObject(file->clip_data_table); + WINPR_ASSERT(ctobj); + ctobj->fnObjectFree = clip_data_entry_free; + } + + file->root_dir = fuse_file_new_root(file); + if (!file->root_dir) + goto fail; +#endif + + if (!create_base_path(file)) + goto fail; + +#if defined(WITH_FUSE) + if (!(file->fuse_start_sync = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail; + if (!(file->fuse_stop_sync = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail; + if (!(file->fuse_thread = CreateThread(NULL, 0, cliprdr_file_fuse_thread, file, 0, NULL))) + goto fail; + + if (WaitForSingleObject(file->fuse_start_sync, INFINITE) == WAIT_FAILED) + WLog_Print(file->log, WLOG_ERROR, "Failed to wait for start sync"); +#endif + return file; + +fail: + WINPR_PRAGMA_DIAG_PUSH + WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC + cliprdr_file_context_free(file); + WINPR_PRAGMA_DIAG_POP + return NULL; +} + +BOOL local_stream_discard(const void* key, void* value, void* arg) +{ + CliprdrFileContext* file = arg; + CliprdrLocalStream* stream = value; + WINPR_ASSERT(file); + WINPR_ASSERT(stream); + + if (!stream->locked) + HashTable_Remove(file->local_streams, key); + return TRUE; +} + +BOOL cliprdr_file_context_clear(CliprdrFileContext* file) +{ + WINPR_ASSERT(file); + + WLog_Print(file->log, WLOG_DEBUG, "clear file clipboard..."); + + HashTable_Lock(file->local_streams); + HashTable_Foreach(file->local_streams, local_stream_discard, file); + HashTable_Unlock(file->local_streams); + + memset(file->server_data_hash, 0, sizeof(file->server_data_hash)); + memset(file->client_data_hash, 0, sizeof(file->client_data_hash)); + return TRUE; +} + +BOOL cliprdr_file_context_update_client_data(CliprdrFileContext* file, const char* data, + size_t size) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(file); + if (!cliprdr_file_client_content_changed_and_update(file, data, size)) + return TRUE; + + if (!cliprdr_file_context_clear(file)) + return FALSE; + + UINT32 lockId = file->local_lock_id; + + HashTable_Lock(file->local_streams); + CliprdrLocalStream* stream = HashTable_GetItemValue(file->local_streams, &lockId); + + WLog_Print(file->log, WLOG_DEBUG, "update client file list (stream=%p)...", stream); + if (stream) + rc = cliprdr_local_stream_update(stream, data, size); + else + { + stream = cliprdr_local_stream_new(file, lockId, data, size); + rc = HashTable_Insert(file->local_streams, &stream->lockId, stream); + if (!rc) + cliprdr_local_stream_free(stream); + } + // HashTable_Insert owns stream + // NOLINTNEXTLINE(clang-analyzer-unix.Malloc) + HashTable_Unlock(file->local_streams); + return rc; +} + +UINT32 cliprdr_file_context_current_flags(CliprdrFileContext* file) +{ + WINPR_ASSERT(file); + + if ((file->file_capability_flags & CB_STREAM_FILECLIP_ENABLED) == 0) + return 0; + + if (!file->file_formats_registered) + return 0; + + return CB_STREAM_FILECLIP_ENABLED | CB_FILECLIP_NO_FILE_PATHS | + CB_HUGE_FILE_SUPPORT_ENABLED; // | CB_CAN_LOCK_CLIPDATA; +} + +BOOL cliprdr_file_context_set_locally_available(CliprdrFileContext* file, BOOL available) +{ + WINPR_ASSERT(file); + file->file_formats_registered = available; + return TRUE; +} + +BOOL cliprdr_file_context_remote_set_flags(CliprdrFileContext* file, UINT32 flags) +{ + WINPR_ASSERT(file); + file->file_capability_flags = flags; + return TRUE; +} + +UINT32 cliprdr_file_context_remote_get_flags(CliprdrFileContext* file) +{ + WINPR_ASSERT(file); + return file->file_capability_flags; +} + +BOOL cliprdr_file_context_has_local_support(CliprdrFileContext* file) +{ + WINPR_UNUSED(file); + +#if defined(WITH_FUSE) + return TRUE; +#else + return FALSE; +#endif +} diff --git a/local-test-freerdp-full-01/afc-freerdp/client/common/cmdline.c b/local-test-freerdp-full-01/afc-freerdp/client/common/cmdline.c new file mode 100644 index 0000000000000000000000000000000000000000..bb1f2bcaf759d1a31a48296e84a2afb803e15fde --- /dev/null +++ b/local-test-freerdp-full-01/afc-freerdp/client/common/cmdline.c @@ -0,0 +1,6233 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Client Command-Line Interface + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2014 Norbert Federa + * Copyright 2016 Armin Novak + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CHANNEL_AINPUT_CLIENT) +#include +#endif + +#include +#include + +#include +#include +#include + +#include +#include "cmdline.h" + +#include +#define TAG CLIENT_TAG("common.cmdline") + +static const char str_force[] = "force"; + +static const char* option_starts_with(const char* what, const char* val); +static BOOL option_ends_with(const char* str, const char* ext); +static BOOL option_equals(const char* what, const char* val); + +static BOOL freerdp_client_print_codepages(const char* arg) +{ + size_t count = 0; + DWORD column = 2; + const char* filter = NULL; + RDP_CODEPAGE* pages = NULL; + + if (arg) + { + filter = strchr(arg, ','); + if (!filter) + filter = arg; + else + filter++; + } + pages = freerdp_keyboard_get_matching_codepages(column, filter, &count); + if (!pages) + return TRUE; + + printf("%-10s %-8s %-60s %-36s %-48s\n", "", "", "", "", + ""); + for (size_t x = 0; x < count; x++) + { + const RDP_CODEPAGE* page = &pages[x]; + char buffer[2048] = { 0 }; + + if (strnlen(page->subLanguageSymbol, ARRAYSIZE(page->subLanguageSymbol)) > 0) + (void)_snprintf(buffer, sizeof(buffer), "[%s|%s]", page->primaryLanguageSymbol, + page->subLanguageSymbol); + else + (void)_snprintf(buffer, sizeof(buffer), "[%s]", page->primaryLanguageSymbol); + printf("id=0x%04" PRIx16 ": [%-6s] %-60s %-36s %-48s\n", page->id, page->locale, buffer, + page->primaryLanguage, page->subLanguage); + } + freerdp_codepages_free(pages); + return TRUE; +} + +static BOOL freerdp_path_valid(const char* path, BOOL* special) +{ + const char DynamicDrives[] = "DynamicDrives"; + BOOL isPath = FALSE; + BOOL isSpecial = 0; + if (!path) + return FALSE; + + isSpecial = + (option_equals("*", path) || option_equals(DynamicDrives, path) || option_equals("%", path)) + ? TRUE + : FALSE; + if (!isSpecial) + isPath = winpr_PathFileExists(path); + + if (special) + *special = isSpecial; + + return isSpecial || isPath; +} + +static BOOL freerdp_sanitize_drive_name(char* name, const char* invalid, const char* replacement) +{ + if (!name || !invalid || !replacement) + return FALSE; + if (strlen(invalid) != strlen(replacement)) + return FALSE; + + while (*invalid != '\0') + { + const char what = *invalid++; + const char with = *replacement++; + + char* cur = name; + while ((cur = strchr(cur, what)) != NULL) + *cur = with; + } + return TRUE; +} + +static char* name_from_path(const char* path) +{ + const char* name = "NULL"; + if (path) + { + if (option_equals("%", path)) + name = "home"; + else if (option_equals("*", path)) + name = "hotplug-all"; + else if (option_equals("DynamicDrives", path)) + name = "hotplug"; + else + name = path; + } + return _strdup(name); +} + +static BOOL freerdp_client_add_drive(rdpSettings* settings, const char* path, const char* name) +{ + char* dname = NULL; + RDPDR_DEVICE* device = NULL; + + if (name) + { + BOOL skip = FALSE; + if (path) + { + switch (path[0]) + { + case '*': + case '%': + skip = TRUE; + break; + default: + break; + } + } + /* Path was entered as secondary argument, swap */ + if (!skip && winpr_PathFileExists(name)) + { + if (!winpr_PathFileExists(path) || (!PathIsRelativeA(name) && PathIsRelativeA(path))) + { + const char* tmp = path; + path = name; + name = tmp; + } + } + } + + if (name) + dname = _strdup(name); + else /* We need a name to send to the server. */ + dname = name_from_path(path); + + if (freerdp_sanitize_drive_name(dname, "\\/", "__")) + { + const char* args[] = { dname, path }; + device = freerdp_device_new(RDPDR_DTYP_FILESYSTEM, ARRAYSIZE(args), args); + } + free(dname); + if (!device) + goto fail; + + if (!path) + goto fail; + + { + BOOL isSpecial = FALSE; + BOOL isPath = freerdp_path_valid(path, &isSpecial); + + if (!isPath && !isSpecial) + { + WLog_WARN(TAG, "Invalid drive to redirect: '%s' does not exist, skipping.", path); + freerdp_device_free(device); + } + else if (!freerdp_device_collection_add(settings, device)) + goto fail; + } + + return TRUE; + +fail: + freerdp_device_free(device); + return FALSE; +} + +static BOOL value_to_int(const char* value, LONGLONG* result, LONGLONG min, LONGLONG max) +{ + long long rc = 0; + + if (!value || !result) + return FALSE; + + errno = 0; + rc = _strtoi64(value, NULL, 0); + + if (errno != 0) + return FALSE; + + if ((rc < min) || (rc > max)) + return FALSE; + + *result = rc; + return TRUE; +} + +static BOOL value_to_uint(const char* value, ULONGLONG* result, ULONGLONG min, ULONGLONG max) +{ + unsigned long long rc = 0; + + if (!value || !result) + return FALSE; + + errno = 0; + rc = _strtoui64(value, NULL, 0); + + if (errno != 0) + return FALSE; + + if ((rc < min) || (rc > max)) + return FALSE; + + *result = rc; + return TRUE; +} + +BOOL freerdp_client_print_version(void) +{ + printf("This is FreeRDP version %s (%s)\n", FREERDP_VERSION_FULL, FREERDP_GIT_REVISION); + return TRUE; +} + +BOOL freerdp_client_print_version_ex(int argc, char** argv) +{ + WINPR_ASSERT(argc >= 0); + WINPR_ASSERT(argv || (argc == 0)); + const char* name = (argc > 0) ? argv[0] : "argc < 1"; + printf("This is FreeRDP version [%s] %s (%s)\n", name, FREERDP_VERSION_FULL, + FREERDP_GIT_REVISION); + return TRUE; +} + +BOOL freerdp_client_print_buildconfig(void) +{ + printf("%s", freerdp_get_build_config()); + return TRUE; +} + +BOOL freerdp_client_print_buildconfig_ex(int argc, char** argv) +{ + WINPR_ASSERT(argc >= 0); + WINPR_ASSERT(argv || (argc == 0)); + const char* name = (argc > 0) ? argv[0] : "argc < 1"; + printf("[%s] %s", name, freerdp_get_build_config()); + return TRUE; +} + +static void freerdp_client_print_scancodes(void) +{ + printf("RDP scancodes and their name for use with /kbd:remap\n"); + + for (UINT32 x = 0; x < UINT16_MAX; x++) + { + const char* name = freerdp_keyboard_scancode_name(x); + if (name) + printf("0x%04" PRIx32 " --> %s\n", x, name); + } +} + +static BOOL is_delimiter(char c, const char* delimiters) +{ + char d = 0; + while ((d = *delimiters++) != '\0') + { + if (c == d) + return TRUE; + } + return FALSE; +} + +static const char* get_last(const char* start, size_t len, const char* delimiters) +{ + const char* last = NULL; + for (size_t x = 0; x < len; x++) + { + char c = start[x]; + if (is_delimiter(c, delimiters)) + last = &start[x]; + } + return last; +} + +static SSIZE_T next_delimiter(const char* text, size_t len, size_t max, const char* delimiters) +{ + if (len < max) + return -1; + + const char* last = get_last(text, max, delimiters); + if (!last) + return -1; + + return (SSIZE_T)(last - text); +} + +static SSIZE_T forced_newline_at(const char* text, size_t len, size_t limit, + const char* force_newline) +{ + char d = 0; + while ((d = *force_newline++) != '\0') + { + const char* tok = strchr(text, d); + if (tok) + { + const size_t offset = WINPR_ASSERTING_INT_CAST(size_t, tok - text); + if ((offset > len) || (offset > limit)) + continue; + return (SSIZE_T)(offset); + } + } + return -1; +} + +static BOOL print_align(size_t start_offset, size_t* current) +{ + WINPR_ASSERT(current); + if (*current < start_offset) + { + const int rc = printf("%*c", (int)(start_offset - *current), ' '); + if (rc < 0) + return FALSE; + *current += (size_t)rc; + } + return TRUE; +} + +static char* print_token(char* text, size_t start_offset, size_t* current, size_t limit, + const char* delimiters, const char* force_newline) +{ + int rc = 0; + const size_t tlen = strnlen(text, limit); + size_t len = tlen; + const SSIZE_T force_at = forced_newline_at(text, len, limit - *current, force_newline); + BOOL isForce = (force_at >= 0); + + if (isForce) + len = MIN(len, (size_t)force_at); + + if (!print_align(start_offset, current)) + return NULL; + + const SSIZE_T delim = next_delimiter(text, len, limit - *current, delimiters); + const BOOL isDelim = delim > 0; + if (isDelim) + { + len = MIN(len, (size_t)delim + 1); + } + + rc = printf("%.*s", (int)len, text); + if (rc < 0) + return NULL; + + if (isForce || isDelim) + { + printf("\n"); + *current = 0; + + const size_t offset = len + ((isForce && (force_at == 0)) ? 1 : 0); + return &text[offset]; + } + + *current += (size_t)rc; + + if (tlen == (size_t)rc) + return NULL; + return &text[(size_t)rc]; +} + +static size_t print_optionals(const char* text, size_t start_offset, size_t current) +{ + const size_t limit = 80; + char* str = _strdup(text); + char* cur = str; + + do + { + cur = print_token(cur, start_offset + 1, ¤t, limit, "[], ", "\r\n"); + } while (cur != NULL); + + free(str); + return current; +} + +static size_t print_description(const char* text, size_t start_offset, size_t current) +{ + const size_t limit = 80; + char* str = _strdup(text); + char* cur = str; + + while (cur != NULL) + cur = print_token(cur, start_offset, ¤t, limit, " ", "\r\n"); + + free(str); + const int rc = printf("\n"); + if (rc >= 0) + { + const size_t src = WINPR_ASSERTING_INT_CAST(size_t, rc); + WINPR_ASSERT(SIZE_MAX - src > current); + current += src; + } + return current; +} + +static int cmp_cmdline_args(const void* pva, const void* pvb) +{ + const COMMAND_LINE_ARGUMENT_A* a = (const COMMAND_LINE_ARGUMENT_A*)pva; + const COMMAND_LINE_ARGUMENT_A* b = (const COMMAND_LINE_ARGUMENT_A*)pvb; + + if (!a->Name && !b->Name) + return 0; + if (!a->Name) + return 1; + if (!b->Name) + return -1; + return strcmp(a->Name, b->Name); +} + +static void freerdp_client_print_command_line_args(COMMAND_LINE_ARGUMENT_A* parg, size_t count) +{ + if (!parg) + return; + + qsort(parg, count, sizeof(COMMAND_LINE_ARGUMENT_A), cmp_cmdline_args); + + const COMMAND_LINE_ARGUMENT_A* arg = parg; + do + { + int rc = 0; + size_t pos = 0; + const size_t description_offset = 30 + 8; + + if (arg->Flags & (COMMAND_LINE_VALUE_BOOL | COMMAND_LINE_VALUE_FLAG)) + { + if ((arg->Flags & (uint32_t)~COMMAND_LINE_VALUE_BOOL) == 0) + rc = printf(" %s%s", arg->Default ? "-" : "+", arg->Name); + else if ((arg->Flags & COMMAND_LINE_VALUE_OPTIONAL) != 0) + rc = printf(" [%s|/]%s", arg->Default ? "-" : "+", arg->Name); + else + { + rc = printf(" %s%s", arg->Default ? "-" : "+", arg->Name); + } + } + else + rc = printf(" /%s", arg->Name); + + if (rc < 0) + return; + pos += (size_t)rc; + + if ((arg->Flags & COMMAND_LINE_VALUE_REQUIRED) || + (arg->Flags & COMMAND_LINE_VALUE_OPTIONAL)) + { + if (arg->Format) + { + if (arg->Flags & COMMAND_LINE_VALUE_OPTIONAL) + { + rc = printf("[:"); + if (rc < 0) + return; + pos += (size_t)rc; + pos = print_optionals(arg->Format, pos, pos); + rc = printf("]"); + if (rc < 0) + return; + pos += (size_t)rc; + } + else + { + rc = printf(":"); + if (rc < 0) + return; + pos += (size_t)rc; + pos = print_optionals(arg->Format, pos, pos); + } + + if (pos > description_offset) + { + printf("\n"); + pos = 0; + } + } + } + + rc = printf("%*c", (int)(description_offset - pos), ' '); + if (rc < 0) + return; + pos += (size_t)rc; + + if (arg->Flags & COMMAND_LINE_VALUE_BOOL) + { + rc = printf("%s ", arg->Default ? "Disable" : "Enable"); + if (rc < 0) + return; + pos += (size_t)rc; + } + + print_description(arg->Text, description_offset, pos); + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); +} + +BOOL freerdp_client_print_command_line_help(int argc, char** argv) +{ + return freerdp_client_print_command_line_help_ex(argc, argv, NULL); +} + +static COMMAND_LINE_ARGUMENT_A* create_merged_args(const COMMAND_LINE_ARGUMENT_A* custom, + SSIZE_T count, size_t* pcount) +{ + WINPR_ASSERT(pcount); + if (count < 0) + { + const COMMAND_LINE_ARGUMENT_A* cur = custom; + count = 0; + while (cur && cur->Name) + { + count++; + cur++; + } + } + + COMMAND_LINE_ARGUMENT_A* largs = + calloc((size_t)count + ARRAYSIZE(global_cmd_args), sizeof(COMMAND_LINE_ARGUMENT_A)); + *pcount = 0; + if (!largs) + return NULL; + + size_t lcount = 0; + const COMMAND_LINE_ARGUMENT_A* cur = custom; + while (cur && cur->Name) + { + largs[lcount++] = *cur++; + } + + cur = global_cmd_args; + while (cur && cur->Name) + { + largs[lcount++] = *cur++; + } + *pcount = lcount; + return largs; +} + +BOOL freerdp_client_print_command_line_help_ex(int argc, char** argv, + const COMMAND_LINE_ARGUMENT_A* custom) +{ + const char* name = "FreeRDP"; + + /* allocate a merged copy of implementation defined and default arguments */ + size_t lcount = 0; + COMMAND_LINE_ARGUMENT_A* largs = create_merged_args(custom, -1, &lcount); + if (!largs) + return FALSE; + + if (argc > 0) + name = argv[0]; + + printf("\n"); + printf("FreeRDP - A Free Remote Desktop Protocol Implementation\n"); + printf("See www.freerdp.com for more information\n"); + printf("\n"); + printf("Usage: %s [file] [options] [/v:[:port]]\n", argv[0]); + printf("\n"); + printf("Syntax:\n"); + printf(" /flag (enables flag)\n"); + printf(" /option: (specifies option with value)\n"); + printf(" +toggle -toggle (enables or disables toggle, where '/' is a synonym of '+')\n"); + printf("\n"); + + freerdp_client_print_command_line_args(largs, lcount); + free(largs); + + printf("\n"); + printf("Examples:\n"); + printf(" %s connection.rdp /p:Pwd123! /f\n", name); + printf(" %s /u:CONTOSO\\JohnDoe /p:Pwd123! /v:rdp.contoso.com\n", name); + printf(" %s /u:JohnDoe /p:Pwd123! /w:1366 /h:768 /v:192.168.1.100:4489\n", name); + printf(" %s /u:JohnDoe /p:Pwd123! /vmconnect:C824F53E-95D2-46C6-9A18-23A5BB403532 " + "/v:192.168.1.100\n", + name); + printf(" %s /u:\\AzureAD\\user@corp.example /p:pwd /v:host\n", name); + printf("\n"); + printf("Clipboard Redirection: +clipboard\n"); + printf("\n"); + printf("Drive Redirection: /drive:home,/home/user\n"); + printf("Smartcard Redirection: /smartcard:\n"); + printf("Smartcard logon with Kerberos authentication: /smartcard-logon /sec:nla\n"); + +#if defined(CHANNEL_SERIAL_CLIENT) + printf("Serial Port Redirection: /serial:,,[SerCx2|SerCx|Serial],[permissive]\n"); + printf("Serial Port Redirection: /serial:COM1,/dev/ttyS0\n"); +#endif +#if defined(CHANNEL_PARALLEL_CLIENT) + printf("Parallel Port Redirection: /parallel:,\n"); +#endif + printf("Printer Redirection: /printer:,,[default]\n"); + printf("TCP redirection: /rdp2tcp:/usr/bin/rdp2tcp\n"); + printf("\n"); + printf("Audio Output Redirection: /sound:sys:oss,dev:1,format:1\n"); + printf("Audio Output Redirection: /sound:sys:alsa\n"); + printf("Audio Input Redirection: /microphone:sys:oss,dev:1,format:1\n"); + printf("Audio Input Redirection: /microphone:sys:alsa\n"); + printf("\n"); + printf("Multimedia Redirection: /video\n"); +#ifdef CHANNEL_URBDRC_CLIENT + printf("USB Device Redirection: /usb:id:054c:0268#4669:6e6b,addr:04:0c\n"); +#endif + printf("\n"); + printf("For Gateways, the https_proxy environment variable is respected:\n"); +#ifdef _WIN32 + printf(" set HTTPS_PROXY=http://proxy.contoso.com:3128/\n"); +#else + printf(" export https_proxy=http://proxy.contoso.com:3128/\n"); +#endif + printf(" %s /g:rdp.contoso.com ...\n", name); + printf("\n"); + printf("More documentation is coming, in the meantime consult source files\n"); + printf("\n"); + return TRUE; +} + +static BOOL option_is_rdp_file(const char* option) +{ + WINPR_ASSERT(option); + + if (option_ends_with(option, ".rdp")) + return TRUE; + if (option_ends_with(option, ".rdpw")) + return TRUE; + return FALSE; +} + +static BOOL option_is_incident_file(const char* option) +{ + WINPR_ASSERT(option); + + if (option_ends_with(option, ".msrcIncident")) + return TRUE; + return FALSE; +} + +static int freerdp_client_command_line_pre_filter(void* context, int index, int argc, LPSTR* argv) +{ + if (index == 1) + { + size_t length = 0; + rdpSettings* settings = NULL; + + if (argc <= index) + return -1; + + length = strlen(argv[index]); + + if (length > 4) + { + if (option_is_rdp_file(argv[index])) + { + settings = (rdpSettings*)context; + + if (!freerdp_settings_set_string(settings, FreeRDP_ConnectionFile, argv[index])) + return COMMAND_LINE_ERROR_MEMORY; + + return 1; + } + } + + if (length > 13) + { + if (option_is_incident_file(argv[index])) + { + settings = (rdpSettings*)context; + + if (!freerdp_settings_set_string(settings, FreeRDP_AssistanceFile, argv[index])) + return COMMAND_LINE_ERROR_MEMORY; + + return 1; + } + } + } + + return 0; +} + +BOOL freerdp_client_add_device_channel(rdpSettings* settings, size_t count, + const char* const* params) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(params); + WINPR_ASSERT(count > 0); + + if (option_equals(params[0], "drive")) + { + BOOL rc = 0; + if (count < 2) + return FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + if (count < 3) + rc = freerdp_client_add_drive(settings, params[1], NULL); + else + rc = freerdp_client_add_drive(settings, params[2], params[1]); + + return rc; + } + else if (option_equals(params[0], "printer")) + { + RDPDR_DEVICE* printer = NULL; + + if (count < 1) + return FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectPrinters, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + + printer = freerdp_device_new(RDPDR_DTYP_PRINT, count - 1, ¶ms[1]); + if (!printer) + return FALSE; + + if (!freerdp_device_collection_add(settings, printer)) + { + freerdp_device_free(printer); + return FALSE; + } + + return TRUE; + } + else if (option_equals(params[0], "smartcard")) + { + RDPDR_DEVICE* smartcard = NULL; + + if (count < 1) + return FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectSmartCards, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + + smartcard = freerdp_device_new(RDPDR_DTYP_SMARTCARD, count - 1, ¶ms[1]); + + if (!smartcard) + return FALSE; + + if (!freerdp_device_collection_add(settings, smartcard)) + { + freerdp_device_free(smartcard); + return FALSE; + } + + return TRUE; + } +#if defined(CHANNEL_SERIAL_CLIENT) + else if (option_equals(params[0], "serial")) + { + RDPDR_DEVICE* serial = NULL; + + if (count < 1) + return FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectSerialPorts, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + + serial = freerdp_device_new(RDPDR_DTYP_SERIAL, count - 1, ¶ms[1]); + + if (!serial) + return FALSE; + + if (!freerdp_device_collection_add(settings, serial)) + { + freerdp_device_free(serial); + return FALSE; + } + + return TRUE; + } +#endif + else if (option_equals(params[0], "parallel")) + { + RDPDR_DEVICE* parallel = NULL; + + if (count < 1) + return FALSE; + + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectParallelPorts, TRUE)) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + return FALSE; + + parallel = freerdp_device_new(RDPDR_DTYP_PARALLEL, count - 1, ¶ms[1]); + + if (!parallel) + return FALSE; + + if (!freerdp_device_collection_add(settings, parallel)) + { + freerdp_device_free(parallel); + return FALSE; + } + + return TRUE; + } + + return FALSE; +} + +BOOL freerdp_client_del_static_channel(rdpSettings* settings, const char* name) +{ + return freerdp_static_channel_collection_del(settings, name); +} + +BOOL freerdp_client_add_static_channel(rdpSettings* settings, size_t count, + const char* const* params) +{ + ADDIN_ARGV* _args = NULL; + + if (!settings || !params || !params[0] || (count > INT_MAX)) + return FALSE; + + if (freerdp_static_channel_collection_find(settings, params[0])) + return TRUE; + + _args = freerdp_addin_argv_new(count, params); + + if (!_args) + return FALSE; + + if (!freerdp_static_channel_collection_add(settings, _args)) + goto fail; + + return TRUE; +fail: + freerdp_addin_argv_free(_args); + return FALSE; +} + +BOOL freerdp_client_del_dynamic_channel(rdpSettings* settings, const char* name) +{ + return freerdp_dynamic_channel_collection_del(settings, name); +} + +BOOL freerdp_client_add_dynamic_channel(rdpSettings* settings, size_t count, + const char* const* params) +{ + ADDIN_ARGV* _args = NULL; + + if (!settings || !params || !params[0] || (count > INT_MAX)) + return FALSE; + + if (freerdp_dynamic_channel_collection_find(settings, params[0])) + return TRUE; + + _args = freerdp_addin_argv_new(count, params); + + if (!_args) + return FALSE; + + if (!freerdp_dynamic_channel_collection_add(settings, _args)) + goto fail; + + return TRUE; + +fail: + freerdp_addin_argv_free(_args); + return FALSE; +} + +static BOOL read_pem_file(rdpSettings* settings, FreeRDP_Settings_Keys_String id, const char* file) +{ + size_t length = 0; + char* pem = crypto_read_pem(file, &length); + if (!pem || (length == 0)) + { + free(pem); + return FALSE; + } + + BOOL rc = freerdp_settings_set_string_len(settings, id, pem, length); + free(pem); + return rc; +} + +/** @brief suboption type */ +typedef enum +{ + CMDLINE_SUBOPTION_STRING, + CMDLINE_SUBOPTION_FILE, +} CmdLineSubOptionType; + +typedef BOOL (*CmdLineSubOptionCb)(const char* value, rdpSettings* settings); +typedef struct +{ + const char* optname; + FreeRDP_Settings_Keys_String id; + CmdLineSubOptionType opttype; + CmdLineSubOptionCb cb; +} CmdLineSubOptions; + +static BOOL parseSubOptions(rdpSettings* settings, const CmdLineSubOptions* opts, size_t count, + const char* arg) +{ + BOOL found = FALSE; + + for (size_t xx = 0; xx < count; xx++) + { + const CmdLineSubOptions* opt = &opts[xx]; + + if (option_starts_with(opt->optname, arg)) + { + const size_t optlen = strlen(opt->optname); + const char* val = &arg[optlen]; + BOOL status = 0; + + switch (opt->opttype) + { + case CMDLINE_SUBOPTION_STRING: + status = freerdp_settings_set_string(settings, opt->id, val); + break; + case CMDLINE_SUBOPTION_FILE: + status = read_pem_file(settings, opt->id, val); + break; + default: + WLog_ERR(TAG, "invalid subOption type"); + return FALSE; + } + + if (!status) + return FALSE; + + if (opt->cb && !opt->cb(val, settings)) + return FALSE; + + found = TRUE; + break; + } + } + + if (!found) + WLog_ERR(TAG, "option %s not handled", arg); + + return found; +} + +#define fail_at(arg, rc) fail_at_((arg), (rc), __FILE__, __func__, __LINE__) +static int fail_at_(const COMMAND_LINE_ARGUMENT_A* arg, int rc, const char* file, const char* fkt, + size_t line) +{ + const DWORD level = WLOG_ERROR; + wLog* log = WLog_Get(TAG); + if (WLog_IsLevelActive(log, level)) + WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, level, line, file, fkt, + "Command line parsing failed at '%s' value '%s' [%d]", arg->Name, + arg->Value, rc); + return rc; +} + +static int freerdp_client_command_line_post_filter_int(void* context, COMMAND_LINE_ARGUMENT_A* arg) +{ + rdpSettings* settings = (rdpSettings*)context; + int status = CHANNEL_RC_OK; + BOOL enable = arg->Value ? TRUE : FALSE; + + CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "a") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_settings_set_bool(settings, FreeRDP_DeviceRedirection, TRUE)) + status = COMMAND_LINE_ERROR; + + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "kerberos") + { + size_t count = 0; + + char** ptr = CommandLineParseCommaSeparatedValuesEx("kerberos", arg->Value, &count); + if (ptr) + { + const CmdLineSubOptions opts[] = { + { "kdc-url:", FreeRDP_KerberosKdcUrl, CMDLINE_SUBOPTION_STRING, NULL }, + { "start-time:", FreeRDP_KerberosStartTime, CMDLINE_SUBOPTION_STRING, NULL }, + { "lifetime:", FreeRDP_KerberosLifeTime, CMDLINE_SUBOPTION_STRING, NULL }, + { "renewable-lifetime:", FreeRDP_KerberosRenewableLifeTime, + CMDLINE_SUBOPTION_STRING, NULL }, + { "cache:", FreeRDP_KerberosCache, CMDLINE_SUBOPTION_STRING, NULL }, + { "armor:", FreeRDP_KerberosArmor, CMDLINE_SUBOPTION_STRING, NULL }, + { "pkinit-anchors:", FreeRDP_PkinitAnchors, CMDLINE_SUBOPTION_STRING, NULL }, + { "pkcs11-module:", FreeRDP_Pkcs11Module, CMDLINE_SUBOPTION_STRING, NULL } + }; + + for (size_t x = 1; x < count; x++) + { + const char* cur = ptr[x]; + if (!parseSubOptions(settings, opts, ARRAYSIZE(opts), cur)) + { + CommandLineParserFree(ptr); + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + } + } + CommandLineParserFree(ptr); + } + + CommandLineSwitchCase(arg, "vc") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!freerdp_client_add_static_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "dvc") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!freerdp_client_add_dynamic_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "drive") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } +#if defined(CHANNEL_SERIAL_CLIENT) + CommandLineSwitchCase(arg, "serial") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } +#endif +#if defined(CHANNEL_PARALLEL_CLIENT) + CommandLineSwitchCase(arg, "parallel") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } +#endif + CommandLineSwitchCase(arg, "smartcard") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "printer") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(arg->Name, arg->Value, &count); + if (!freerdp_client_add_device_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "usb") + { + size_t count = 0; + char** ptr = + CommandLineParseCommaSeparatedValuesEx(URBDRC_CHANNEL_NAME, arg->Value, &count); + if (!freerdp_client_add_dynamic_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "multitouch") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_MultiTouchInput, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gestures") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_MultiTouchGestures, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "echo") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportEchoChannel, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "ssh-agent") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportSSHAgentChannel, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "disp") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportDisplayControl, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "geometry") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGeometryTracking, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "video") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGeometryTracking, + enable)) /* this requires geometry tracking */ + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportVideoOptimized, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "sound") + { + size_t count = 0; + char** ptr = + CommandLineParseCommaSeparatedValuesEx(RDPSND_CHANNEL_NAME, arg->Value, &count); + if (!freerdp_client_add_static_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_client_add_dynamic_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } + CommandLineSwitchCase(arg, "microphone") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx(AUDIN_CHANNEL_NAME, arg->Value, &count); + if (!freerdp_client_add_dynamic_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } +#if defined(CHANNEL_TSMF_CLIENT) + CommandLineSwitchCase(arg, "multimedia") + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx("tsmf", arg->Value, &count); + if (!freerdp_client_add_dynamic_channel(settings, count, (const char* const*)ptr)) + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineParserFree(ptr); + if (status) + return fail_at(arg, status); + } +#endif + CommandLineSwitchCase(arg, "heartbeat") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportHeartbeatPdu, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "multitransport") + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportMultitransport, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + + UINT32 flags = 0; + if (freerdp_settings_get_bool(settings, FreeRDP_SupportMultitransport)) + flags = + (TRANSPORT_TYPE_UDP_FECR | TRANSPORT_TYPE_UDP_FECL | TRANSPORT_TYPE_UDP_PREFERRED); + + if (!freerdp_settings_set_uint32(settings, FreeRDP_MultitransportFlags, flags)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchEnd(arg) + + return status; +} + +static int freerdp_client_command_line_post_filter(void* context, COMMAND_LINE_ARGUMENT_A* arg) +{ + int status = freerdp_client_command_line_post_filter_int(context, arg); + return status == CHANNEL_RC_OK ? 1 : -1; +} + +static BOOL freerdp_parse_username_ptr(const char* username, const char** user, size_t* userlen, + const char** domain, size_t* domainlen) +{ + WINPR_ASSERT(user); + WINPR_ASSERT(userlen); + WINPR_ASSERT(domain); + WINPR_ASSERT(domainlen); + + if (!username) + return FALSE; + + const char* p = strchr(username, '\\'); + + *user = NULL; + *userlen = 0; + + *domain = NULL; + *domainlen = 0; + + if (p) + { + const size_t length = (size_t)(p - username); + *user = &p[1]; + *userlen = strlen(*user); + + *domain = username; + *domainlen = length; + } + else + { + /* Do not break up the name for '@'; both credSSP and the + * ClientInfo PDU expect 'user@corp.net' to be transmitted + * as username 'user@corp.net', domain empty (not NULL!). + */ + *user = username; + *userlen = strlen(username); + } + + return TRUE; +} + +static BOOL freerdp_parse_username_settings(const char* username, rdpSettings* settings, + FreeRDP_Settings_Keys_String userID, + FreeRDP_Settings_Keys_String domainID) +{ + const char* user = NULL; + const char* domain = NULL; + size_t userlen = 0; + size_t domainlen = 0; + + const BOOL rc = freerdp_parse_username_ptr(username, &user, &userlen, &domain, &domainlen); + if (!rc) + return FALSE; + if (!freerdp_settings_set_string_len(settings, userID, user, userlen)) + return FALSE; + return freerdp_settings_set_string_len(settings, domainID, domain, domainlen); +} + +BOOL freerdp_parse_username(const char* username, char** puser, char** pdomain) +{ + const char* user = NULL; + const char* domain = NULL; + size_t userlen = 0; + size_t domainlen = 0; + + *puser = NULL; + *pdomain = NULL; + + const BOOL rc = freerdp_parse_username_ptr(username, &user, &userlen, &domain, &domainlen); + if (!rc) + return FALSE; + + if (userlen > 0) + { + *puser = strndup(user, userlen); + if (!*puser) + return FALSE; + } + + if (domainlen > 0) + { + *pdomain = strndup(domain, domainlen); + if (!*pdomain) + { + free(*puser); + *puser = NULL; + return FALSE; + } + } + + return TRUE; +} + +BOOL freerdp_parse_hostname(const char* hostname, char** host, int* port) +{ + char* p = NULL; + p = strrchr(hostname, ':'); + + if (p) + { + size_t length = (size_t)(p - hostname); + LONGLONG val = 0; + + if (!value_to_int(p + 1, &val, 1, UINT16_MAX)) + return FALSE; + + *host = (char*)calloc(length + 1UL, sizeof(char)); + + if (!(*host)) + return FALSE; + + CopyMemory(*host, hostname, length); + (*host)[length] = '\0'; + *port = (UINT16)val; + } + else + { + *host = _strdup(hostname); + + if (!(*host)) + return FALSE; + + *port = -1; + } + + return TRUE; +} + +static BOOL freerdp_apply_connection_type(rdpSettings* settings, UINT32 type) +{ + struct network_settings + { + FreeRDP_Settings_Keys_Bool id; + BOOL value[7]; + }; + const struct network_settings config[] = { + { FreeRDP_DisableWallpaper, { TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE } }, + { FreeRDP_AllowFontSmoothing, { FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE } }, + { FreeRDP_AllowDesktopComposition, { FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE } }, + { FreeRDP_DisableFullWindowDrag, { TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE } }, + { FreeRDP_DisableMenuAnims, { TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE } }, + { FreeRDP_DisableThemes, { TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE } } + }; + + switch (type) + { + case CONNECTION_TYPE_INVALID: + return TRUE; + + case CONNECTION_TYPE_MODEM: + case CONNECTION_TYPE_BROADBAND_LOW: + case CONNECTION_TYPE_BROADBAND_HIGH: + case CONNECTION_TYPE_SATELLITE: + case CONNECTION_TYPE_WAN: + case CONNECTION_TYPE_LAN: + case CONNECTION_TYPE_AUTODETECT: + break; + default: + WLog_WARN(TAG, "Unknown ConnectionType %" PRIu32 ", aborting", type); + return FALSE; + } + + for (size_t x = 0; x < ARRAYSIZE(config); x++) + { + const struct network_settings* cur = &config[x]; + if (!freerdp_settings_set_bool(settings, cur->id, cur->value[type - 1])) + return FALSE; + } + return TRUE; +} + +BOOL freerdp_set_connection_type(rdpSettings* settings, UINT32 type) +{ + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ConnectionType, type)) + return FALSE; + + switch (type) + { + case CONNECTION_TYPE_INVALID: + case CONNECTION_TYPE_MODEM: + case CONNECTION_TYPE_BROADBAND_LOW: + case CONNECTION_TYPE_SATELLITE: + case CONNECTION_TYPE_BROADBAND_HIGH: + case CONNECTION_TYPE_WAN: + case CONNECTION_TYPE_LAN: + if (!freerdp_apply_connection_type(settings, type)) + return FALSE; + break; + case CONNECTION_TYPE_AUTODETECT: + if (!freerdp_apply_connection_type(settings, type)) + return FALSE; + /* Automatically activate GFX and RFX codec support */ +#ifdef WITH_GFX_H264 + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GfxH264, TRUE)) + return FALSE; +#endif + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE)) + return FALSE; + break; + default: + WLog_WARN(TAG, "Unknown ConnectionType %" PRIu32 ", aborting", type); + return FALSE; + } + + return TRUE; +} + +static UINT32 freerdp_get_keyboard_layout_for_type(const char* name, DWORD type) +{ + UINT32 res = 0; + size_t count = 0; + RDP_KEYBOARD_LAYOUT* layouts = + freerdp_keyboard_get_layouts(RDP_KEYBOARD_LAYOUT_TYPE_STANDARD, &count); + + if (!layouts || (count == 0)) + goto fail; + + for (size_t x = 0; x < count; x++) + { + const RDP_KEYBOARD_LAYOUT* layout = &layouts[x]; + if (option_equals(layout->name, name)) + { + res = layout->code; + break; + } + } + +fail: + freerdp_keyboard_layouts_free(layouts, count); + return res; +} + +static UINT32 freerdp_map_keyboard_layout_name_to_id(const char* name) +{ + const UINT32 variants[] = { RDP_KEYBOARD_LAYOUT_TYPE_STANDARD, RDP_KEYBOARD_LAYOUT_TYPE_VARIANT, + RDP_KEYBOARD_LAYOUT_TYPE_IME }; + + for (size_t x = 0; x < ARRAYSIZE(variants); x++) + { + UINT32 rc = freerdp_get_keyboard_layout_for_type(name, variants[x]); + if (rc > 0) + return rc; + } + + return 0; +} + +static int freerdp_detect_command_line_pre_filter(void* context, int index, int argc, LPSTR* argv) +{ + size_t length = 0; + WINPR_UNUSED(context); + + if (index == 1) + { + if (argc < index) + return -1; + + length = strlen(argv[index]); + + if (length > 4) + { + if (option_is_rdp_file(argv[index])) + { + return 1; + } + } + + if (length > 13) + { + if (option_is_incident_file(argv[index])) + { + return 1; + } + } + } + + return 0; +} + +static int freerdp_detect_windows_style_command_line_syntax(int argc, char** argv, size_t* count, + BOOL ignoreUnknown) +{ + int status = 0; + DWORD flags = 0; + int detect_status = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + COMMAND_LINE_ARGUMENT_A largs[ARRAYSIZE(global_cmd_args)]; + memcpy(largs, global_cmd_args, sizeof(global_cmd_args)); + + flags = COMMAND_LINE_SEPARATOR_COLON | COMMAND_LINE_SILENCE_PARSER; + flags |= COMMAND_LINE_SIGIL_SLASH | COMMAND_LINE_SIGIL_PLUS_MINUS; + + if (ignoreUnknown) + { + flags |= COMMAND_LINE_IGN_UNKNOWN_KEYWORD; + } + + *count = 0; + detect_status = 0; + CommandLineClearArgumentsA(largs); + status = CommandLineParseArgumentsA(argc, argv, largs, flags, NULL, + freerdp_detect_command_line_pre_filter, NULL); + + if (status < 0) + return status; + + arg = largs; + + do + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + (*count)++; + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + return detect_status; +} + +static int freerdp_detect_posix_style_command_line_syntax(int argc, char** argv, size_t* count, + BOOL ignoreUnknown) +{ + int status = 0; + DWORD flags = 0; + int detect_status = 0; + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + COMMAND_LINE_ARGUMENT_A largs[ARRAYSIZE(global_cmd_args)]; + memcpy(largs, global_cmd_args, sizeof(global_cmd_args)); + + flags = COMMAND_LINE_SEPARATOR_SPACE | COMMAND_LINE_SILENCE_PARSER; + flags |= COMMAND_LINE_SIGIL_DASH | COMMAND_LINE_SIGIL_DOUBLE_DASH; + flags |= COMMAND_LINE_SIGIL_ENABLE_DISABLE; + + if (ignoreUnknown) + { + flags |= COMMAND_LINE_IGN_UNKNOWN_KEYWORD; + } + + *count = 0; + detect_status = 0; + CommandLineClearArgumentsA(largs); + status = CommandLineParseArgumentsA(argc, argv, largs, flags, NULL, + freerdp_detect_command_line_pre_filter, NULL); + + if (status < 0) + return status; + + arg = largs; + + do + { + if (!(arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + continue; + + (*count)++; + } while ((arg = CommandLineFindNextArgumentA(arg)) != NULL); + + return detect_status; +} + +static BOOL freerdp_client_detect_command_line(int argc, char** argv, DWORD* flags) +{ + size_t posix_cli_count = 0; + size_t windows_cli_count = 0; + const BOOL ignoreUnknown = TRUE; + const int windows_cli_status = freerdp_detect_windows_style_command_line_syntax( + argc, argv, &windows_cli_count, ignoreUnknown); + const int posix_cli_status = + freerdp_detect_posix_style_command_line_syntax(argc, argv, &posix_cli_count, ignoreUnknown); + + /* Default is POSIX syntax */ + *flags = COMMAND_LINE_SEPARATOR_SPACE; + *flags |= COMMAND_LINE_SIGIL_DASH | COMMAND_LINE_SIGIL_DOUBLE_DASH; + *flags |= COMMAND_LINE_SIGIL_ENABLE_DISABLE; + + if (posix_cli_status <= COMMAND_LINE_STATUS_PRINT) + return FALSE; + + /* Check, if this may be windows style syntax... */ + if ((windows_cli_count && (windows_cli_count >= posix_cli_count)) || + (windows_cli_status <= COMMAND_LINE_STATUS_PRINT)) + { + windows_cli_count = 1; + *flags = COMMAND_LINE_SEPARATOR_COLON; + *flags |= COMMAND_LINE_SIGIL_SLASH | COMMAND_LINE_SIGIL_PLUS_MINUS; + } + + WLog_DBG(TAG, "windows: %d/%" PRIuz " posix: %d/%" PRIuz "", windows_cli_status, + windows_cli_count, posix_cli_status, posix_cli_count); + if ((posix_cli_count == 0) && (windows_cli_count == 0)) + { + if ((posix_cli_status == COMMAND_LINE_ERROR) && (windows_cli_status == COMMAND_LINE_ERROR)) + return TRUE; + } + return FALSE; +} + +int freerdp_client_settings_command_line_status_print(rdpSettings* settings, int status, int argc, + char** argv) +{ + return freerdp_client_settings_command_line_status_print_ex(settings, status, argc, argv, NULL); +} + +static void freerdp_client_print_keyboard_type_list(const char* msg, DWORD type) +{ + size_t count = 0; + RDP_KEYBOARD_LAYOUT* layouts = NULL; + layouts = freerdp_keyboard_get_layouts(type, &count); + + printf("\n%s\n", msg); + + for (size_t x = 0; x < count; x++) + { + const RDP_KEYBOARD_LAYOUT* layout = &layouts[x]; + printf("0x%08" PRIX32 "\t%s\n", layout->code, layout->name); + } + + freerdp_keyboard_layouts_free(layouts, count); +} + +static void freerdp_client_print_keyboard_list(void) +{ + freerdp_client_print_keyboard_type_list("Keyboard Layouts", RDP_KEYBOARD_LAYOUT_TYPE_STANDARD); + freerdp_client_print_keyboard_type_list("Keyboard Layout Variants", + RDP_KEYBOARD_LAYOUT_TYPE_VARIANT); + freerdp_client_print_keyboard_type_list("Keyboard Layout Variants", + RDP_KEYBOARD_LAYOUT_TYPE_IME); +} + +static void freerdp_client_print_timezone_list(void) +{ + DWORD index = 0; + DYNAMIC_TIME_ZONE_INFORMATION info = { 0 }; + while (EnumDynamicTimeZoneInformation(index++, &info) != ERROR_NO_MORE_ITEMS) + { + char TimeZoneKeyName[ARRAYSIZE(info.TimeZoneKeyName) + 1] = { 0 }; + + (void)ConvertWCharNToUtf8(info.TimeZoneKeyName, ARRAYSIZE(info.TimeZoneKeyName), + TimeZoneKeyName, ARRAYSIZE(TimeZoneKeyName)); + printf("%" PRIu32 ": '%s'\n", index, TimeZoneKeyName); + } +} + +static void freerdp_client_print_tune_list(const rdpSettings* settings) +{ + SSIZE_T type = 0; + + for (SSIZE_T x = 0; x < FreeRDP_Settings_StableAPI_MAX; x++) + { + const char* name = freerdp_settings_get_name_for_key(x); + type = freerdp_settings_get_type_for_key(x); + + // NOLINTBEGIN(clang-analyzer-optin.core.EnumCastOutOfRange) + switch (type) + { + case RDP_SETTINGS_TYPE_BOOL: + printf("%" PRIdz "\t%50s\tBOOL\t%s\n", x, name, + freerdp_settings_get_bool(settings, (FreeRDP_Settings_Keys_Bool)x) + ? "TRUE" + : "FALSE"); + break; + case RDP_SETTINGS_TYPE_UINT16: + printf("%" PRIdz "\t%50s\tUINT16\t%" PRIu16 "\n", x, name, + freerdp_settings_get_uint16(settings, (FreeRDP_Settings_Keys_UInt16)x)); + break; + case RDP_SETTINGS_TYPE_INT16: + printf("%" PRIdz "\t%50s\tINT16\t%" PRId16 "\n", x, name, + freerdp_settings_get_int16(settings, (FreeRDP_Settings_Keys_Int16)x)); + break; + case RDP_SETTINGS_TYPE_UINT32: + printf("%" PRIdz "\t%50s\tUINT32\t%" PRIu32 "\n", x, name, + freerdp_settings_get_uint32(settings, (FreeRDP_Settings_Keys_UInt32)x)); + break; + case RDP_SETTINGS_TYPE_INT32: + printf("%" PRIdz "\t%50s\tINT32\t%" PRId32 "\n", x, name, + freerdp_settings_get_int32(settings, (FreeRDP_Settings_Keys_Int32)x)); + break; + case RDP_SETTINGS_TYPE_UINT64: + printf("%" PRIdz "\t%50s\tUINT64\t%" PRIu64 "\n", x, name, + freerdp_settings_get_uint64(settings, (FreeRDP_Settings_Keys_UInt64)x)); + break; + case RDP_SETTINGS_TYPE_INT64: + printf("%" PRIdz "\t%50s\tINT64\t%" PRId64 "\n", x, name, + freerdp_settings_get_int64(settings, (FreeRDP_Settings_Keys_Int64)x)); + break; + case RDP_SETTINGS_TYPE_STRING: + printf("%" PRIdz "\t%50s\tSTRING\t%s" + "\n", + x, name, + freerdp_settings_get_string(settings, (FreeRDP_Settings_Keys_String)x)); + break; + case RDP_SETTINGS_TYPE_POINTER: + printf("%" PRIdz "\t%50s\tPOINTER\t%p" + "\n", + x, name, + freerdp_settings_get_pointer(settings, (FreeRDP_Settings_Keys_Pointer)x)); + break; + default: + break; + } + // NOLINTEND(clang-analyzer-optin.core.EnumCastOutOfRange) + } +} + +int freerdp_client_settings_command_line_status_print_ex(rdpSettings* settings, int status, + int argc, char** argv, + const COMMAND_LINE_ARGUMENT_A* custom) +{ + const COMMAND_LINE_ARGUMENT_A* arg = NULL; + COMMAND_LINE_ARGUMENT_A largs[ARRAYSIZE(global_cmd_args)]; + memcpy(largs, global_cmd_args, sizeof(global_cmd_args)); + + if (status == COMMAND_LINE_STATUS_PRINT_VERSION) + { + freerdp_client_print_version(); + goto out; + } + + if (status == COMMAND_LINE_STATUS_PRINT_BUILDCONFIG) + { + freerdp_client_print_version_ex(argc, argv); + freerdp_client_print_buildconfig_ex(argc, argv); + goto out; + } + else if (status == COMMAND_LINE_STATUS_PRINT) + { + (void)CommandLineParseArgumentsA(argc, argv, largs, 0x112, NULL, NULL, NULL); + + arg = CommandLineFindArgumentA(largs, "list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT) + { + if (option_equals("timezones", arg->Value)) + freerdp_client_print_timezone_list(); + else if (option_equals("tune", arg->Value)) + freerdp_client_print_tune_list(settings); + else if (option_equals("kbd", arg->Value)) + freerdp_client_print_keyboard_list(); + else if (option_starts_with("kbd-lang", arg->Value)) + { + const char* val = NULL; + if (option_starts_with("kbd-lang:", arg->Value)) + val = &arg->Value[9]; + else if (!option_equals("kbd-lang", arg->Value)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (val && strchr(val, ',')) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + freerdp_client_print_codepages(val); + } + else if (option_equals("kbd-scancode", arg->Value)) + freerdp_client_print_scancodes(); + else if (option_equals("monitor", arg->Value)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_ListMonitors, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_starts_with("smartcard", arg->Value)) + { + BOOL opts = FALSE; + if (option_starts_with("smartcard:", arg->Value)) + opts = TRUE; + else if (!option_equals("smartcard", arg->Value)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (opts) + { + const char* sub = strchr(arg->Value, ':') + 1; + const CmdLineSubOptions options[] = { + { "pkinit-anchors:", FreeRDP_PkinitAnchors, CMDLINE_SUBOPTION_STRING, + NULL }, + { "pkcs11-module:", FreeRDP_Pkcs11Module, CMDLINE_SUBOPTION_STRING, NULL } + }; + + size_t count = 0; + + char** ptr = CommandLineParseCommaSeparatedValuesEx("smartcard", sub, &count); + if (!ptr) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (count < 2) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + for (size_t x = 1; x < count; x++) + { + const char* cur = ptr[x]; + if (!parseSubOptions(settings, options, ARRAYSIZE(options), cur)) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + + CommandLineParserFree(ptr); + } + + freerdp_smartcard_list(settings); + } + else + { + freerdp_client_print_command_line_help_ex(argc, argv, custom); + return COMMAND_LINE_ERROR; + } + } +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) + arg = CommandLineFindArgumentA(largs, "tune-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT) + { + WLog_WARN(TAG, "Option /tune-list is deprecated, use /list:tune instead"); + freerdp_client_print_tune_list(settings); + } + + arg = CommandLineFindArgumentA(largs, "kbd-lang-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT) + { + WLog_WARN(TAG, "Option /kbd-lang-list is deprecated, use /list:kbd-lang instead"); + freerdp_client_print_codepages(arg->Value); + } + + arg = CommandLineFindArgumentA(largs, "kbd-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + WLog_WARN(TAG, "Option /kbd-list is deprecated, use /list:kbd instead"); + freerdp_client_print_keyboard_list(); + } + + arg = CommandLineFindArgumentA(largs, "monitor-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + WLog_WARN(TAG, "Option /monitor-list is deprecated, use /list:monitor instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_ListMonitors, TRUE)) + return COMMAND_LINE_ERROR; + } + + arg = CommandLineFindArgumentA(largs, "smartcard-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + WLog_WARN(TAG, "Option /smartcard-list is deprecated, use /list:smartcard instead"); + freerdp_smartcard_list(settings); + } + + arg = CommandLineFindArgumentA(largs, "kbd-scancode-list"); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + WLog_WARN(TAG, + "Option /kbd-scancode-list is deprecated, use /list:kbd-scancode instead"); + freerdp_client_print_scancodes(); + goto out; + } +#endif + goto out; + } + else if (status < 0) + { + freerdp_client_print_command_line_help_ex(argc, argv, custom); + goto out; + } + +out: + if (status <= COMMAND_LINE_STATUS_PRINT && status >= COMMAND_LINE_STATUS_PRINT_LAST) + return 0; + return status; +} + +/** + * parses a string value with the format x + * + * @param input input string + * @param v1 pointer to output v1 + * @param v2 pointer to output v2 + * @return if the parsing was successful + */ +static BOOL parseSizeValue(const char* input, unsigned long* v1, unsigned long* v2) +{ + const char* xcharpos = NULL; + char* endPtr = NULL; + unsigned long v = 0; + errno = 0; + v = strtoul(input, &endPtr, 10); + + if ((v == 0 || v == ULONG_MAX) && (errno != 0)) + return FALSE; + + if (v1) + *v1 = v; + + xcharpos = strchr(input, 'x'); + + if (!xcharpos || xcharpos != endPtr) + return FALSE; + + errno = 0; + v = strtoul(xcharpos + 1, &endPtr, 10); + + if ((v == 0 || v == ULONG_MAX) && (errno != 0)) + return FALSE; + + if (*endPtr != '\0') + return FALSE; + + if (v2) + *v2 = v; + + return TRUE; +} + +static BOOL prepare_default_settings(rdpSettings* settings, COMMAND_LINE_ARGUMENT_A* args, + BOOL rdp_file) +{ + const char* arguments[] = { "network", "gfx", "rfx", "bpp" }; + WINPR_ASSERT(settings); + WINPR_ASSERT(args); + + if (rdp_file) + return FALSE; + + for (size_t x = 0; x < ARRAYSIZE(arguments); x++) + { + const char* arg = arguments[x]; + const COMMAND_LINE_ARGUMENT_A* p = CommandLineFindArgumentA(args, arg); + if (p && (p->Flags & COMMAND_LINE_ARGUMENT_PRESENT)) + return FALSE; + } + + return freerdp_set_connection_type(settings, CONNECTION_TYPE_AUTODETECT); +} + +static BOOL setSmartcardEmulation(const char* value, rdpSettings* settings) +{ + return freerdp_settings_set_bool(settings, FreeRDP_SmartcardEmulation, TRUE); +} + +const char* option_starts_with(const char* what, const char* val) +{ + WINPR_ASSERT(what); + WINPR_ASSERT(val); + const size_t wlen = strlen(what); + + if (_strnicmp(what, val, wlen) != 0) + return NULL; + return &val[wlen]; +} + +BOOL option_ends_with(const char* str, const char* ext) +{ + WINPR_ASSERT(str); + WINPR_ASSERT(ext); + const size_t strLen = strlen(str); + const size_t extLen = strlen(ext); + + if (strLen < extLen) + return FALSE; + + return _strnicmp(&str[strLen - extLen], ext, extLen) == 0; +} + +BOOL option_equals(const char* what, const char* val) +{ + WINPR_ASSERT(what); + WINPR_ASSERT(val); + return _stricmp(what, val) == 0; +} + +typedef enum +{ + PARSE_ON, + PARSE_OFF, + PARSE_NONE, + PARSE_FAIL +} PARSE_ON_OFF_RESULT; + +static PARSE_ON_OFF_RESULT parse_on_off_option(const char* value) +{ + WINPR_ASSERT(value); + const char* sep = strchr(value, ':'); + if (!sep) + return PARSE_NONE; + if (option_equals("on", &sep[1])) + return PARSE_ON; + if (option_equals("off", &sep[1])) + return PARSE_OFF; + return PARSE_FAIL; +} + +typedef enum +{ + CLIP_DIR_PARSE_ALL, + CLIP_DIR_PARSE_OFF, + CLIP_DIR_PARSE_LOCAL, + CLIP_DIR_PARSE_REMOTE, + CLIP_DIR_PARSE_FAIL +} PARSE_CLIP_DIR_RESULT; + +static PARSE_CLIP_DIR_RESULT parse_clip_direciton_to_option(const char* value) +{ + WINPR_ASSERT(value); + const char* sep = strchr(value, ':'); + if (!sep) + return CLIP_DIR_PARSE_FAIL; + if (option_equals("all", &sep[1])) + return CLIP_DIR_PARSE_ALL; + if (option_equals("off", &sep[1])) + return CLIP_DIR_PARSE_OFF; + if (option_equals("local", &sep[1])) + return CLIP_DIR_PARSE_LOCAL; + if (option_equals("remote", &sep[1])) + return CLIP_DIR_PARSE_REMOTE; + return CLIP_DIR_PARSE_FAIL; +} + +static int parse_tls_ciphers(rdpSettings* settings, const char* Value) +{ + const char* ciphers = NULL; + if (!Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (option_equals(Value, "netmon")) + { + ciphers = "ALL:!ECDH:!ADH:!DHE"; + } + else if (option_equals(Value, "ma")) + { + ciphers = "AES128-SHA"; + } + else + { + ciphers = Value; + } + + if (!freerdp_settings_set_string(settings, FreeRDP_AllowedTlsCiphers, ciphers)) + return COMMAND_LINE_ERROR_MEMORY; + return 0; +} + +static int parse_tls_seclevel(rdpSettings* settings, const char* Value) +{ + LONGLONG val = 0; + + if (!value_to_int(Value, &val, 0, 5)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_TlsSecLevel, (UINT32)val)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + return 0; +} + +static int parse_tls_secrets_file(rdpSettings* settings, const char* Value) +{ + if (!Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_string(settings, FreeRDP_TlsSecretsFile, Value)) + return COMMAND_LINE_ERROR_MEMORY; + return 0; +} + +static int parse_tls_enforce(rdpSettings* settings, const char* Value) +{ + UINT16 version = TLS1_2_VERSION; + + if (Value) + { + struct map_t + { + const char* name; + UINT16 version; + }; + const struct map_t map[] = { { "1.0", TLS1_VERSION }, + { "1.1", TLS1_1_VERSION }, + { "1.2", TLS1_2_VERSION } +#if defined(TLS1_3_VERSION) + , + { "1.3", TLS1_3_VERSION } +#endif + }; + + for (size_t x = 0; x < ARRAYSIZE(map); x++) + { + const struct map_t* cur = &map[x]; + if (option_equals(cur->name, Value)) + { + version = cur->version; + break; + } + } + } + + if (!(freerdp_settings_set_uint16(settings, FreeRDP_TLSMinVersion, version) && + freerdp_settings_set_uint16(settings, FreeRDP_TLSMaxVersion, version))) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + return 0; +} + +static int parse_tls_cipher_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + int rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "tls") + { + if (option_starts_with("ciphers:", arg->Value)) + rc = parse_tls_ciphers(settings, &arg->Value[8]); + else if (option_starts_with("seclevel:", arg->Value)) + rc = parse_tls_seclevel(settings, &arg->Value[9]); + else if (option_starts_with("secrets-file:", arg->Value)) + rc = parse_tls_secrets_file(settings, &arg->Value[13]); + else if (option_starts_with("enforce:", arg->Value)) + rc = parse_tls_enforce(settings, &arg->Value[8]); + } + +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) + CommandLineSwitchCase(arg, "tls-ciphers") + { + WLog_WARN(TAG, "Option /tls-ciphers is deprecated, use /tls:ciphers instead"); + rc = parse_tls_ciphers(settings, arg->Value); + } + CommandLineSwitchCase(arg, "tls-seclevel") + { + WLog_WARN(TAG, "Option /tls-seclevel is deprecated, use /tls:seclevel instead"); + rc = parse_tls_seclevel(settings, arg->Value); + } + CommandLineSwitchCase(arg, "tls-secrets-file") + { + WLog_WARN(TAG, "Option /tls-secrets-file is deprecated, use /tls:secrets-file instead"); + rc = parse_tls_secrets_file(settings, arg->Value); + } + CommandLineSwitchCase(arg, "enforce-tlsv1_2") + { + WLog_WARN(TAG, "Option /enforce-tlsv1_2 is deprecated, use /tls:enforce:1.2 instead"); + rc = parse_tls_enforce(settings, "1.2"); + } +#endif + CommandLineSwitchDefault(arg) + { + } + CommandLineSwitchEnd(arg) + + return rc; +} + +static int parse_tls_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + for (size_t x = 0; x < count; x++) + { + COMMAND_LINE_ARGUMENT_A larg = *arg; + larg.Value = ptr[x]; + + int rc = parse_tls_cipher_options(settings, &larg); + if (rc != 0) + { + CommandLineParserFree(ptr); + return rc; + } + } + CommandLineParserFree(ptr); + return 0; +} + +static int parse_gfx_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE)) + return COMMAND_LINE_ERROR; + + if (arg->Value) + { + int rc = CHANNEL_RC_OK; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr || (count == 0)) + rc = COMMAND_LINE_ERROR; + else + { + BOOL GfxH264 = FALSE; + BOOL GfxAVC444 = FALSE; + BOOL RemoteFxCodec = FALSE; + BOOL GfxProgressive = FALSE; + BOOL codecSelected = FALSE; + + for (size_t x = 0; x < count; x++) + { + const char* val = ptr[x]; +#ifdef WITH_GFX_H264 + if (option_starts_with("AVC444", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + GfxAVC444 = bval != PARSE_OFF; + codecSelected = TRUE; + } + else if (option_starts_with("AVC420", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + GfxH264 = bval != PARSE_OFF; + codecSelected = TRUE; + } + else +#endif + if (option_starts_with("RFX", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + RemoteFxCodec = bval != PARSE_OFF; + codecSelected = TRUE; + } + else if (option_starts_with("progressive", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + GfxProgressive = bval != PARSE_OFF; + codecSelected = TRUE; + } + else if (option_starts_with("mask:", val)) + { + ULONGLONG v = 0; + const char* uv = &val[5]; + if (!value_to_uint(uv, &v, 0, UINT32_MAX)) + rc = COMMAND_LINE_ERROR; + else + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_GfxCapsFilter, + (UINT32)v)) + rc = COMMAND_LINE_ERROR; + } + } + else if (option_starts_with("small-cache", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_GfxSmallCache, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("thin-client", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_GfxThinClient, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + if ((rc == CHANNEL_RC_OK) && (bval > 0)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxSmallCache, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + } + else if (option_starts_with("frame-ack", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_GfxSuspendFrameAck, + bval == PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + else + rc = COMMAND_LINE_ERROR; + } + + if ((rc == CHANNEL_RC_OK) && codecSelected) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444, GfxAVC444)) + rc = COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxAVC444v2, GfxAVC444)) + rc = COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxH264, GfxH264)) + rc = COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, RemoteFxCodec)) + rc = COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxProgressive, GfxProgressive)) + rc = COMMAND_LINE_ERROR; + } + } + CommandLineParserFree(ptr); + if (rc != CHANNEL_RC_OK) + return rc; + } + return CHANNEL_RC_OK; +} + +static int parse_kbd_layout(rdpSettings* settings, const char* value) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(value); + + int rc = 0; + LONGLONG ival = 0; + const BOOL isInt = value_to_int(value, &ival, 1, UINT32_MAX); + if (!isInt) + { + ival = freerdp_map_keyboard_layout_name_to_id(value); + + if (ival == 0) + { + WLog_ERR(TAG, "Could not identify keyboard layout: %s", value); + WLog_ERR(TAG, "Use /list:kbd to list available layouts"); + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + + if (rc == 0) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardLayout, (UINT32)ival)) + rc = COMMAND_LINE_ERROR; + } + return rc; +} + +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) +static int parse_codec_cache_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!arg->Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheV3Enabled, TRUE)) + return COMMAND_LINE_ERROR; + + if (option_equals(arg->Value, "rfx")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_equals(arg->Value, "nsc")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, TRUE)) + return COMMAND_LINE_ERROR; + } + +#if defined(WITH_JPEG) + else if (option_equals(arg->Value, "jpeg")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_JpegCodec, TRUE)) + return COMMAND_LINE_ERROR; + + if (freerdp_settings_get_uint32(settings, FreeRDP_JpegQuality) == 0) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_JpegQuality, 75)) + return COMMAND_LINE_ERROR; + } + } + +#endif + return 0; +} +#endif + +static BOOL check_kbd_remap_valid(const char* token) +{ + DWORD key = 0; + DWORD value = 0; + + WINPR_ASSERT(token); + /* The remapping is only allowed for scancodes, so maximum is 999=999 */ + if (strlen(token) > 10) + return FALSE; + + if (!freerdp_extract_key_value(token, &key, &value)) + { + WLog_WARN(TAG, "/kbd:remap invalid entry '%s'", token); + return FALSE; + } + return TRUE; +} + +static int parse_host_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!arg->Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_settings_set_string(settings, FreeRDP_ServerHostname, NULL)) + return COMMAND_LINE_ERROR_MEMORY; + char* p = strchr(arg->Value, '['); + + /* ipv4 */ + if (!p) + { + const char scheme[] = "://"; + const char* val = strstr(arg->Value, scheme); + if (val) + val += strnlen(scheme, sizeof(scheme)); + else + val = arg->Value; + p = strchr(val, ':'); + + if (p) + { + LONGLONG lval = 0; + size_t length = 0; + + if (!value_to_int(&p[1], &lval, 1, UINT16_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + length = (size_t)(p - arg->Value); + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, (UINT16)lval)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_settings_set_string_len(settings, FreeRDP_ServerHostname, arg->Value, + length)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else + { + if (!freerdp_settings_set_string(settings, FreeRDP_ServerHostname, arg->Value)) + return COMMAND_LINE_ERROR_MEMORY; + } + } + else /* ipv6 */ + { + size_t length = 0; + char* p2 = strchr(arg->Value, ']'); + + /* not a valid [] ipv6 addr found */ + if (!p2) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + length = (size_t)(p2 - p); + if (!freerdp_settings_set_string_len(settings, FreeRDP_ServerHostname, p + 1, length - 1)) + return COMMAND_LINE_ERROR_MEMORY; + + if (*(p2 + 1) == ':') + { + LONGLONG val = 0; + + if (!value_to_int(&p2[2], &val, 0, UINT16_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, (UINT16)val)) + return COMMAND_LINE_ERROR; + } + + printf("hostname %s port %" PRIu32 "\n", + freerdp_settings_get_string(settings, FreeRDP_ServerHostname), + freerdp_settings_get_uint32(settings, FreeRDP_ServerPort)); + } + return 0; +} + +static int parse_redirect_prefer_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char* cur = arg->Value; + if (!arg->Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (!freerdp_settings_set_uint32(settings, FreeRDP_RedirectionPreferType, 0)) + return COMMAND_LINE_ERROR; + + UINT32 value = 0; + do + { + UINT32 mask = 0; + char* next = strchr(cur, ','); + + if (next) + { + *next = '\0'; + next++; + } + + if (option_equals("fqdn", cur)) + mask = 0x06U; + else if (option_equals("ip", cur)) + mask = 0x05U; + else if (option_equals("netbios", cur)) + mask = 0x03U; + else + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + cur = next; + mask = (mask & 0x07); + value |= mask << (count * 3); + count++; + } while (cur != NULL); + + if (!freerdp_settings_set_uint32(settings, FreeRDP_RedirectionPreferType, value)) + return COMMAND_LINE_ERROR; + + if (count > 3) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + return 0; +} + +static int parse_prevent_session_lock_options(rdpSettings* settings, + const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!freerdp_settings_set_uint32(settings, FreeRDP_FakeMouseMotionInterval, 180)) + return COMMAND_LINE_ERROR_MEMORY; + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 1, UINT32_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_FakeMouseMotionInterval, (UINT32)val)) + return COMMAND_LINE_ERROR_MEMORY; + } + + return 0; +} + +static int parse_vmconnect_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!freerdp_settings_set_bool(settings, FreeRDP_VmConnectMode, TRUE)) + return COMMAND_LINE_ERROR; + + UINT32 port = freerdp_settings_get_uint32(settings, FreeRDP_ServerPort); + if (port == 3389) + port = 2179; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ServerPort, port)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_NegotiateSecurityLayer, FALSE)) + return COMMAND_LINE_ERROR; + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SendPreconnectionPdu, TRUE)) + return COMMAND_LINE_ERROR; + + if (!freerdp_settings_set_string(settings, FreeRDP_PreconnectionBlob, arg->Value)) + return COMMAND_LINE_ERROR_MEMORY; + } + return 0; +} + +static int parse_size_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + int status = 0; + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (!arg->Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + char* p = strchr(arg->Value, 'x'); + + if (p) + { + unsigned long w = 0; + unsigned long h = 0; + + if (!parseSizeValue(arg->Value, &w, &h) || (w > UINT16_MAX) || (h > UINT16_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, (UINT32)w)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, (UINT32)h)) + return COMMAND_LINE_ERROR; + } + else + { + char* str = _strdup(arg->Value); + if (!str) + return COMMAND_LINE_ERROR_MEMORY; + + p = strchr(str, '%'); + + if (p) + { + BOOL partial = FALSE; + + status = COMMAND_LINE_ERROR; + if (strchr(p, 'w')) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_PercentScreenUseWidth, TRUE)) + goto fail; + partial = TRUE; + } + + if (strchr(p, 'h')) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_PercentScreenUseHeight, TRUE)) + goto fail; + partial = TRUE; + } + + if (!partial) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_PercentScreenUseWidth, TRUE)) + goto fail; + if (!freerdp_settings_set_bool(settings, FreeRDP_PercentScreenUseHeight, TRUE)) + goto fail; + } + + *p = '\0'; + { + LONGLONG val = 0; + + if (!value_to_int(str, &val, 0, 100)) + { + status = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + goto fail; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_PercentScreen, (UINT32)val)) + goto fail; + } + + status = 0; + } + + fail: + free(str); + } + + return status; +} + +static int parse_monitors_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + size_t count = 0; + UINT32* MonitorIds = NULL; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + + if (!ptr) + return COMMAND_LINE_ERROR_MEMORY; + + if (count > 16) + count = 16; + + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_MonitorIds, NULL, count)) + { + CommandLineParserFree(ptr); + return FALSE; + } + + MonitorIds = freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorIds, 0); + for (UINT32 i = 0; i < count; i++) + { + LONGLONG val = 0; + + if (!value_to_int(ptr[i], &val, 0, UINT16_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + MonitorIds[i] = (UINT32)val; + } + + CommandLineParserFree(ptr); + } + + return 0; +} + +static int parse_dynamic_resolution_options(rdpSettings* settings, + const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + const BOOL val = arg->Value != 0; + + if (val && freerdp_settings_get_bool(settings, FreeRDP_SmartSizing)) + { + WLog_ERR(TAG, "Smart sizing and dynamic resolution are mutually exclusive options"); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportDisplayControl, val)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_DynamicResolutionUpdate, val)) + return COMMAND_LINE_ERROR; + + return 0; +} + +static int parse_smart_sizing_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate)) + { + WLog_ERR(TAG, "Smart sizing and dynamic resolution are mutually exclusive options"); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + if (!freerdp_settings_set_bool(settings, FreeRDP_SmartSizing, TRUE)) + return COMMAND_LINE_ERROR; + + if (arg->Value) + { + unsigned long w = 0; + unsigned long h = 0; + + if (!parseSizeValue(arg->Value, &w, &h) || (w > UINT16_MAX) || (h > UINT16_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (!freerdp_settings_set_uint32(settings, FreeRDP_SmartSizingWidth, (UINT32)w)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_uint32(settings, FreeRDP_SmartSizingHeight, (UINT32)h)) + return COMMAND_LINE_ERROR; + } + return 0; +} + +static int parse_bpp_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 0, UINT32_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + switch (val) + { + case 32: + case 24: + case 16: + case 15: + case 8: + if (!freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, (UINT32)val)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + break; + + default: + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + return 0; +} + +static int parse_kbd_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + int rc = CHANNEL_RC_OK; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr || (count == 0)) + rc = COMMAND_LINE_ERROR; + else + { + for (size_t x = 0; x < count; x++) + { + const char* val = ptr[x]; + + if (option_starts_with("remap:", val)) + { + /* Append this new occurrence to the already existing list */ + char* now = _strdup(&val[6]); + const char* old = + freerdp_settings_get_string(settings, FreeRDP_KeyboardRemappingList); + + /* Basic sanity test. Entries must be like =, e.g. 1=2 */ + if (!check_kbd_remap_valid(now)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (old) + { + const size_t olen = strlen(old); + const size_t alen = strlen(now); + const size_t tlen = olen + alen + 2; + char* tmp = calloc(tlen, sizeof(char)); + if (!tmp) + rc = COMMAND_LINE_ERROR_MEMORY; + else + (void)_snprintf(tmp, tlen, "%s,%s", old, now); + free(now); + now = tmp; + } + + if (rc == 0) + { + if (!freerdp_settings_set_string(settings, FreeRDP_KeyboardRemappingList, now)) + rc = COMMAND_LINE_ERROR; + } + free(now); + } + else if (option_starts_with("layout:", val)) + { + rc = parse_kbd_layout(settings, &val[7]); + } + else if (option_starts_with("lang:", val)) + { + LONGLONG ival = 0; + const BOOL isInt = value_to_int(&val[5], &ival, 1, UINT32_MAX); + if (!isInt) + ival = freerdp_get_locale_id_from_string(&val[5]); + + if (ival <= 0) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardCodePage, + (UINT32)ival)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("type:", val)) + { + LONGLONG ival = 0; + const BOOL isInt = value_to_int(&val[5], &ival, 1, UINT32_MAX); + if (!isInt) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardType, (UINT32)ival)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("subtype:", val)) + { + LONGLONG ival = 0; + const BOOL isInt = value_to_int(&val[8], &ival, 1, UINT32_MAX); + if (!isInt) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardSubType, + (UINT32)ival)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("fn-key:", val)) + { + LONGLONG ival = 0; + const BOOL isInt = value_to_int(&val[7], &ival, 1, UINT32_MAX); + if (!isInt) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardFunctionKey, + (UINT32)ival)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("unicode", val)) + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_UnicodeInput, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else if (option_starts_with("pipe:", val)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_UnicodeInput, TRUE)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else if (!freerdp_settings_set_string(settings, FreeRDP_KeyboardPipeName, &val[5])) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) + else if (count == 1) + { + /* Legacy, allow /kbd: for setting keyboard layout */ + rc = parse_kbd_layout(settings, val); + } +#endif + else + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (rc != 0) + break; + } + } + CommandLineParserFree(ptr); + return rc; +} + +static int parse_proxy_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + /* initial value */ + if (!freerdp_settings_set_uint32(settings, FreeRDP_ProxyType, PROXY_TYPE_HTTP)) + return COMMAND_LINE_ERROR_MEMORY; + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + const char* cur = arg->Value; + + if (!cur) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + /* value is [scheme://][user:password@]hostname:port */ + if (!proxy_parse_uri(settings, cur)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else + { + WLog_ERR(TAG, "Option http-proxy needs argument."); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + return 0; +} + +static int parse_dump_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + BOOL failed = FALSE; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr) + failed = TRUE; + else + { + BOOL modernsyntax = FALSE; + BOOL oldsyntax = FALSE; + for (size_t x = 0; (x < count) && !failed; x++) + { + const char* carg = ptr[x]; + if (option_starts_with("file:", carg)) + { + const char* val = &carg[5]; + if (oldsyntax) + failed = TRUE; + else if (!freerdp_settings_set_string(settings, FreeRDP_TransportDumpFile, val)) + failed = TRUE; + modernsyntax = TRUE; + } + else if (option_equals("replay", carg)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDump, FALSE)) + failed = TRUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDumpReplay, TRUE)) + failed = TRUE; + } + else if (option_equals("record", carg)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDump, TRUE)) + failed = TRUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDumpReplay, FALSE)) + failed = TRUE; + } + else if (option_equals("nodelay", carg)) + { + if (oldsyntax) + failed = TRUE; + else if (!freerdp_settings_set_bool(settings, FreeRDP_TransportDumpReplayNodelay, + TRUE)) + failed = TRUE; + modernsyntax = TRUE; + } + else + { + /* compat: + * support syntax record, and replay, + */ + if (modernsyntax) + failed = TRUE; + else if (!freerdp_settings_set_string(settings, FreeRDP_TransportDumpFile, carg)) + failed = TRUE; + oldsyntax = TRUE; + } + } + + if (oldsyntax && (count != 2)) + failed = TRUE; + } + CommandLineParserFree(ptr); + if (failed) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + return 0; +} + +static int parse_clipboard_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (arg->Value == BoolValueTrue || arg->Value == BoolValueFalse) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectClipboard, + (arg->Value == BoolValueTrue))) + return COMMAND_LINE_ERROR; + } + else + { + int rc = 0; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + for (size_t x = 0; (x < count) && (rc == 0); x++) + { + const char* usesel = "use-selection:"; + + const char* cur = ptr[x]; + if (option_starts_with(usesel, cur)) + { + const char* val = &cur[strlen(usesel)]; + if (!freerdp_settings_set_string(settings, FreeRDP_ClipboardUseSelection, val)) + rc = COMMAND_LINE_ERROR_MEMORY; + if (!freerdp_settings_set_bool(settings, FreeRDP_RedirectClipboard, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_starts_with("direction-to", cur)) + { + const UINT32 mask = + freerdp_settings_get_uint32(settings, FreeRDP_ClipboardFeatureMask) & + (uint32_t)~(CLIPRDR_FLAG_LOCAL_TO_REMOTE | CLIPRDR_FLAG_REMOTE_TO_LOCAL); + const PARSE_CLIP_DIR_RESULT bval = parse_clip_direciton_to_option(cur); + UINT32 bflags = 0; + switch (bval) + { + case CLIP_DIR_PARSE_ALL: + bflags |= CLIPRDR_FLAG_LOCAL_TO_REMOTE | CLIPRDR_FLAG_REMOTE_TO_LOCAL; + break; + case CLIP_DIR_PARSE_LOCAL: + bflags |= CLIPRDR_FLAG_REMOTE_TO_LOCAL; + break; + case CLIP_DIR_PARSE_REMOTE: + bflags |= CLIPRDR_FLAG_LOCAL_TO_REMOTE; + break; + case CLIP_DIR_PARSE_OFF: + break; + case CLIP_DIR_PARSE_FAIL: + default: + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + break; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ClipboardFeatureMask, + mask | bflags)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else if (option_starts_with("files-to", cur)) + { + const UINT32 mask = + freerdp_settings_get_uint32(settings, FreeRDP_ClipboardFeatureMask) & + (uint32_t)~(CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES | + CLIPRDR_FLAG_REMOTE_TO_LOCAL_FILES); + const PARSE_CLIP_DIR_RESULT bval = parse_clip_direciton_to_option(cur); + UINT32 bflags = 0; + switch (bval) + { + case CLIP_DIR_PARSE_ALL: + bflags |= + CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES | CLIPRDR_FLAG_REMOTE_TO_LOCAL_FILES; + break; + case CLIP_DIR_PARSE_LOCAL: + bflags |= CLIPRDR_FLAG_REMOTE_TO_LOCAL_FILES; + break; + case CLIP_DIR_PARSE_REMOTE: + bflags |= CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES; + break; + case CLIP_DIR_PARSE_OFF: + break; + case CLIP_DIR_PARSE_FAIL: + default: + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + break; + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_ClipboardFeatureMask, + mask | bflags)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + CommandLineParserFree(ptr); + + if (rc) + return rc; + } + return 0; +} + +static int parse_audio_mode_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 0, UINT32_MAX)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + switch (val) + { + case AUDIO_MODE_REDIRECT: + if (!freerdp_settings_set_bool(settings, FreeRDP_AudioPlayback, TRUE)) + return COMMAND_LINE_ERROR; + break; + + case AUDIO_MODE_PLAY_ON_SERVER: + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteConsoleAudio, TRUE)) + return COMMAND_LINE_ERROR; + break; + + case AUDIO_MODE_NONE: + if (!freerdp_settings_set_bool(settings, FreeRDP_AudioPlayback, FALSE)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteConsoleAudio, FALSE)) + return COMMAND_LINE_ERROR; + break; + + default: + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + return 0; +} + +static int parse_network_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + UINT32 type = CONNECTION_TYPE_INVALID; + + if (option_equals(arg->Value, "invalid")) + type = CONNECTION_TYPE_INVALID; + else if (option_equals(arg->Value, "modem")) + type = CONNECTION_TYPE_MODEM; + else if (option_equals(arg->Value, "broadband")) + type = CONNECTION_TYPE_BROADBAND_HIGH; + else if (option_equals(arg->Value, "broadband-low")) + type = CONNECTION_TYPE_BROADBAND_LOW; + else if (option_equals(arg->Value, "broadband-high")) + type = CONNECTION_TYPE_BROADBAND_HIGH; + else if (option_equals(arg->Value, "wan")) + type = CONNECTION_TYPE_WAN; + else if (option_equals(arg->Value, "lan")) + type = CONNECTION_TYPE_LAN; + else if ((option_equals(arg->Value, "autodetect")) || (option_equals(arg->Value, "auto")) || + (option_equals(arg->Value, "detect"))) + { + type = CONNECTION_TYPE_AUTODETECT; + } + else + { + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 0, 7)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + type = (UINT32)val; + } + + if (!freerdp_set_connection_type(settings, type)) + return COMMAND_LINE_ERROR; + return 0; +} + +static int parse_sec_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (count == 0) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + FreeRDP_Settings_Keys_Bool singleOptionWithoutOnOff = FreeRDP_BOOL_UNUSED; + for (size_t x = 0; x < count; x++) + { + const char* cur = ptr[x]; + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(cur); + if (bval == PARSE_FAIL) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + const BOOL val = bval != PARSE_OFF; + FreeRDP_Settings_Keys_Bool id = FreeRDP_BOOL_UNUSED; + if (option_starts_with("rdp", cur)) /* Standard RDP */ + { + id = FreeRDP_RdpSecurity; + if (!freerdp_settings_set_bool(settings, FreeRDP_UseRdpSecurityLayer, val)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else if (option_starts_with("tls", cur)) /* TLS */ + id = FreeRDP_TlsSecurity; + else if (option_starts_with("nla", cur)) /* NLA */ + id = FreeRDP_NlaSecurity; + else if (option_starts_with("ext", cur)) /* NLA Extended */ + id = FreeRDP_ExtSecurity; + else if (option_equals("aad", cur)) /* RDSAAD */ + id = FreeRDP_AadSecurity; + else + { + WLog_ERR(TAG, "unknown protocol security: %s", arg->Value); + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + if ((bval == PARSE_NONE) && (count == 1)) + singleOptionWithoutOnOff = id; + if (!freerdp_settings_set_bool(settings, id, val)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + if (singleOptionWithoutOnOff != FreeRDP_BOOL_UNUSED) + { + const FreeRDP_Settings_Keys_Bool options[] = { FreeRDP_AadSecurity, + FreeRDP_UseRdpSecurityLayer, + FreeRDP_RdpSecurity, FreeRDP_NlaSecurity, + FreeRDP_TlsSecurity }; + + for (size_t i = 0; i < ARRAYSIZE(options); i++) + { + if (!freerdp_settings_set_bool(settings, options[i], FALSE)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + + if (!freerdp_settings_set_bool(settings, singleOptionWithoutOnOff, TRUE)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + if (singleOptionWithoutOnOff == FreeRDP_RdpSecurity) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_UseRdpSecurityLayer, TRUE)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + CommandLineParserFree(ptr); + return 0; +} + +static int parse_encryption_methods_options(rdpSettings* settings, + const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + { + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + + UINT32 EncryptionMethods = 0; + for (UINT32 i = 0; i < count; i++) + { + if (option_equals(ptr[i], "40")) + EncryptionMethods |= ENCRYPTION_METHOD_40BIT; + else if (option_equals(ptr[i], "56")) + EncryptionMethods |= ENCRYPTION_METHOD_56BIT; + else if (option_equals(ptr[i], "128")) + EncryptionMethods |= ENCRYPTION_METHOD_128BIT; + else if (option_equals(ptr[i], "FIPS")) + EncryptionMethods |= ENCRYPTION_METHOD_FIPS; + else + WLog_ERR(TAG, "unknown encryption method '%s'", ptr[i]); + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_EncryptionMethods, EncryptionMethods)) + return COMMAND_LINE_ERROR; + CommandLineParserFree(ptr); + } + return 0; +} + +static int parse_cert_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + int rc = 0; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + for (size_t x = 0; (x < count) && (rc == 0); x++) + { + const char deny[] = "deny"; + const char ignore[] = "ignore"; + const char tofu[] = "tofu"; + const char name[] = "name:"; + const char fingerprints[] = "fingerprint:"; + + const char* cur = ptr[x]; + if (option_equals(deny, cur)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoDenyCertificate, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_equals(ignore, cur)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_IgnoreCertificate, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_equals(tofu, cur)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_AutoAcceptCertificate, TRUE)) + return COMMAND_LINE_ERROR; + } + else if (option_starts_with(name, cur)) + { + const char* val = &cur[strnlen(name, sizeof(name))]; + if (!freerdp_settings_set_string(settings, FreeRDP_CertificateName, val)) + rc = COMMAND_LINE_ERROR_MEMORY; + } + else if (option_starts_with(fingerprints, cur)) + { + const char* val = &cur[strnlen(fingerprints, sizeof(fingerprints))]; + if (!freerdp_settings_append_string(settings, FreeRDP_CertificateAcceptedFingerprints, + ",", val)) + rc = COMMAND_LINE_ERROR_MEMORY; + } + else + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + CommandLineParserFree(ptr); + + return rc; +} + +static int parse_mouse_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx("mouse", arg->Value, &count); + int rc = 0; + if (ptr) + { + for (size_t x = 1; x < count; x++) + { + const char* cur = ptr[x]; + + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(cur); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + { + const BOOL val = bval != PARSE_OFF; + + if (option_starts_with("relative", cur)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_MouseUseRelativeMove, val)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else if (option_starts_with("grab", cur)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GrabMouse, val)) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + + if (rc != 0) + break; + } + } + CommandLineParserFree(ptr); + + return rc; +} + +static int parse_floatbar_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + /* Defaults are enabled, visible, sticky, fullscreen */ + UINT32 Floatbar = 0x0017; + + if (arg->Value) + { + char* start = arg->Value; + + do + { + char* cur = start; + start = strchr(start, ','); + + if (start) + { + *start = '\0'; + start = start + 1; + } + + /* sticky:[on|off] */ + if (option_starts_with("sticky:", cur)) + { + Floatbar &= ~0x02u; + + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(cur); + switch (bval) + { + case PARSE_ON: + case PARSE_NONE: + Floatbar |= 0x02u; + break; + case PARSE_OFF: + Floatbar &= ~0x02u; + break; + case PARSE_FAIL: + default: + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + /* default:[visible|hidden] */ + else if (option_starts_with("default:", cur)) + { + const char* val = cur + 8; + Floatbar &= ~0x04u; + + if (option_equals("visible", val)) + Floatbar |= 0x04u; + else if (option_equals("hidden", val)) + Floatbar &= ~0x04u; + else + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + /* show:[always|fullscreen|window] */ + else if (option_starts_with("show:", cur)) + { + const char* val = cur + 5; + Floatbar &= ~0x30u; + + if (option_equals("always", val)) + Floatbar |= 0x30u; + else if (option_equals("fullscreen", val)) + Floatbar |= 0x10u; + else if (option_equals("window", val)) + Floatbar |= 0x20u; + else + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + else + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } while (start); + } + if (!freerdp_settings_set_uint32(settings, FreeRDP_Floatbar, Floatbar)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + return 0; +} + +static int parse_reconnect_cookie_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + BYTE* base64 = NULL; + size_t length = 0; + if (!arg->Value) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + crypto_base64_decode((const char*)(arg->Value), strlen(arg->Value), &base64, &length); + + if ((base64 != NULL) && (length == sizeof(ARC_SC_PRIVATE_PACKET))) + { + if (!freerdp_settings_set_pointer_len(settings, FreeRDP_ServerAutoReconnectCookie, base64, + 1)) + return COMMAND_LINE_ERROR; + } + else + { + WLog_ERR(TAG, "reconnect-cookie: invalid base64 '%s'", arg->Value); + } + + free(base64); + return 0; +} + +static int parse_scale_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 100, 180)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + switch (val) + { + case 100: + case 140: + case 180: + if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopScaleFactor, (UINT32)val)) + return COMMAND_LINE_ERROR; + if (!freerdp_settings_set_uint32(settings, FreeRDP_DeviceScaleFactor, (UINT32)val)) + return COMMAND_LINE_ERROR; + break; + + default: + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + return 0; +} + +static int parse_scale_device_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, 100, 180)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + switch (val) + { + case 100: + case 140: + case 180: + if (!freerdp_settings_set_uint32(settings, FreeRDP_DeviceScaleFactor, (UINT32)val)) + return COMMAND_LINE_ERROR; + break; + + default: + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + return 0; +} + +static int parse_smartcard_logon_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + + if (!freerdp_settings_set_bool(settings, FreeRDP_SmartcardLogon, TRUE)) + return COMMAND_LINE_ERROR; + + char** ptr = CommandLineParseCommaSeparatedValuesEx("smartcard-logon", arg->Value, &count); + if (ptr) + { + const CmdLineSubOptions opts[] = { + { "cert:", FreeRDP_SmartcardCertificate, CMDLINE_SUBOPTION_FILE, + setSmartcardEmulation }, + { "key:", FreeRDP_SmartcardPrivateKey, CMDLINE_SUBOPTION_FILE, setSmartcardEmulation }, + { "pin:", FreeRDP_Password, CMDLINE_SUBOPTION_STRING, NULL }, + { "csp:", FreeRDP_CspName, CMDLINE_SUBOPTION_STRING, NULL }, + { "reader:", FreeRDP_ReaderName, CMDLINE_SUBOPTION_STRING, NULL }, + { "card:", FreeRDP_CardName, CMDLINE_SUBOPTION_STRING, NULL }, + { "container:", FreeRDP_ContainerName, CMDLINE_SUBOPTION_STRING, NULL } + }; + + for (size_t x = 1; x < count; x++) + { + const char* cur = ptr[x]; + if (!parseSubOptions(settings, opts, ARRAYSIZE(opts), cur)) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + } + } + } + CommandLineParserFree(ptr); + return 0; +} + +static int parse_tune_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValuesEx("tune", arg->Value, &count); + if (!ptr) + return COMMAND_LINE_ERROR; + for (size_t x = 1; x < count; x++) + { + const char* cur = ptr[x]; + char* sep = strchr(cur, ':'); + if (!sep) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR; + } + *sep++ = '\0'; + if (!freerdp_settings_set_value_for_name(settings, cur, sep)) + { + CommandLineParserFree(ptr); + return COMMAND_LINE_ERROR; + } + } + + CommandLineParserFree(ptr); + return 0; +} + +static int parse_app_option_program(rdpSettings* settings, const char* cmd) +{ + const FreeRDP_Settings_Keys_Bool ids[] = { FreeRDP_RemoteApplicationMode, + FreeRDP_RemoteAppLanguageBarSupported, + FreeRDP_Workarea, FreeRDP_DisableWallpaper, + FreeRDP_DisableFullWindowDrag }; + + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationProgram, cmd)) + return COMMAND_LINE_ERROR_MEMORY; + + for (size_t y = 0; y < ARRAYSIZE(ids); y++) + { + if (!freerdp_settings_set_bool(settings, ids[y], TRUE)) + return COMMAND_LINE_ERROR; + } + return CHANNEL_RC_OK; +} + +static int parse_aad_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + int rc = CHANNEL_RC_OK; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr || (count == 0)) + rc = COMMAND_LINE_ERROR; + else + { + struct app_map + { + const char* name; + SSIZE_T id; + int (*fkt)(rdpSettings* settings, const char* value); + }; + const struct app_map amap[] = { { "tenantid:", FreeRDP_GatewayAvdAadtenantid, + parse_app_option_program }, + { "ad:", FreeRDP_GatewayAzureActiveDirectory, NULL } }; + for (size_t x = 0; x < count; x++) + { + BOOL handled = FALSE; + const char* val = ptr[x]; + + if (option_starts_with("use-tenantid", val)) + { + PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + { + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + break; + } + else + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayAvdUseTenantid, + bval != PARSE_OFF)) + { + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + break; + } + } + continue; + } + for (size_t y = 0; y < ARRAYSIZE(amap); y++) + { + const struct app_map* cur = &amap[y]; + if (option_starts_with(cur->name, val)) + { + const char* xval = &val[strlen(cur->name)]; + if (cur->fkt) + rc = cur->fkt(settings, xval); + else + { + const char* name = freerdp_settings_get_name_for_key(cur->id); + if (!freerdp_settings_set_value_for_name(settings, name, xval)) + rc = COMMAND_LINE_ERROR_MEMORY; + } + + handled = TRUE; + break; + } + } + + if (!handled) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (rc != 0) + break; + } + } + + CommandLineParserFree(ptr); + return rc; +} + +static int parse_app_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + int rc = CHANNEL_RC_OK; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr || (count == 0)) + rc = COMMAND_LINE_ERROR; + else + { + struct app_map + { + const char* name; + SSIZE_T id; + int (*fkt)(rdpSettings* settings, const char* value); + }; + const struct app_map amap[] = { { "program:", FreeRDP_RemoteApplicationProgram, + parse_app_option_program }, + { "workdir:", FreeRDP_RemoteApplicationWorkingDir, NULL }, + { "name:", FreeRDP_RemoteApplicationName, NULL }, + { "icon:", FreeRDP_RemoteApplicationIcon, NULL }, + { "cmd:", FreeRDP_RemoteApplicationCmdLine, NULL }, + { "file:", FreeRDP_RemoteApplicationFile, NULL }, + { "guid:", FreeRDP_RemoteApplicationGuid, NULL }, + { "hidef:", FreeRDP_HiDefRemoteApp, NULL } }; + for (size_t x = 0; x < count; x++) + { + BOOL handled = FALSE; + const char* val = ptr[x]; + + for (size_t y = 0; y < ARRAYSIZE(amap); y++) + { + const struct app_map* cur = &amap[y]; + if (option_starts_with(cur->name, val)) + { + const char* xval = &val[strlen(cur->name)]; + if (cur->fkt) + rc = cur->fkt(settings, xval); + else + { + const char* name = freerdp_settings_get_name_for_key(cur->id); + if (!freerdp_settings_set_value_for_name(settings, name, xval)) + rc = COMMAND_LINE_ERROR_MEMORY; + } + + handled = TRUE; + break; + } + } + +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) + if (!handled && (count == 1)) + { + /* Legacy path, allow /app:command and /app:||command syntax */ + rc = parse_app_option_program(settings, val); + } + else +#endif + if (!handled) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + if (rc != 0) + break; + } + } + + CommandLineParserFree(ptr); + return rc; +} + +static int parse_cache_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + int rc = CHANNEL_RC_OK; + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (!ptr || (count == 0)) + return COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + + for (size_t x = 0; x < count; x++) + { + const char* val = ptr[x]; + + if (option_starts_with("codec:", val)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheV3Enabled, TRUE)) + rc = COMMAND_LINE_ERROR; + else if (option_equals(arg->Value, "rfx")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_RemoteFxCodec, TRUE)) + rc = COMMAND_LINE_ERROR; + } + else if (option_equals(arg->Value, "nsc")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_NSCodec, TRUE)) + rc = COMMAND_LINE_ERROR; + } + +#if defined(WITH_JPEG) + else if (option_equals(arg->Value, "jpeg")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_JpegCodec, TRUE)) + rc = COMMAND_LINE_ERROR; + + if (freerdp_settings_get_uint32(settings, FreeRDP_JpegQuality) == 0) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_JpegQuality, 75)) + return COMMAND_LINE_ERROR; + } + } + +#endif + } + else if (option_starts_with("persist-file:", val)) + { + + if (!freerdp_settings_set_string(settings, FreeRDP_BitmapCachePersistFile, &val[13])) + rc = COMMAND_LINE_ERROR_MEMORY; + else if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCachePersistEnabled, TRUE)) + rc = COMMAND_LINE_ERROR; + } + else + { + const PARSE_ON_OFF_RESULT bval = parse_on_off_option(val); + if (bval == PARSE_FAIL) + rc = COMMAND_LINE_ERROR_UNEXPECTED_VALUE; + else + { + if (option_starts_with("bitmap", val)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheEnabled, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("glyph", val)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_GlyphSupportLevel, + bval != PARSE_OFF ? GLYPH_SUPPORT_FULL + : GLYPH_SUPPORT_NONE)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("persist", val)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCachePersistEnabled, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + else if (option_starts_with("offscreen", val)) + { + if (!freerdp_settings_set_uint32(settings, FreeRDP_OffscreenSupportLevel, + bval != PARSE_OFF)) + rc = COMMAND_LINE_ERROR; + } + } + } + } + + CommandLineParserFree(ptr); + return rc; +} + +static BOOL parse_gateway_host_option(rdpSettings* settings, const char* host) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(host); + + char* name = NULL; + int port = -1; + if (!freerdp_parse_hostname(host, &name, &port)) + return FALSE; + const BOOL rc = freerdp_settings_set_string(settings, FreeRDP_GatewayHostname, name); + free(name); + if (!rc) + return FALSE; + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayUseSameCredentials, TRUE)) + return FALSE; + if (!freerdp_set_gateway_usage_method(settings, TSC_PROXY_MODE_DIRECT)) + return FALSE; + + return TRUE; +} + +static BOOL parse_gateway_cred_option(rdpSettings* settings, const char* value, + FreeRDP_Settings_Keys_String what) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(value); + + switch (what) + { + case FreeRDP_GatewayUsername: + if (!freerdp_parse_username_settings(value, settings, FreeRDP_GatewayUsername, + FreeRDP_GatewayDomain)) + return FALSE; + break; + default: + if (!freerdp_settings_set_string(settings, what, value)) + return FALSE; + break; + } + + return freerdp_settings_set_bool(settings, FreeRDP_GatewayUseSameCredentials, FALSE); +} + +static BOOL parse_gateway_type_option(rdpSettings* settings, const char* value) +{ + WINPR_ASSERT(settings); + WINPR_ASSERT(value); + + if (option_equals(value, "rpc")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayRpcTransport, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpTransport, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpUseWebsockets, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayArmTransport, FALSE)) + return FALSE; + } + else + { + if (option_equals(value, "http")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayRpcTransport, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpTransport, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayArmTransport, FALSE)) + return FALSE; + } + else if (option_equals(value, "auto")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayRpcTransport, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpTransport, TRUE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayArmTransport, FALSE)) + return FALSE; + } + else if (option_equals(value, "arm")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayRpcTransport, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpTransport, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpUseWebsockets, FALSE) || + !freerdp_settings_set_bool(settings, FreeRDP_GatewayArmTransport, TRUE)) + return FALSE; + } + } + return TRUE; +} + +static BOOL parse_gateway_usage_option(rdpSettings* settings, const char* value) +{ + UINT32 type = 0; + + WINPR_ASSERT(settings); + WINPR_ASSERT(value); + + if (option_equals(value, "none")) + type = TSC_PROXY_MODE_NONE_DIRECT; + else if (option_equals(value, "direct")) + type = TSC_PROXY_MODE_DIRECT; + else if (option_equals(value, "detect")) + type = TSC_PROXY_MODE_DETECT; + else if (option_equals(value, "default")) + type = TSC_PROXY_MODE_DEFAULT; + else + { + LONGLONG val = 0; + + if (!value_to_int(value, &val, TSC_PROXY_MODE_NONE_DIRECT, TSC_PROXY_MODE_NONE_DETECT)) + return FALSE; + } + + return freerdp_set_gateway_usage_method(settings, type); +} + +static BOOL parse_gateway_options(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + BOOL rc = FALSE; + + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + size_t count = 0; + char** ptr = CommandLineParseCommaSeparatedValues(arg->Value, &count); + if (count == 0) + return TRUE; + WINPR_ASSERT(ptr); + + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayEnabled, TRUE)) + goto fail; + + BOOL allowHttpOpts = FALSE; + for (size_t x = 0; x < count; x++) + { + BOOL validOption = FALSE; + const char* argval = ptr[x]; + + WINPR_ASSERT(argval); + + const char* gw = option_starts_with("g:", argval); + if (gw) + { + if (!parse_gateway_host_option(settings, gw)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* gu = option_starts_with("u:", argval); + if (gu) + { + if (!parse_gateway_cred_option(settings, gu, FreeRDP_GatewayUsername)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* gd = option_starts_with("d:", argval); + if (gd) + { + if (!parse_gateway_cred_option(settings, gd, FreeRDP_GatewayDomain)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* gp = option_starts_with("p:", argval); + if (gp) + { + if (!parse_gateway_cred_option(settings, gp, FreeRDP_GatewayPassword)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* gt = option_starts_with("type:", argval); + if (gt) + { + if (!parse_gateway_type_option(settings, gt)) + goto fail; + validOption = TRUE; + allowHttpOpts = freerdp_settings_get_bool(settings, FreeRDP_GatewayHttpTransport); + } + + const char* gat = option_starts_with("access-token:", argval); + if (gat) + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayAccessToken, gat)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* bearer = option_starts_with("bearer:", argval); + if (bearer) + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayHttpExtAuthBearer, bearer)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* gwurl = option_starts_with("url:", argval); + if (gwurl) + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayUrl, gwurl)) + goto fail; + if (!freerdp_set_gateway_usage_method(settings, TSC_PROXY_MODE_DIRECT)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + const char* um = option_starts_with("usage-method:", argval); + if (um) + { + if (!parse_gateway_usage_option(settings, um)) + goto fail; + validOption = TRUE; + allowHttpOpts = FALSE; + } + + if (allowHttpOpts) + { + if (option_equals(argval, "no-websockets")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpUseWebsockets, FALSE)) + goto fail; + validOption = TRUE; + } + else if (option_equals(argval, "extauth-sspi-ntlm")) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GatewayHttpExtAuthSspiNtlm, TRUE)) + goto fail; + validOption = TRUE; + } + } + + if (!validOption) + goto fail; + } + + rc = TRUE; +fail: + CommandLineParserFree(ptr); + return rc; +} + +static void fill_credential_string(COMMAND_LINE_ARGUMENT_A* args, const char* value) +{ + WINPR_ASSERT(args); + WINPR_ASSERT(value); + + const COMMAND_LINE_ARGUMENT_A* arg = CommandLineFindArgumentA(args, value); + if (!arg) + return; + + if (arg->Flags & COMMAND_LINE_VALUE_PRESENT) + FillMemory(arg->Value, strlen(arg->Value), '*'); +} + +static void fill_credential_strings(COMMAND_LINE_ARGUMENT_A* args) +{ + const char* credentials[] = { + "p", + "smartcard-logon", +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) + "gp", + "gat", +#endif + "pth", + "reconnect-cookie", + "assistance" + }; + + for (size_t x = 0; x < ARRAYSIZE(credentials); x++) + { + const char* cred = credentials[x]; + fill_credential_string(args, cred); + } + + const COMMAND_LINE_ARGUMENT_A* arg = CommandLineFindArgumentA(args, "gateway"); + if (arg && ((arg->Flags & COMMAND_LINE_ARGUMENT_PRESENT) != 0)) + { + const char* gwcreds[] = { "p:", "access-token:" }; + char* saveptr = NULL; + char* tok = strtok_s(arg->Value, ",", &saveptr); + while (tok) + { + for (size_t x = 0; x < ARRAYSIZE(gwcreds); x++) + { + const char* opt = gwcreds[x]; + if (option_starts_with(opt, tok)) + { + char* val = &tok[strlen(opt)]; + FillMemory(val, strlen(val), '*'); + } + } + tok = strtok_s(NULL, ",", &saveptr); + } + } +} + +static int parse_command_line_option_uint32(rdpSettings* settings, + const COMMAND_LINE_ARGUMENT_A* arg, + FreeRDP_Settings_Keys_UInt32 key, LONGLONG min, + LONGLONG max) +{ + LONGLONG val = 0; + + if (!value_to_int(arg->Value, &val, min, max)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + + if (!freerdp_settings_set_uint32(settings, key, (UINT32)val)) + return fail_at(arg, COMMAND_LINE_ERROR); + return 0; +} + +#if defined(WITH_FREERDP_DEPRECATED_COMMANDLINE) +static int parse_deprecated_command_line(rdpSettings* settings, const COMMAND_LINE_ARGUMENT_A* arg) +{ + int status = 0; + + WINPR_ASSERT(settings); + WINPR_ASSERT(arg); + + BOOL enable = arg->Value ? TRUE : FALSE; + CommandLineSwitchStart(arg) CommandLineSwitchCase(arg, "gfx-thin-client") + { + WLog_WARN(TAG, "/gfx-thin-client is deprecated, use /gfx:thin-client[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxThinClient, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + + if (freerdp_settings_get_bool(settings, FreeRDP_GfxThinClient)) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxSmallCache, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-small-cache") + { + WLog_WARN(TAG, "/gfx-small-cache is deprecated, use /gfx:small-cache[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxSmallCache, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + + if (enable) + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gfx-progressive") + { + WLog_WARN(TAG, "/gfx-progressive is deprecated, use /gfx:progressive[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxProgressive, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + if (!freerdp_settings_set_bool(settings, FreeRDP_GfxThinClient, !enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + + if (enable) + { + if (!freerdp_settings_set_bool(settings, FreeRDP_SupportGraphicsPipeline, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + } +#ifdef WITH_GFX_H264 + CommandLineSwitchCase(arg, "gfx-h264") + { + WLog_WARN(TAG, "/gfx-h264 is deprecated, use /gfx:avc420 instead"); + int rc = parse_gfx_options(settings, arg); + if (rc != 0) + return fail_at(arg, rc); + } +#endif + CommandLineSwitchCase(arg, "app-workdir") + { + WLog_WARN(TAG, + "/app-workdir: is deprecated, use /app:workdir: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationWorkingDir, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "app-name") + { + WLog_WARN(TAG, "/app-name: is deprecated, use /app:name: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationName, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "app-icon") + { + WLog_WARN(TAG, "/app-icon: is deprecated, use /app:icon: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationIcon, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "app-cmd") + { + WLog_WARN(TAG, "/app-cmd: is deprecated, use /app:cmd: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationCmdLine, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "app-file") + { + WLog_WARN(TAG, "/app-file: is deprecated, use /app:file: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationFile, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "app-guid") + { + WLog_WARN(TAG, "/app-guid: is deprecated, use /app:guid: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_RemoteApplicationGuid, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "g") + { + if (!parse_gateway_host_option(settings, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "gu") + { + if (!parse_gateway_cred_option(settings, arg->Value, FreeRDP_GatewayUsername)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "gd") + { + if (!parse_gateway_cred_option(settings, arg->Value, FreeRDP_GatewayDomain)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "gp") + { + if (!parse_gateway_cred_option(settings, arg->Value, FreeRDP_GatewayPassword)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "gt") + { + if (!parse_gateway_type_option(settings, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "gat") + { + if (!freerdp_settings_set_string(settings, FreeRDP_GatewayAccessToken, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "gateway-usage-method") + { + if (!parse_gateway_usage_option(settings, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "kbd-remap") + { + WLog_WARN(TAG, "/kbd-remap:=,= is deprecated, use " + "/kbd:remap:=,remap:=,... instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_KeyboardRemappingList, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + } + CommandLineSwitchCase(arg, "kbd-lang") + { + LONGLONG val = 0; + + WLog_WARN(TAG, "/kbd-lang: is deprecated, use /kbd:lang: instead"); + if (!value_to_int(arg->Value, &val, 1, UINT32_MAX)) + { + WLog_ERR(TAG, "Could not identify keyboard active language %s", arg->Value); + WLog_ERR(TAG, "Use /list:kbd-lang to list available layouts"); + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + + if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardCodePage, (UINT32)val)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "kbd-type") + { + WLog_WARN(TAG, "/kbd-type: is deprecated, use /kbd:type: instead"); + const int rc = + parse_command_line_option_uint32(settings, arg, FreeRDP_KeyboardType, 0, UINT32_MAX); + if (rc != 0) + return fail_at(arg, rc); + } + CommandLineSwitchCase(arg, "kbd-unicode") + { + WLog_WARN(TAG, "/kbd-unicode is deprecated, use /kbd:unicode[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_UnicodeInput, enable)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "kbd-subtype") + { + WLog_WARN(TAG, "/kbd-subtype: is deprecated, use /kbd:subtype: instead"); + const int rc = + parse_command_line_option_uint32(settings, arg, FreeRDP_KeyboardSubType, 0, UINT32_MAX); + if (rc != 0) + return fail_at(arg, rc); + } + CommandLineSwitchCase(arg, "kbd-fn-key") + { + WLog_WARN(TAG, "/kbd-fn-key: is deprecated, use /kbd:fn-key: instead"); + const int rc = parse_command_line_option_uint32(settings, arg, FreeRDP_KeyboardFunctionKey, + 0, UINT32_MAX); + if (rc != 0) + return fail_at(arg, rc); + } + CommandLineSwitchCase(arg, "bitmap-cache") + { + WLog_WARN(TAG, "/bitmap-cache is deprecated, use /cache:bitmap[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCacheEnabled, enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "persist-cache") + { + WLog_WARN(TAG, "/persist-cache is deprecated, use /cache:persist[:on|off] instead"); + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCachePersistEnabled, enable)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "persist-cache-file") + { + WLog_WARN(TAG, "/persist-cache-file: is deprecated, use " + "/cache:persist-file: instead"); + if (!freerdp_settings_set_string(settings, FreeRDP_BitmapCachePersistFile, arg->Value)) + return fail_at(arg, COMMAND_LINE_ERROR_MEMORY); + + if (!freerdp_settings_set_bool(settings, FreeRDP_BitmapCachePersistEnabled, TRUE)) + return fail_at(arg, COMMAND_LINE_ERROR_UNEXPECTED_VALUE); + } + CommandLineSwitchCase(arg, "offscreen-cache") + { + WLog_WARN(TAG, "/bitmap-cache is deprecated, use /cache:bitmap[:on|off] instead"); + if (!freerdp_settings_set_uint32(settings, FreeRDP_OffscreenSupportLevel, (UINT32)enable)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "glyph-cache") + { + WLog_WARN(TAG, "/glyph-cache is deprecated, use /cache:glyph[:on|off] instead"); + if (!freerdp_settings_set_uint32(settings, FreeRDP_GlyphSupportLevel, + arg->Value ? GLYPH_SUPPORT_FULL : GLYPH_SUPPORT_NONE)) + return fail_at(arg, COMMAND_LINE_ERROR); + } + CommandLineSwitchCase(arg, "codec-cache") + { + WLog_WARN(TAG, "/codec-cache: