Kitxuuu commited on
Commit
9cbbf63
·
verified ·
1 Parent(s): 12fb50f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/lint.xml +2 -0
  2. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/src/main/AndroidManifest.xml +107 -0
  3. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/src/main/res/values/strings.xml +7 -0
  4. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/build.gradle +70 -0
  5. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/freeRDPCore/build.gradle +66 -0
  6. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/freeRDPCore/lint.xml +2 -0
  7. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/gradle.properties +3 -0
  8. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/gradlew +160 -0
  9. local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/settings.gradle +2 -0
  10. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/CMakeLists.txt +72 -0
  11. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/CMakeLists.txt +30 -0
  12. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/sdl2_resource_manager.cpp +37 -0
  13. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/sdl2_resource_manager.hpp +38 -0
  14. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_button.cpp +71 -0
  15. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_button.hpp +27 -0
  16. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_buttons.cpp +112 -0
  17. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_buttons.hpp +38 -0
  18. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp +539 -0
  19. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_connection_dialog.hpp +131 -0
  20. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_dialogs.cpp +623 -0
  21. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_dialogs.hpp +53 -0
  22. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input.cpp +177 -0
  23. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input.hpp +73 -0
  24. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp +299 -0
  25. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input_widgets.hpp +44 -0
  26. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_select.cpp +72 -0
  27. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_select.hpp +47 -0
  28. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_selectlist.cpp +217 -0
  29. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_selectlist.hpp +41 -0
  30. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_widget.cpp +290 -0
  31. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_widget.hpp +90 -0
  32. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/test/CMakeLists.txt +25 -0
  33. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/test/TestSDLDialogs.cpp +99 -0
  34. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/man/CMakeLists.txt +8 -0
  35. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/man/sdl2-freerdp.1.in +15 -0
  36. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/font/OFL.txt +93 -0
  37. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/font/README.txt +100 -0
  38. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/res/CMakeLists.txt +29 -0
  39. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/sdl_input.hpp +73 -0
  40. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/sdl_selectlist.cpp +215 -0
  41. local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/test/CMakeLists.txt +25 -0
  42. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/CMakeLists.txt +63 -0
  43. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/dummy.cpp +0 -0
  44. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/qt/webview_impl.cpp +105 -0
  45. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_config.hpp.in +3 -0
  46. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_webview.cpp +154 -0
  47. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_webview.hpp +38 -0
  48. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/webview_impl.hpp +24 -0
  49. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/wrapper/README +1 -0
  50. local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/wrapper/webview.h +2811 -0
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/lint.xml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <lint></lint>
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/src/main/AndroidManifest.xml ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+
3
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
4
+ android:installLocation="auto">
5
+
6
+ <application
7
+ android:name="com.freerdp.afreerdp.application.GlobalApp"
8
+ android:icon="@drawable/icon_launcher_freerdp"
9
+ android:label="aFreeRDP"
10
+ android:resizeableActivity="true">
11
+
12
+ <!-- Main activity -->
13
+ <activity
14
+ android:exported="true"
15
+ android:name="com.freerdp.freerdpcore.presentation.HomeActivity"
16
+ android:alwaysRetainTaskState="true"
17
+ android:label="@string/app_title"
18
+ android:theme="@style/Theme.Main"
19
+ android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|density|screenLayout">
20
+
21
+ <intent-filter android:label="@string/app_title">
22
+ <action android:name="android.intent.action.MAIN" />
23
+ <category android:name="android.intent.category.LAUNCHER" />
24
+ </intent-filter>
25
+ <intent-filter>
26
+ <action android:name="android.intent.action.VIEW" />
27
+
28
+ <category android:name="android.intent.category.DEFAULT" />
29
+ <category android:name="android.intent.category.BROWSABLE" />
30
+
31
+ <data android:mimeType="application/rdp" />
32
+ <data android:mimeType="application/x-rdp" />
33
+ </intent-filter>
34
+ <intent-filter>
35
+ <action android:name="android.intent.action.VIEW" />
36
+
37
+ <category android:name="android.intent.category.DEFAULT" />
38
+ <category android:name="android.intent.category.BROWSABLE" />
39
+
40
+ <data android:scheme="rdp" />
41
+ <data android:scheme="Rdp" />
42
+ </intent-filter>
43
+ <intent-filter>
44
+ <action android:name="android.intent.action.VIEW" />
45
+
46
+ <category android:name="android.intent.category.DEFAULT" />
47
+ <category android:name="android.intent.category.BROWSABLE" />
48
+
49
+ <data android:scheme="file" />
50
+ <data android:scheme="http" />
51
+ <data android:scheme="https" />
52
+ <data android:scheme="content" />
53
+ <data android:host="*" />
54
+
55
+ <!-- Ugly hack to match all files with a dot in its name.
56
+ Remove if a better way is found / supported.
57
+ https://stackoverflow.com/questions/3400072/pathpattern-to-match-file-extension-does-not-work-if-a-period-exists-elsewhere-i/8599921#8599921
58
+ -->
59
+ <data android:pathPattern=".*\\.rdp" />
60
+ <data android:pathPattern=".*\\..*\\.rdp" />
61
+ <data android:pathPattern=".*\\..*\\..*\\.rdp" />
62
+ <data android:pathPattern=".*\\..*\\..*\\..*\\.rdp" />
63
+ <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.rdp" />
64
+ <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.rdp" />
65
+ <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.rdp" />
66
+ <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\..*\\.rdp" />
67
+ <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\..*\\..*\\.rdp" />
68
+ </intent-filter>
69
+ </activity>
70
+
71
+ <!-- Session request handler activity - used for search and internally to start sessions -->
72
+ <!-- This should actually be defined in FreeRDPCore lib but Android manifest merging will -->
73
+ <!-- append the libs manifest to the apps manifest and therefore aliasing is not possible -->
74
+ <activity
75
+ android:exported="true"
76
+ android:name="com.freerdp.freerdpcore.services.SessionRequestHandlerActivity"
77
+ android:excludeFromRecents="true"
78
+ android:noHistory="true"
79
+ android:theme="@android:style/Theme.NoDisplay">
80
+ <intent-filter>
81
+ <action android:name="android.intent.action.MAIN" />
82
+ </intent-filter>
83
+ </activity>
84
+
85
+ <activity-alias
86
+ android:exported="true"
87
+ android:name=".services.SessionRequestHandlerActivity"
88
+ android:targetActivity="com.freerdp.freerdpcore.services.SessionRequestHandlerActivity">
89
+ <intent-filter>
90
+ <action android:name="android.intent.action.SEARCH" />
91
+ </intent-filter>
92
+ <meta-data
93
+ android:name="android.app.searchable"
94
+ android:resource="@xml/searchable" />
95
+ </activity-alias>
96
+
97
+ <provider
98
+ android:name="com.freerdp.freerdpcore.services.FreeRDPSuggestionProvider"
99
+ android:authorities="com.freerdp.afreerdp.services.freerdpsuggestionprovider"
100
+ android:exported="false"></provider>
101
+
102
+ <meta-data android:name="com.samsung.android.keepalive.density" android:value="true"/>
103
+
104
+ </application>
105
+
106
+ </manifest>
107
+
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/aFreeRDP/src/main/res/values/strings.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <resources>
3
+ <string name="app_title" translatable="false">aFreeRDP</string>
4
+ <!-- Search strings -->
5
+ <string name="search_label" translatable="false">aFreeRDP</string>
6
+ <string name="search_settings_description">Remote Computers</string>
7
+ </resources>
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/build.gradle ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Top-level build file where you can add configuration options common to all sub-projects/modules.
2
+ Properties releaseProperties = new Properties()
3
+ File file = new File('release.properties')
4
+ if (file.canRead()) {
5
+ releaseProperties.load(new FileInputStream(file))
6
+ }
7
+
8
+ if (!hasProperty('RELEASE_STORE_FILE')) {
9
+ RELEASE_STORE_FILE=releaseProperties.get('RELEASE_STORE_FILE', '~/.android/debug.keystore')
10
+ }
11
+ if (!hasProperty('RELEASE_KEY_ALIAS')) {
12
+ RELEASE_KEY_ALIAS=releaseProperties.get('RELEASE_KEY_ALIAS', 'androiddebugkey')
13
+ }
14
+ if (!hasProperty('RELEASE_KEY_PASSWORD')) {
15
+ RELEASE_KEY_PASSWORD=releaseProperties.get('RELEASE_KEY_PASSWORD', 'android')
16
+ }
17
+ if (!hasProperty('RELEASE_STORE_PASSWORD')) {
18
+ RELEASE_STORE_PASSWORD=releaseProperties.get('RELEASE_STORE_PASSWORD', 'android')
19
+ }
20
+
21
+ ext {
22
+ compileApi = releaseProperties.get('COMPILE_API', 35)
23
+ targetApi = releaseProperties.get('TARGET_API', 35)
24
+ minApi = releaseProperties.get('MIN_API', 23)
25
+ toolsVersion = releaseProperties.get('TOOLS_VERSION', '35.0.0')
26
+
27
+ println '----------------- Project configuration -------------------'
28
+ println 'RELEASE_STORE_FILE: ' + RELEASE_STORE_FILE
29
+ println 'RELEASE_KEY_ALIAS: ' + RELEASE_KEY_ALIAS
30
+ println 'compile API: ' + compileApi
31
+ println 'target API: ' + targetApi
32
+ println 'min API: ' + minApi
33
+ println 'tools version: ' + toolsVersion
34
+ println '-----------------------------------------------------------'
35
+ }
36
+
37
+ buildscript {
38
+ repositories {
39
+ mavenCentral()
40
+ google()
41
+ maven {
42
+ url 'https://maven.google.com'
43
+ }
44
+ }
45
+ dependencies {
46
+ classpath 'com.android.tools.build:gradle:8.8.0'
47
+ }
48
+ }
49
+
50
+ allprojects {
51
+ repositories {
52
+ mavenCentral()
53
+ google()
54
+ maven {
55
+ url 'https://maven.google.com'
56
+ }
57
+ }
58
+
59
+ subprojects {
60
+ afterEvaluate { project ->
61
+ if (project.hasProperty('android')) {
62
+ project.android {
63
+ if (namespace == null) {
64
+ namespace 'com.freerdp.' + project.name.toLowerCase()
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
70
+ }
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/freeRDPCore/build.gradle ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ apply plugin: 'com.android.library'
2
+
3
+ android {
4
+ compileSdkVersion = rootProject.ext.compileApi
5
+ buildToolsVersion = rootProject.ext.toolsVersion
6
+ packagingOptions {
7
+ jniLibs {
8
+ pickFirsts += ['lib/arm64-v8a/libfreerdp3.so', 'lib/armeabi-v7a/libfreerdp3.so', 'lib/x86/libfreerdp3.so', 'lib/x86_64/libfreerdp3.so', 'lib/arm64-v8a/libfreerdp-client3.so', 'lib/armeabi-v7a/libfreerdp-client3.so', 'lib/x86/libfreerdp-client3.so', 'lib/x86_64/libfreerdp-client3.so', 'lib/arm64-v8a/libwinpr3.so', 'lib/armeabi-v7a/libwinpr3.so', 'lib/x86/libwinpr3.so', 'lib/x86_64/libwinpr3.so']
9
+ }
10
+ }
11
+
12
+
13
+ defaultConfig {
14
+ minSdkVersion rootProject.ext.minApi
15
+ targetSdkVersion rootProject.ext.targetApi
16
+ vectorDrawables.useSupportLibrary = true
17
+ ndkVersion = "27.2.12479018"
18
+
19
+ ndk {
20
+ File jniLibsDirectory = new File(project.projectDir, "src/main/jniLibs")
21
+ ArrayList<String> abiFiltersList = new ArrayList<String>()
22
+ if (new File(jniLibsDirectory, "arm64-v8a/libfreerdp3.so").exists())
23
+ abiFiltersList.add("arm64-v8a")
24
+ if (new File(jniLibsDirectory, "armeabi-v7a/libfreerdp3.so").exists())
25
+ abiFiltersList.add("armeabi-v7a")
26
+ if (new File(jniLibsDirectory, "x86_64/libfreerdp3.so").exists())
27
+ abiFiltersList.add("x86_64")
28
+ if (new File(jniLibsDirectory, "x86/libfreerdp3.so").exists())
29
+ abiFiltersList.add("x86")
30
+
31
+ abiFilters = abiFiltersList
32
+ }
33
+
34
+ externalNativeBuild {
35
+ cmake {
36
+ arguments "-DWITH_CLIENT_CHANNELS=ON"
37
+ }
38
+ }
39
+ }
40
+
41
+ buildTypes {
42
+ release {
43
+ minifyEnabled false
44
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
45
+ }
46
+ debug {
47
+ jniDebuggable true
48
+ renderscriptDebuggable true
49
+ }
50
+ }
51
+ compileOptions {
52
+ sourceCompatibility JavaVersion.VERSION_1_8
53
+ targetCompatibility JavaVersion.VERSION_1_8
54
+ }
55
+ externalNativeBuild {
56
+ cmake {
57
+ path file('src/main/cpp/CMakeLists.txt')
58
+ }
59
+ }
60
+ }
61
+
62
+ dependencies {
63
+ implementation 'com.android.support:appcompat-v7:28.0.0'
64
+ implementation 'com.android.support:support-v4:28.0.0'
65
+ implementation 'com.android.support:support-vector-drawable:28.0.0'
66
+ }
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/freeRDPCore/lint.xml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <lint></lint>
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/gradle.properties ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ org.gradle.jvmargs=-Xmx4096M
2
+ android.useAndroidX = true
3
+ android.enableJetifier = true
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/gradlew ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ ##############################################################################
4
+ ##
5
+ ## Gradle start up script for UN*X
6
+ ##
7
+ ##############################################################################
8
+
9
+ # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10
+ DEFAULT_JVM_OPTS=""
11
+
12
+ APP_NAME="Gradle"
13
+ APP_BASE_NAME=`basename "$0"`
14
+
15
+ # Use the maximum available, or set MAX_FD != -1 to use that value.
16
+ MAX_FD="maximum"
17
+
18
+ warn ( ) {
19
+ echo "$*"
20
+ }
21
+
22
+ die ( ) {
23
+ echo
24
+ echo "$*"
25
+ echo
26
+ exit 1
27
+ }
28
+
29
+ # OS specific support (must be 'true' or 'false').
30
+ cygwin=false
31
+ msys=false
32
+ darwin=false
33
+ case "`uname`" in
34
+ CYGWIN* )
35
+ cygwin=true
36
+ ;;
37
+ Darwin* )
38
+ darwin=true
39
+ ;;
40
+ MINGW* )
41
+ msys=true
42
+ ;;
43
+ esac
44
+
45
+ # Attempt to set APP_HOME
46
+ # Resolve links: $0 may be a link
47
+ PRG="$0"
48
+ # Need this for relative symlinks.
49
+ while [ -h "$PRG" ] ; do
50
+ ls=`ls -ld "$PRG"`
51
+ link=`expr "$ls" : '.*-> \(.*\)$'`
52
+ if expr "$link" : '/.*' > /dev/null; then
53
+ PRG="$link"
54
+ else
55
+ PRG=`dirname "$PRG"`"/$link"
56
+ fi
57
+ done
58
+ SAVED="`pwd`"
59
+ cd "`dirname \"$PRG\"`/" >/dev/null
60
+ APP_HOME="`pwd -P`"
61
+ cd "$SAVED" >/dev/null
62
+
63
+ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64
+
65
+ # Determine the Java command to use to start the JVM.
66
+ if [ -n "$JAVA_HOME" ] ; then
67
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68
+ # IBM's JDK on AIX uses strange locations for the executables
69
+ JAVACMD="$JAVA_HOME/jre/sh/java"
70
+ else
71
+ JAVACMD="$JAVA_HOME/bin/java"
72
+ fi
73
+ if [ ! -x "$JAVACMD" ] ; then
74
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75
+
76
+ Please set the JAVA_HOME variable in your environment to match the
77
+ location of your Java installation."
78
+ fi
79
+ else
80
+ JAVACMD="java"
81
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82
+
83
+ Please set the JAVA_HOME variable in your environment to match the
84
+ location of your Java installation."
85
+ fi
86
+
87
+ # Increase the maximum file descriptors if we can.
88
+ if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89
+ MAX_FD_LIMIT=`ulimit -H -n`
90
+ if [ $? -eq 0 ] ; then
91
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92
+ MAX_FD="$MAX_FD_LIMIT"
93
+ fi
94
+ ulimit -n $MAX_FD
95
+ if [ $? -ne 0 ] ; then
96
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
97
+ fi
98
+ else
99
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100
+ fi
101
+ fi
102
+
103
+ # For Darwin, add options to specify how the application appears in the dock
104
+ if $darwin; then
105
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106
+ fi
107
+
108
+ # For Cygwin, switch paths to Windows format before running java
109
+ if $cygwin ; then
110
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112
+ JAVACMD=`cygpath --unix "$JAVACMD"`
113
+
114
+ # We build the pattern for arguments to be converted via cygpath
115
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116
+ SEP=""
117
+ for dir in $ROOTDIRSRAW ; do
118
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
119
+ SEP="|"
120
+ done
121
+ OURCYGPATTERN="(^($ROOTDIRS))"
122
+ # Add a user-defined pattern to the cygpath arguments
123
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125
+ fi
126
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
127
+ i=0
128
+ for arg in "$@" ; do
129
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131
+
132
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134
+ else
135
+ eval `echo args$i`="\"$arg\""
136
+ fi
137
+ i=$((i+1))
138
+ done
139
+ case $i in
140
+ (0) set -- ;;
141
+ (1) set -- "$args0" ;;
142
+ (2) set -- "$args0" "$args1" ;;
143
+ (3) set -- "$args0" "$args1" "$args2" ;;
144
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150
+ esac
151
+ fi
152
+
153
+ # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154
+ function splitJvmOpts() {
155
+ JVM_OPTS=("$@")
156
+ }
157
+ eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158
+ JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159
+
160
+ exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
local-test-freerdp-delta-01/afc-freerdp/client/Android/Studio/settings.gradle ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ include ':freeRDPCore'
2
+ include ':aFreeRDP'
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/CMakeLists.txt ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set(SRCS
2
+ sdl_button.hpp
3
+ sdl_button.cpp
4
+ sdl_buttons.hpp
5
+ sdl_buttons.cpp
6
+ sdl_dialogs.cpp
7
+ sdl_dialogs.hpp
8
+ sdl_widget.hpp
9
+ sdl_widget.cpp
10
+ sdl_input.hpp
11
+ sdl_input.cpp
12
+ sdl_input_widgets.cpp
13
+ sdl_input_widgets.hpp
14
+ sdl_select.hpp
15
+ sdl_select.cpp
16
+ sdl_selectlist.hpp
17
+ sdl_selectlist.cpp
18
+ sdl_connection_dialog.cpp
19
+ sdl_connection_dialog.hpp
20
+ )
21
+
22
+ list(APPEND LIBS sdl2_client_res winpr)
23
+
24
+ if(NOT WITH_SDL_LINK_SHARED)
25
+ list(APPEND LIBS SDL2::SDL2-static)
26
+ else()
27
+ list(APPEND LIBS SDL2::SDL2)
28
+ endif()
29
+
30
+ macro(find_sdl_component name)
31
+ find_package(${name})
32
+ if(NOT ${name}_FOUND)
33
+ find_package(PkgConfig REQUIRED)
34
+ pkg_check_modules(${name} REQUIRED ${name})
35
+
36
+ if(BUILD_SHARED_LIBS)
37
+ list(APPEND LIBS ${${name}_LIBRARIES})
38
+ link_directories(${${name}_LIBRARY_DIRS})
39
+ include_directories(SYSTEM ${${name}_INCLUDE_DIRS})
40
+ else()
41
+ list(APPEND LIBS ${${name}_STATIC_LIBRARIES})
42
+ link_directories(${${name}_STATIC_LIBRARY_DIRS})
43
+ include_directories(SYSTEM ${${name}_STATIC_INCLUDE_DIRS})
44
+ endif()
45
+ else()
46
+ if(WITH_SDL_LINK_SHARED)
47
+ list(APPEND LIBS ${name}::${name})
48
+ set_target_properties(${name}::${name} PROPERTIES SYSTEM TRUE)
49
+ else()
50
+ list(APPEND LIBS ${name}::${name}-static)
51
+ set_target_properties(${name}::${name}-static PROPERTIES SYSTEM TRUE)
52
+ endif()
53
+ endif()
54
+ endmacro()
55
+
56
+ find_sdl_component(SDL2_ttf)
57
+
58
+ option(WITH_SDL_IMAGE_DIALOGS "Build with SDL_image support (recommended)" OFF)
59
+ if(WITH_SDL_IMAGE_DIALOGS)
60
+ find_sdl_component(SDL2_image)
61
+ add_compile_definitions(WITH_SDL_IMAGE_DIALOGS)
62
+ endif()
63
+
64
+ add_subdirectory(res)
65
+
66
+ add_library(sdl2-dialogs STATIC ${SRCS})
67
+
68
+ target_link_libraries(sdl2-dialogs PRIVATE ${LIBS})
69
+
70
+ if(BUILD_TESTING_INTERNAL OR BUILD_TESTING)
71
+ # add_subdirectory(test)
72
+ endif()
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/CMakeLists.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FreeRDP: A Remote Desktop Protocol Implementation
2
+ # FreeRDP SDL Client
3
+ #
4
+ # Copyright 2024 Armin Novak <[email protected]>
5
+ # Copyright 2024 Thincast Technologies GmbH
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ set(SRCS sdl2_resource_manager.cpp sdl2_resource_manager.hpp)
20
+
21
+ add_library(sdl2_client_res STATIC ${SRCS})
22
+
23
+ if(NOT WITH_SDL_LINK_SHARED)
24
+ target_link_libraries(sdl2_client_res ${SDL2_STATIC_LIBRARIES})
25
+ else()
26
+ target_link_libraries(sdl2_client_res ${SDL2_LIBRARIES})
27
+ endif()
28
+
29
+ set_target_properties(sdl2_client_res PROPERTIES POSITION_INDEPENDENT_CODE ON INTERPROCEDURAL_OPTIMIZATION OFF)
30
+ target_link_libraries(sdl2_client_res sdl-common-client-res)
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/sdl2_resource_manager.cpp ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ *
4
+ * Copyright 2023 Armin Novak <[email protected]>
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ #include "sdl2_resource_manager.hpp"
19
+ #include <iostream>
20
+
21
+ SDL_RWops* SDL2ResourceManager::get(const std::string& type, const std::string& id)
22
+ {
23
+ if (useCompiledResources())
24
+ {
25
+ auto d = data(type, id);
26
+ if (!d)
27
+ return nullptr;
28
+
29
+ auto s = d->size();
30
+ if (s > INT32_MAX)
31
+ return nullptr;
32
+ return SDL_RWFromConstMem(d->data(), static_cast<int>(s));
33
+ }
34
+
35
+ auto name = filename(type, id);
36
+ return SDL_RWFromFile(name.c_str(), "rb");
37
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/res/sdl2_resource_manager.hpp ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ *
4
+ * Copyright 2023 Armin Novak <[email protected]>
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+ #pragma once
19
+
20
+ #include <string>
21
+ #include <map>
22
+ #include <vector>
23
+ #include <SDL.h>
24
+
25
+ #include <res/sdl_resource_manager.hpp>
26
+
27
+ class SDL2ResourceManager : public SDLResourceManager
28
+ {
29
+ public:
30
+ SDL2ResourceManager() = delete;
31
+ SDL2ResourceManager(const SDL2ResourceManager& other) = delete;
32
+ SDL2ResourceManager(const SDL2ResourceManager&& other) = delete;
33
+ ~SDL2ResourceManager() = delete;
34
+ SDL2ResourceManager& operator=(const SDL2ResourceManager& other) = delete;
35
+ SDL2ResourceManager& operator=(SDL2ResourceManager&& other) = delete;
36
+
37
+ static SDL_RWops* get(const std::string& type, const std::string& id);
38
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_button.cpp ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client Channels
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ * Copyright 2023 Thincast Technologies GmbH
7
+ *
8
+ * Licensed under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License.
10
+ * You may obtain a copy of the License at
11
+ *
12
+ * http://www.apache.org/licenses/LICENSE-2.0
13
+ *
14
+ * Unless required by applicable law or agreed to in writing, software
15
+ * distributed under the License is distributed on an "AS IS" BASIS,
16
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ * See the License for the specific language governing permissions and
18
+ * limitations under the License.
19
+ */
20
+
21
+ #include <cassert>
22
+ #include <utility>
23
+
24
+ #include "sdl_button.hpp"
25
+
26
+ static const SDL_Color buttonbackgroundcolor = { 0x69, 0x66, 0x63, 0xff };
27
+ static const SDL_Color buttonhighlightcolor = { 0xcd, 0xca, 0x35, 0x60 };
28
+ static const SDL_Color buttonmouseovercolor = { 0x66, 0xff, 0x66, 0x60 };
29
+ static const SDL_Color buttonfontcolor = { 0xd1, 0xcf, 0xcd, 0xff };
30
+
31
+ SdlButton::SdlButton(SDL_Renderer* renderer, std::string label, int id, SDL_Rect rect)
32
+ : SdlWidget(renderer, rect, false), _name(std::move(label)), _id(id)
33
+ {
34
+ assert(renderer);
35
+
36
+ update_text(renderer, _name, buttonfontcolor, buttonbackgroundcolor);
37
+ }
38
+
39
+ SdlButton::SdlButton(SdlButton&& other) noexcept = default;
40
+
41
+ SdlButton::~SdlButton() = default;
42
+
43
+ bool SdlButton::highlight(SDL_Renderer* renderer)
44
+ {
45
+ assert(renderer);
46
+
47
+ std::vector<SDL_Color> colors = { buttonbackgroundcolor, buttonhighlightcolor };
48
+ if (!fill(renderer, colors))
49
+ return false;
50
+ return update_text(renderer, _name, buttonfontcolor);
51
+ }
52
+
53
+ bool SdlButton::mouseover(SDL_Renderer* renderer)
54
+ {
55
+ std::vector<SDL_Color> colors = { buttonbackgroundcolor, buttonmouseovercolor };
56
+ if (!fill(renderer, colors))
57
+ return false;
58
+ return update_text(renderer, _name, buttonfontcolor);
59
+ }
60
+
61
+ bool SdlButton::update(SDL_Renderer* renderer)
62
+ {
63
+ assert(renderer);
64
+
65
+ return update_text(renderer, _name, buttonfontcolor, buttonbackgroundcolor);
66
+ }
67
+
68
+ int SdlButton::id() const
69
+ {
70
+ return _id;
71
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_button.hpp ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+
5
+ #include "sdl_widget.hpp"
6
+
7
+ class SdlButton : public SdlWidget
8
+ {
9
+ public:
10
+ SdlButton(SDL_Renderer* renderer, std::string label, int id, SDL_Rect rect);
11
+ SdlButton(const SdlButton& other) = delete;
12
+ SdlButton(SdlButton&& other) noexcept;
13
+ ~SdlButton() override;
14
+
15
+ SdlButton& operator=(const SdlButton& other) = delete;
16
+ SdlButton& operator=(SdlButton&& other) = delete;
17
+
18
+ bool highlight(SDL_Renderer* renderer);
19
+ bool mouseover(SDL_Renderer* renderer);
20
+ bool update(SDL_Renderer* renderer);
21
+
22
+ [[nodiscard]] int id() const;
23
+
24
+ private:
25
+ std::string _name;
26
+ int _id;
27
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_buttons.cpp ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cassert>
2
+ #include <algorithm>
3
+
4
+ #include <winpr/cast.h>
5
+
6
+ #include "sdl_buttons.hpp"
7
+
8
+ static const Uint32 hpadding = 10;
9
+
10
+ SdlButtonList::~SdlButtonList() = default;
11
+
12
+ bool SdlButtonList::populate(SDL_Renderer* renderer, const std::vector<std::string>& labels,
13
+ const std::vector<int>& ids, Sint32 total_width, Sint32 offsetY,
14
+ Sint32 width, Sint32 height)
15
+ {
16
+ assert(renderer);
17
+ assert(width >= 0);
18
+ assert(height >= 0);
19
+ assert(labels.size() == ids.size());
20
+
21
+ _list.clear();
22
+ size_t button_width =
23
+ ids.size() * (WINPR_ASSERTING_INT_CAST(uint32_t, width) + hpadding) + hpadding;
24
+ size_t offsetX =
25
+ WINPR_ASSERTING_INT_CAST(uint32_t, total_width) -
26
+ std::min<size_t>(WINPR_ASSERTING_INT_CAST(uint32_t, total_width), button_width);
27
+ for (size_t x = 0; x < ids.size(); x++)
28
+ {
29
+ const size_t curOffsetX = offsetX + x * (static_cast<size_t>(width) + hpadding);
30
+ const SDL_Rect rect = { static_cast<int>(curOffsetX), offsetY, width, height };
31
+ _list.emplace_back(renderer, labels[x], ids[x], rect);
32
+ }
33
+ return true;
34
+ }
35
+
36
+ SdlButton* SdlButtonList::get_selected(const SDL_MouseButtonEvent& button)
37
+ {
38
+ const Sint32 x = button.x;
39
+ const Sint32 y = button.y;
40
+
41
+ return get_selected(x, y);
42
+ }
43
+
44
+ SdlButton* SdlButtonList::get_selected(Sint32 x, Sint32 y)
45
+ {
46
+ for (auto& btn : _list)
47
+ {
48
+ auto r = btn.rect();
49
+ if ((x >= r.x) && (x <= r.x + r.w) && (y >= r.y) && (y <= r.y + r.h))
50
+ return &btn;
51
+ }
52
+ return nullptr;
53
+ }
54
+
55
+ bool SdlButtonList::set_highlight_next(bool reset)
56
+ {
57
+ if (reset)
58
+ _highlighted = nullptr;
59
+ else
60
+ {
61
+ auto next = _highlight_index++;
62
+ _highlight_index %= _list.size();
63
+ auto& element = _list[next];
64
+ _highlighted = &element;
65
+ }
66
+ return true;
67
+ }
68
+
69
+ bool SdlButtonList::set_highlight(size_t index)
70
+ {
71
+ if (index >= _list.size())
72
+ {
73
+ _highlighted = nullptr;
74
+ return false;
75
+ }
76
+ auto& element = _list[index];
77
+ _highlighted = &element;
78
+ _highlight_index = ++index % _list.size();
79
+ return true;
80
+ }
81
+
82
+ bool SdlButtonList::set_mouseover(Sint32 x, Sint32 y)
83
+ {
84
+ _mouseover = get_selected(x, y);
85
+ return _mouseover != nullptr;
86
+ }
87
+
88
+ void SdlButtonList::clear()
89
+ {
90
+ _list.clear();
91
+ _mouseover = nullptr;
92
+ _highlighted = nullptr;
93
+ _highlight_index = 0;
94
+ }
95
+
96
+ bool SdlButtonList::update(SDL_Renderer* renderer)
97
+ {
98
+ assert(renderer);
99
+
100
+ for (auto& btn : _list)
101
+ {
102
+ if (!btn.update(renderer))
103
+ return false;
104
+ }
105
+
106
+ if (_highlighted)
107
+ _highlighted->highlight(renderer);
108
+
109
+ if (_mouseover)
110
+ _mouseover->mouseover(renderer);
111
+ return true;
112
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_buttons.hpp ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <vector>
4
+ #include <cstdint>
5
+
6
+ #include "sdl_button.hpp"
7
+
8
+ class SdlButtonList
9
+ {
10
+ public:
11
+ SdlButtonList() = default;
12
+ virtual ~SdlButtonList();
13
+
14
+ bool populate(SDL_Renderer* renderer, const std::vector<std::string>& labels,
15
+ const std::vector<int>& ids, Sint32 total_width, Sint32 offsetY, Sint32 width,
16
+ Sint32 height);
17
+
18
+ bool update(SDL_Renderer* renderer);
19
+ SdlButton* get_selected(const SDL_MouseButtonEvent& button);
20
+ SdlButton* get_selected(Sint32 x, Sint32 y);
21
+
22
+ bool set_highlight_next(bool reset = false);
23
+ bool set_highlight(size_t index);
24
+ bool set_mouseover(Sint32 x, Sint32 y);
25
+
26
+ void clear();
27
+
28
+ SdlButtonList(const SdlButtonList& other) = delete;
29
+ SdlButtonList(SdlButtonList&& other) = delete;
30
+ SdlButtonList& operator=(const SdlButtonList& other) = delete;
31
+ SdlButtonList& operator=(SdlButtonList&& other) = delete;
32
+
33
+ private:
34
+ std::vector<SdlButton> _list;
35
+ SdlButton* _highlighted = nullptr;
36
+ size_t _highlight_index = 0;
37
+ SdlButton* _mouseover = nullptr;
38
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_connection_dialog.cpp ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ #include <cassert>
20
+ #include <thread>
21
+
22
+ #include "sdl_connection_dialog.hpp"
23
+ #include "../sdl_utils.hpp"
24
+ #include "../sdl_freerdp.hpp"
25
+ #include "res/sdl2_resource_manager.hpp"
26
+
27
+ static const SDL_Color backgroundcolor = { 0x38, 0x36, 0x35, 0xff };
28
+ static const SDL_Color textcolor = { 0xd1, 0xcf, 0xcd, 0xff };
29
+ static const SDL_Color infocolor = { 0x43, 0xe0, 0x0f, 0x60 };
30
+ static const SDL_Color warncolor = { 0xcd, 0xca, 0x35, 0x60 };
31
+ static const SDL_Color errorcolor = { 0xf7, 0x22, 0x30, 0x60 };
32
+
33
+ static const Uint32 vpadding = 5;
34
+ static const Uint32 hpadding = 5;
35
+
36
+ SDLConnectionDialog::SDLConnectionDialog(rdpContext* context) : _context(context)
37
+ {
38
+ SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
39
+ hide();
40
+ }
41
+
42
+ SDLConnectionDialog::~SDLConnectionDialog()
43
+ {
44
+ resetTimer();
45
+ destroyWindow();
46
+ SDL_Quit();
47
+ }
48
+
49
+ bool SDLConnectionDialog::visible() const
50
+ {
51
+ if (!_window || !_renderer)
52
+ return false;
53
+
54
+ auto flags = SDL_GetWindowFlags(_window);
55
+ return (flags & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) == 0;
56
+ }
57
+
58
+ bool SDLConnectionDialog::setTitle(const char* fmt, ...)
59
+ {
60
+ std::lock_guard lock(_mux);
61
+ va_list ap = {};
62
+ va_start(ap, fmt);
63
+ _title = print(fmt, ap);
64
+ va_end(ap);
65
+
66
+ return show(MSG_NONE);
67
+ }
68
+
69
+ bool SDLConnectionDialog::showInfo(const char* fmt, ...)
70
+ {
71
+ va_list ap = {};
72
+ va_start(ap, fmt);
73
+ auto rc = show(MSG_INFO, fmt, ap);
74
+ va_end(ap);
75
+ return rc;
76
+ }
77
+
78
+ bool SDLConnectionDialog::showWarn(const char* fmt, ...)
79
+ {
80
+ va_list ap = {};
81
+ va_start(ap, fmt);
82
+ auto rc = show(MSG_WARN, fmt, ap);
83
+ va_end(ap);
84
+ return rc;
85
+ }
86
+
87
+ bool SDLConnectionDialog::showError(const char* fmt, ...)
88
+ {
89
+ va_list ap = {};
90
+ va_start(ap, fmt);
91
+ auto rc = show(MSG_ERROR, fmt, ap);
92
+ va_end(ap);
93
+ if (!rc)
94
+ return rc;
95
+ return setTimer();
96
+ }
97
+
98
+ bool SDLConnectionDialog::show()
99
+ {
100
+ std::lock_guard lock(_mux);
101
+ return show(_type_active);
102
+ }
103
+
104
+ bool SDLConnectionDialog::hide()
105
+ {
106
+ std::lock_guard lock(_mux);
107
+ return show(MSG_DISCARD);
108
+ }
109
+
110
+ bool SDLConnectionDialog::running() const
111
+ {
112
+ std::lock_guard lock(_mux);
113
+ return _running;
114
+ }
115
+
116
+ bool SDLConnectionDialog::update()
117
+ {
118
+ std::lock_guard lock(_mux);
119
+ switch (_type)
120
+ {
121
+ case MSG_INFO:
122
+ case MSG_WARN:
123
+ case MSG_ERROR:
124
+ _type_active = _type;
125
+ createWindow();
126
+ break;
127
+ case MSG_DISCARD:
128
+ resetTimer();
129
+ destroyWindow();
130
+ break;
131
+ default:
132
+ if (_window)
133
+ {
134
+ SDL_SetWindowTitle(_window, _title.c_str());
135
+ }
136
+ break;
137
+ }
138
+ _type = MSG_NONE;
139
+ return true;
140
+ }
141
+
142
+ bool SDLConnectionDialog::setModal()
143
+ {
144
+ if (_window)
145
+ {
146
+ auto sdl = get_context(_context);
147
+ if (sdl->windows.empty())
148
+ return true;
149
+
150
+ auto parent = sdl->windows.begin()->second.window();
151
+ SDL_SetWindowModalFor(_window, parent);
152
+ SDL_RaiseWindow(_window);
153
+ }
154
+ return true;
155
+ }
156
+
157
+ bool SDLConnectionDialog::clearWindow(SDL_Renderer* renderer)
158
+ {
159
+ assert(renderer);
160
+
161
+ const int drc = SDL_SetRenderDrawColor(renderer, backgroundcolor.r, backgroundcolor.g,
162
+ backgroundcolor.b, backgroundcolor.a);
163
+ if (widget_log_error(drc, "SDL_SetRenderDrawColor"))
164
+ return false;
165
+
166
+ const int rcls = SDL_RenderClear(renderer);
167
+ return !widget_log_error(rcls, "SDL_RenderClear");
168
+ }
169
+
170
+ bool SDLConnectionDialog::update(SDL_Renderer* renderer)
171
+ {
172
+ std::lock_guard lock(_mux);
173
+ if (!renderer)
174
+ return false;
175
+
176
+ if (!clearWindow(renderer))
177
+ return false;
178
+
179
+ for (auto& btn : _list)
180
+ {
181
+ if (!btn.widget.update_text(renderer, _msg, btn.fgcolor, btn.bgcolor))
182
+ return false;
183
+ }
184
+
185
+ if (!_buttons.update(renderer))
186
+ return false;
187
+
188
+ SDL_RenderPresent(renderer);
189
+ return true;
190
+ }
191
+
192
+ bool SDLConnectionDialog::wait(bool ignoreRdpContext)
193
+ {
194
+ while (running())
195
+ {
196
+ if (!ignoreRdpContext)
197
+ {
198
+ if (freerdp_shall_disconnect_context(_context))
199
+ return false;
200
+ }
201
+ std::this_thread::yield();
202
+ }
203
+ return true;
204
+ }
205
+
206
+ bool SDLConnectionDialog::handle(const SDL_Event& event)
207
+ {
208
+ Uint32 windowID = 0;
209
+ if (_window)
210
+ {
211
+ windowID = SDL_GetWindowID(_window);
212
+ }
213
+
214
+ switch (event.type)
215
+ {
216
+ case SDL_USEREVENT_RETRY_DIALOG:
217
+ return update();
218
+ case SDL_QUIT:
219
+ resetTimer();
220
+ destroyWindow();
221
+ return false;
222
+ case SDL_KEYDOWN:
223
+ case SDL_KEYUP:
224
+ if (visible())
225
+ {
226
+ auto& ev = reinterpret_cast<const SDL_KeyboardEvent&>(event);
227
+ update(_renderer);
228
+ switch (event.key.keysym.sym)
229
+ {
230
+ case SDLK_RETURN:
231
+ case SDLK_RETURN2:
232
+ case SDLK_ESCAPE:
233
+ case SDLK_KP_ENTER:
234
+ if (event.type == SDL_KEYUP)
235
+ {
236
+ freerdp_abort_event(_context);
237
+ sdl_push_quit();
238
+ }
239
+ break;
240
+ case SDLK_TAB:
241
+ _buttons.set_highlight_next();
242
+ break;
243
+ default:
244
+ break;
245
+ }
246
+
247
+ return windowID == ev.windowID;
248
+ }
249
+ return false;
250
+ case SDL_MOUSEMOTION:
251
+ if (visible())
252
+ {
253
+ auto& ev = reinterpret_cast<const SDL_MouseMotionEvent&>(event);
254
+
255
+ _buttons.set_mouseover(event.button.x, event.button.y);
256
+ update(_renderer);
257
+ return windowID == ev.windowID;
258
+ }
259
+ return false;
260
+ case SDL_MOUSEBUTTONDOWN:
261
+ case SDL_MOUSEBUTTONUP:
262
+ if (visible())
263
+ {
264
+ auto& ev = reinterpret_cast<const SDL_MouseButtonEvent&>(event);
265
+ update(_renderer);
266
+
267
+ auto button = _buttons.get_selected(event.button);
268
+ if (button)
269
+ {
270
+ if (event.type == SDL_MOUSEBUTTONUP)
271
+ {
272
+ freerdp_abort_event(_context);
273
+ sdl_push_quit();
274
+ }
275
+ }
276
+
277
+ return windowID == ev.windowID;
278
+ }
279
+ return false;
280
+ case SDL_MOUSEWHEEL:
281
+ if (visible())
282
+ {
283
+ auto& ev = reinterpret_cast<const SDL_MouseWheelEvent&>(event);
284
+ update(_renderer);
285
+ return windowID == ev.windowID;
286
+ }
287
+ return false;
288
+ case SDL_FINGERUP:
289
+ case SDL_FINGERDOWN:
290
+ if (visible())
291
+ {
292
+ auto& ev = reinterpret_cast<const SDL_TouchFingerEvent&>(event);
293
+ update(_renderer);
294
+ #if SDL_VERSION_ATLEAST(2, 0, 18)
295
+ return windowID == ev.windowID;
296
+ #else
297
+ return false;
298
+ #endif
299
+ }
300
+ return false;
301
+ case SDL_WINDOWEVENT:
302
+ {
303
+ auto& ev = reinterpret_cast<const SDL_WindowEvent&>(event);
304
+ switch (ev.event)
305
+ {
306
+ case SDL_WINDOWEVENT_CLOSE:
307
+ if (windowID == ev.windowID)
308
+ {
309
+ freerdp_abort_event(_context);
310
+ sdl_push_quit();
311
+ }
312
+ break;
313
+ default:
314
+ update(_renderer);
315
+ setModal();
316
+ break;
317
+ }
318
+
319
+ return windowID == ev.windowID;
320
+ }
321
+ default:
322
+ return false;
323
+ }
324
+ }
325
+
326
+ bool SDLConnectionDialog::createWindow()
327
+ {
328
+ destroyWindow();
329
+
330
+ const int widget_height = 50;
331
+ const int widget_width = 600;
332
+ const int total_height = 300;
333
+
334
+ auto flags = WINPR_ASSERTING_INT_CAST(
335
+ uint32_t, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS);
336
+ auto rc = SDL_CreateWindowAndRenderer(widget_width, total_height, flags, &_window, &_renderer);
337
+ if (rc != 0)
338
+ {
339
+ widget_log_error(rc, "SDL_CreateWindowAndRenderer");
340
+ return false;
341
+ }
342
+ SDL_SetWindowTitle(_window, _title.c_str());
343
+ setModal();
344
+
345
+ SDL_Color res_bgcolor;
346
+ switch (_type_active)
347
+ {
348
+ case MSG_INFO:
349
+ res_bgcolor = infocolor;
350
+ break;
351
+ case MSG_WARN:
352
+ res_bgcolor = warncolor;
353
+ break;
354
+ case MSG_ERROR:
355
+ res_bgcolor = errorcolor;
356
+ break;
357
+ case MSG_DISCARD:
358
+ default:
359
+ res_bgcolor = backgroundcolor;
360
+ break;
361
+ }
362
+
363
+ #if defined(WITH_SDL_IMAGE_DIALOGS)
364
+ std::string res_name;
365
+ switch (_type_active)
366
+ {
367
+ case MSG_INFO:
368
+ res_name = "icon_info.svg";
369
+ break;
370
+ case MSG_WARN:
371
+ res_name = "icon_warning.svg";
372
+ break;
373
+ case MSG_ERROR:
374
+ res_name = "icon_error.svg";
375
+ break;
376
+ case MSG_DISCARD:
377
+ default:
378
+ res_name = "";
379
+ break;
380
+ }
381
+
382
+ int height = (total_height - 3ul * vpadding) / 2ul;
383
+ SDL_Rect iconRect{ hpadding, vpadding, widget_width / 4ul - 2ul * hpadding, height };
384
+ widget_cfg_t icon{ textcolor,
385
+ res_bgcolor,
386
+ { _renderer, iconRect,
387
+ SDL2ResourceManager::get(SDLResourceManager::typeImages(), res_name) } };
388
+ _list.emplace_back(std::move(icon));
389
+
390
+ iconRect.y += height;
391
+
392
+ widget_cfg_t logo{ textcolor,
393
+ backgroundcolor,
394
+ { _renderer, iconRect,
395
+ SDL2ResourceManager::get(SDLResourceManager::typeImages(),
396
+ "FreeRDP_Icon.svg") } };
397
+ _list.emplace_back(std::move(logo));
398
+
399
+ SDL_Rect rect = { widget_width / 4ul, vpadding, widget_width * 3ul / 4ul,
400
+ total_height - 3ul * vpadding - widget_height };
401
+ #else
402
+ SDL_Rect rect = { hpadding, vpadding, widget_width - 2ul * hpadding,
403
+ total_height - 2ul * vpadding };
404
+ #endif
405
+
406
+ widget_cfg_t w{ textcolor, backgroundcolor, { _renderer, rect, false } };
407
+ w.widget.set_wrap(true, widget_width);
408
+ _list.emplace_back(std::move(w));
409
+ rect.y += widget_height + vpadding;
410
+
411
+ const std::vector<int> buttonids = { 1 };
412
+ const std::vector<std::string> buttonlabels = { "cancel" };
413
+ _buttons.populate(_renderer, buttonlabels, buttonids, widget_width,
414
+ total_height - widget_height - vpadding,
415
+ static_cast<Sint32>(widget_width / 2), static_cast<Sint32>(widget_height));
416
+ _buttons.set_highlight(0);
417
+
418
+ SDL_ShowWindow(_window);
419
+ SDL_RaiseWindow(_window);
420
+
421
+ return true;
422
+ }
423
+
424
+ void SDLConnectionDialog::destroyWindow()
425
+ {
426
+ _buttons.clear();
427
+ _list.clear();
428
+ SDL_DestroyRenderer(_renderer);
429
+ SDL_DestroyWindow(_window);
430
+ _renderer = nullptr;
431
+ _window = nullptr;
432
+ }
433
+
434
+ bool SDLConnectionDialog::show(MsgType type, const char* fmt, va_list ap)
435
+ {
436
+ std::lock_guard lock(_mux);
437
+ _msg = print(fmt, ap);
438
+ return show(type);
439
+ }
440
+
441
+ bool SDLConnectionDialog::show(MsgType type)
442
+ {
443
+ _type = type;
444
+ return sdl_push_user_event(SDL_USEREVENT_RETRY_DIALOG);
445
+ }
446
+
447
+ std::string SDLConnectionDialog::print(const char* fmt, va_list ap)
448
+ {
449
+ int size = -1;
450
+ std::string res;
451
+
452
+ do
453
+ {
454
+ res.resize(128);
455
+ if (size > 0)
456
+ res.resize(WINPR_ASSERTING_INT_CAST(size_t, size));
457
+
458
+ va_list copy;
459
+ va_copy(copy, ap);
460
+ WINPR_PRAGMA_DIAG_PUSH
461
+ WINPR_PRAGMA_DIAG_IGNORED_FORMAT_NONLITERAL
462
+ size = vsnprintf(res.data(), res.size(), fmt, copy);
463
+ WINPR_PRAGMA_DIAG_POP
464
+ va_end(copy);
465
+
466
+ } while ((size > 0) && (static_cast<size_t>(size) > res.size()));
467
+
468
+ return res;
469
+ }
470
+
471
+ bool SDLConnectionDialog::setTimer(Uint32 timeoutMS)
472
+ {
473
+ std::lock_guard lock(_mux);
474
+ resetTimer();
475
+
476
+ _timer = SDL_AddTimer(timeoutMS, &SDLConnectionDialog::timeout, this);
477
+ _running = true;
478
+ return true;
479
+ }
480
+
481
+ void SDLConnectionDialog::resetTimer()
482
+ {
483
+ if (_running)
484
+ SDL_RemoveTimer(_timer);
485
+ _running = false;
486
+ }
487
+
488
+ Uint32 SDLConnectionDialog::timeout(Uint32 intervalMS, void* pvthis)
489
+ {
490
+ auto self = static_cast<SDLConnectionDialog*>(pvthis);
491
+ self->hide();
492
+ self->_running = false;
493
+ return 0;
494
+ }
495
+
496
+ SDLConnectionDialogHider::SDLConnectionDialogHider(freerdp* instance)
497
+ : SDLConnectionDialogHider(get(instance))
498
+ {
499
+ }
500
+
501
+ SDLConnectionDialogHider::SDLConnectionDialogHider(rdpContext* context)
502
+ : SDLConnectionDialogHider(get(context))
503
+ {
504
+ }
505
+
506
+ SDLConnectionDialogHider::SDLConnectionDialogHider(SDLConnectionDialog* dialog) : _dialog(dialog)
507
+ {
508
+ if (_dialog)
509
+ {
510
+ _visible = _dialog->visible();
511
+ if (_visible)
512
+ {
513
+ _dialog->hide();
514
+ }
515
+ }
516
+ }
517
+
518
+ SDLConnectionDialogHider::~SDLConnectionDialogHider()
519
+ {
520
+ if (_dialog && _visible)
521
+ {
522
+ _dialog->show();
523
+ }
524
+ }
525
+
526
+ SDLConnectionDialog* SDLConnectionDialogHider::get(freerdp* instance)
527
+ {
528
+ if (!instance)
529
+ return nullptr;
530
+ return get(instance->context);
531
+ }
532
+
533
+ SDLConnectionDialog* SDLConnectionDialogHider::get(rdpContext* context)
534
+ {
535
+ auto sdl = get_context(context);
536
+ if (!sdl)
537
+ return nullptr;
538
+ return sdl->connection_dialog.get();
539
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_connection_dialog.hpp ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <memory>
23
+ #include <mutex>
24
+ #include <string>
25
+ #include <vector>
26
+
27
+ #include <SDL.h>
28
+
29
+ #include <freerdp/freerdp.h>
30
+
31
+ #include "sdl_widget.hpp"
32
+ #include "sdl_buttons.hpp"
33
+
34
+ class SDLConnectionDialog
35
+ {
36
+ public:
37
+ explicit SDLConnectionDialog(rdpContext* context);
38
+ SDLConnectionDialog(const SDLConnectionDialog& other) = delete;
39
+ SDLConnectionDialog(const SDLConnectionDialog&& other) = delete;
40
+ virtual ~SDLConnectionDialog();
41
+
42
+ SDLConnectionDialog& operator=(const SDLConnectionDialog& other) = delete;
43
+ SDLConnectionDialog& operator=(SDLConnectionDialog&& other) = delete;
44
+
45
+ bool visible() const;
46
+
47
+ bool setTitle(const char* fmt, ...);
48
+ bool showInfo(const char* fmt, ...);
49
+ bool showWarn(const char* fmt, ...);
50
+ bool showError(const char* fmt, ...);
51
+
52
+ bool show();
53
+ bool hide();
54
+
55
+ bool running() const;
56
+ bool wait(bool ignoreRdpContextQuit = false);
57
+
58
+ bool handle(const SDL_Event& event);
59
+
60
+ private:
61
+ enum MsgType
62
+ {
63
+ MSG_NONE,
64
+ MSG_INFO,
65
+ MSG_WARN,
66
+ MSG_ERROR,
67
+ MSG_DISCARD
68
+ };
69
+
70
+ bool createWindow();
71
+ void destroyWindow();
72
+
73
+ bool update();
74
+
75
+ bool setModal();
76
+
77
+ static bool clearWindow(SDL_Renderer* renderer);
78
+
79
+ bool update(SDL_Renderer* renderer);
80
+
81
+ bool show(MsgType type, const char* fmt, va_list ap);
82
+ bool show(MsgType type);
83
+
84
+ static std::string print(const char* fmt, va_list ap);
85
+ bool setTimer(Uint32 timeoutMS = 15000);
86
+ void resetTimer();
87
+
88
+ static Uint32 timeout(Uint32 intervalMS, void* pvthis);
89
+
90
+ struct widget_cfg_t
91
+ {
92
+ SDL_Color fgcolor = {};
93
+ SDL_Color bgcolor = {};
94
+ SdlWidget widget;
95
+ };
96
+
97
+ rdpContext* _context = nullptr;
98
+ SDL_Window* _window = nullptr;
99
+ SDL_Renderer* _renderer = nullptr;
100
+ mutable std::mutex _mux;
101
+ std::string _title;
102
+ std::string _msg;
103
+ MsgType _type = MSG_NONE;
104
+ MsgType _type_active = MSG_NONE;
105
+ SDL_TimerID _timer = -1;
106
+ bool _running = false;
107
+ std::vector<widget_cfg_t> _list;
108
+ SdlButtonList _buttons;
109
+ };
110
+
111
+ class SDLConnectionDialogHider
112
+ {
113
+ public:
114
+ explicit SDLConnectionDialogHider(freerdp* instance);
115
+ explicit SDLConnectionDialogHider(rdpContext* context);
116
+
117
+ explicit SDLConnectionDialogHider(SDLConnectionDialog* dialog);
118
+ SDLConnectionDialogHider(const SDLConnectionDialogHider& other) = delete;
119
+ SDLConnectionDialogHider(SDLConnectionDialogHider&& other) = delete;
120
+ SDLConnectionDialogHider& operator=(const SDLConnectionDialogHider& other) = delete;
121
+ SDLConnectionDialogHider& operator=(SDLConnectionDialogHider& other) = delete;
122
+
123
+ ~SDLConnectionDialogHider();
124
+
125
+ private:
126
+ SDLConnectionDialog* get(freerdp* instance);
127
+ static SDLConnectionDialog* get(rdpContext* context);
128
+
129
+ SDLConnectionDialog* _dialog = nullptr;
130
+ bool _visible = false;
131
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_dialogs.cpp ADDED
@@ -0,0 +1,623 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include <vector>
21
+ #include <string>
22
+ #include <cassert>
23
+
24
+ #include <freerdp/log.h>
25
+ #include <freerdp/utils/smartcardlogon.h>
26
+
27
+ #include <SDL.h>
28
+
29
+ #include "../sdl_freerdp.hpp"
30
+ #include "sdl_dialogs.hpp"
31
+ #include "sdl_input.hpp"
32
+ #include "sdl_input_widgets.hpp"
33
+ #include "sdl_select.hpp"
34
+ #include "sdl_selectlist.hpp"
35
+
36
+ enum
37
+ {
38
+ SHOW_DIALOG_ACCEPT_REJECT = 1,
39
+ SHOW_DIALOG_TIMED_ACCEPT = 2
40
+ };
41
+
42
+ static const char* type_str_for_flags(UINT32 flags)
43
+ {
44
+ const char* type = "RDP-Server";
45
+
46
+ if (flags & VERIFY_CERT_FLAG_GATEWAY)
47
+ type = "RDP-Gateway";
48
+
49
+ if (flags & VERIFY_CERT_FLAG_REDIRECT)
50
+ type = "RDP-Redirect";
51
+ return type;
52
+ }
53
+
54
+ static BOOL sdl_wait_for_result(rdpContext* context, Uint32 type, SDL_Event* result)
55
+ {
56
+ const SDL_Event empty = {};
57
+
58
+ WINPR_ASSERT(context);
59
+ WINPR_ASSERT(result);
60
+
61
+ while (!freerdp_shall_disconnect_context(context))
62
+ {
63
+ *result = empty;
64
+ const int rc = SDL_PeepEvents(result, 1, SDL_GETEVENT, type, type);
65
+ if (rc > 0)
66
+ return TRUE;
67
+ Sleep(1);
68
+ }
69
+ return FALSE;
70
+ }
71
+
72
+ static int sdl_show_dialog(rdpContext* context, const char* title, const char* message,
73
+ Sint32 flags)
74
+ {
75
+ SDL_Event event = {};
76
+
77
+ if (!sdl_push_user_event(SDL_USEREVENT_SHOW_DIALOG, title, message, flags))
78
+ return 0;
79
+
80
+ if (!sdl_wait_for_result(context, SDL_USEREVENT_SHOW_RESULT, &event))
81
+ return 0;
82
+
83
+ return event.user.code;
84
+ }
85
+
86
+ BOOL sdl_authenticate_ex(freerdp* instance, char** username, char** password, char** domain,
87
+ rdp_auth_reason reason)
88
+ {
89
+ SDL_Event event = {};
90
+ BOOL res = FALSE;
91
+
92
+ SDLConnectionDialogHider hider(instance);
93
+
94
+ const char* target = freerdp_settings_get_server_name(instance->context->settings);
95
+ switch (reason)
96
+ {
97
+ case AUTH_NLA:
98
+ break;
99
+
100
+ case AUTH_TLS:
101
+ case AUTH_RDP:
102
+ case AUTH_SMARTCARD_PIN: /* in this case password is pin code */
103
+ if ((*username) && (*password))
104
+ return TRUE;
105
+ break;
106
+ case GW_AUTH_HTTP:
107
+ case GW_AUTH_RDG:
108
+ case GW_AUTH_RPC:
109
+ target =
110
+ freerdp_settings_get_string(instance->context->settings, FreeRDP_GatewayHostname);
111
+ break;
112
+ default:
113
+ break;
114
+ }
115
+
116
+ char* title = nullptr;
117
+ size_t titlesize = 0;
118
+ winpr_asprintf(&title, &titlesize, "Credentials required for %s", target);
119
+
120
+ std::unique_ptr<char, decltype(&free)> scope(title, free);
121
+ char* u = nullptr;
122
+ char* d = nullptr;
123
+ char* p = nullptr;
124
+
125
+ assert(username);
126
+ assert(domain);
127
+ assert(password);
128
+
129
+ u = *username;
130
+ d = *domain;
131
+ p = *password;
132
+
133
+ if (!sdl_push_user_event(SDL_USEREVENT_AUTH_DIALOG, title, u, d, p, reason))
134
+ return res;
135
+
136
+ if (!sdl_wait_for_result(instance->context, SDL_USEREVENT_AUTH_RESULT, &event))
137
+ return res;
138
+
139
+ auto arg = reinterpret_cast<SDL_UserAuthArg*>(event.padding);
140
+
141
+ res = arg->result > 0;
142
+
143
+ free(*username);
144
+ free(*domain);
145
+ free(*password);
146
+ *username = arg->user;
147
+ *domain = arg->domain;
148
+ *password = arg->password;
149
+
150
+ return res;
151
+ }
152
+
153
+ BOOL sdl_choose_smartcard(freerdp* instance, SmartcardCertInfo** cert_list, DWORD count,
154
+ DWORD* choice, BOOL gateway)
155
+ {
156
+ BOOL res = FALSE;
157
+
158
+ WINPR_ASSERT(instance);
159
+ WINPR_ASSERT(cert_list);
160
+ WINPR_ASSERT(choice);
161
+
162
+ SDLConnectionDialogHider hider(instance);
163
+ std::vector<std::string> strlist;
164
+ std::vector<const char*> list;
165
+ for (DWORD i = 0; i < count; i++)
166
+ {
167
+ const SmartcardCertInfo* cert = cert_list[i];
168
+ char* reader = ConvertWCharToUtf8Alloc(cert->reader, nullptr);
169
+ char* container_name = ConvertWCharToUtf8Alloc(cert->containerName, nullptr);
170
+
171
+ char* msg = nullptr;
172
+ size_t len = 0;
173
+
174
+ winpr_asprintf(&msg, &len,
175
+ "%s\n\tReader: %s\n\tUser: %s@%s\n\tSubject: %s\n\tIssuer: %s\n\tUPN: %s",
176
+ container_name, reader, cert->userHint, cert->domainHint, cert->subject,
177
+ cert->issuer, cert->upn);
178
+
179
+ strlist.emplace_back(msg);
180
+ free(msg);
181
+ free(reader);
182
+ free(container_name);
183
+
184
+ auto& m = strlist.back();
185
+ list.push_back(m.c_str());
186
+ }
187
+
188
+ SDL_Event event = {};
189
+ const char* title = "Select a logon smartcard certificate";
190
+ if (gateway)
191
+ title = "Select a gateway logon smartcard certificate";
192
+ if (!sdl_push_user_event(SDL_USEREVENT_SCARD_DIALOG, title, list.data(), count))
193
+ return res;
194
+
195
+ if (!sdl_wait_for_result(instance->context, SDL_USEREVENT_SCARD_RESULT, &event))
196
+ return res;
197
+
198
+ res = (event.user.code >= 0);
199
+ *choice = static_cast<DWORD>(event.user.code);
200
+
201
+ return res;
202
+ }
203
+
204
+ SSIZE_T sdl_retry_dialog(freerdp* instance, const char* what, size_t current, void* userarg)
205
+ {
206
+ WINPR_ASSERT(instance);
207
+ WINPR_ASSERT(instance->context);
208
+ WINPR_ASSERT(what);
209
+
210
+ auto sdl = get_context(instance->context);
211
+ auto settings = instance->context->settings;
212
+ const size_t delay = freerdp_settings_get_uint32(settings, FreeRDP_TcpConnectTimeout);
213
+ std::lock_guard<CriticalSection> lock(sdl->critical);
214
+ if (!sdl->connection_dialog)
215
+ return WINPR_ASSERTING_INT_CAST(SSIZE_T, delay);
216
+
217
+ sdl->connection_dialog->setTitle("Retry connection to %s",
218
+ freerdp_settings_get_server_name(instance->context->settings));
219
+
220
+ if ((strcmp(what, "arm-transport") != 0) && (strcmp(what, "connection") != 0))
221
+ {
222
+ sdl->connection_dialog->showError("Unknown module %s, aborting", what);
223
+ return -1;
224
+ }
225
+
226
+ if (current == 0)
227
+ {
228
+ if (strcmp(what, "arm-transport") == 0)
229
+ sdl->connection_dialog->showWarn("[%s] Starting your VM. It may take up to 5 minutes",
230
+ what);
231
+ }
232
+
233
+ const BOOL enabled = freerdp_settings_get_bool(settings, FreeRDP_AutoReconnectionEnabled);
234
+
235
+ if (!enabled)
236
+ {
237
+ sdl->connection_dialog->showError(
238
+ "Automatic reconnection disabled, terminating. Try to connect again later");
239
+ return -1;
240
+ }
241
+
242
+ const size_t max = freerdp_settings_get_uint32(settings, FreeRDP_AutoReconnectMaxRetries);
243
+
244
+ if (current >= max)
245
+ {
246
+ sdl->connection_dialog->showError(
247
+ "[%s] retries exceeded. Your VM failed to start. Try again later or contact your "
248
+ "tech support for help if this keeps happening.",
249
+ what);
250
+ return -1;
251
+ }
252
+
253
+ sdl->connection_dialog->showInfo("[%s] retry %" PRIuz "/%" PRIuz ", delaying %" PRIuz
254
+ "ms before next attempt",
255
+ what, current, max, delay);
256
+ return WINPR_ASSERTING_INT_CAST(SSIZE_T, delay);
257
+ }
258
+
259
+ BOOL sdl_present_gateway_message(freerdp* instance, UINT32 type, BOOL isDisplayMandatory,
260
+ BOOL isConsentMandatory, size_t length, const WCHAR* wmessage)
261
+ {
262
+ if (!isDisplayMandatory)
263
+ return TRUE;
264
+
265
+ char* title = nullptr;
266
+ size_t len = 0;
267
+ winpr_asprintf(&title, &len, "[gateway]");
268
+
269
+ Sint32 flags = 0;
270
+ if (isConsentMandatory)
271
+ flags = SHOW_DIALOG_ACCEPT_REJECT;
272
+ else if (isDisplayMandatory)
273
+ flags = SHOW_DIALOG_TIMED_ACCEPT;
274
+ char* message = ConvertWCharNToUtf8Alloc(wmessage, length, nullptr);
275
+
276
+ SDLConnectionDialogHider hider(instance);
277
+ const int rc = sdl_show_dialog(instance->context, title, message, flags);
278
+ free(title);
279
+ free(message);
280
+ return rc > 0;
281
+ }
282
+
283
+ int sdl_logon_error_info(freerdp* instance, UINT32 data, UINT32 type)
284
+ {
285
+ int rc = -1;
286
+ const char* str_data = freerdp_get_logon_error_info_data(data);
287
+ const char* str_type = freerdp_get_logon_error_info_type(type);
288
+
289
+ if (!instance || !instance->context)
290
+ return -1;
291
+
292
+ /* ignore LOGON_MSG_SESSION_CONTINUE message */
293
+ if (type == LOGON_MSG_SESSION_CONTINUE)
294
+ return 0;
295
+
296
+ SDLConnectionDialogHider hider(instance);
297
+
298
+ char* title = nullptr;
299
+ size_t tlen = 0;
300
+ winpr_asprintf(&title, &tlen, "[%s] info",
301
+ freerdp_settings_get_server_name(instance->context->settings));
302
+
303
+ char* message = nullptr;
304
+ size_t mlen = 0;
305
+ winpr_asprintf(&message, &mlen, "Logon Error Info %s [%s]", str_data, str_type);
306
+
307
+ rc = sdl_show_dialog(instance->context, title, message, SHOW_DIALOG_ACCEPT_REJECT);
308
+ free(title);
309
+ free(message);
310
+ return rc;
311
+ }
312
+
313
+ static DWORD sdl_show_ceritifcate_dialog(rdpContext* context, const char* title,
314
+ const char* message)
315
+ {
316
+ SDLConnectionDialogHider hider(context);
317
+ if (!sdl_push_user_event(SDL_USEREVENT_CERT_DIALOG, title, message))
318
+ return 0;
319
+
320
+ SDL_Event event = {};
321
+ if (!sdl_wait_for_result(context, SDL_USEREVENT_CERT_RESULT, &event))
322
+ return 0;
323
+ return static_cast<DWORD>(event.user.code);
324
+ }
325
+
326
+ static char* sdl_pem_cert(const char* pem)
327
+ {
328
+ rdpCertificate* cert = freerdp_certificate_new_from_pem(pem);
329
+ if (!cert)
330
+ return nullptr;
331
+
332
+ char* fp = freerdp_certificate_get_fingerprint(cert);
333
+ char* start = freerdp_certificate_get_validity(cert, TRUE);
334
+ char* end = freerdp_certificate_get_validity(cert, FALSE);
335
+ freerdp_certificate_free(cert);
336
+
337
+ char* str = nullptr;
338
+ size_t slen = 0;
339
+ winpr_asprintf(&str, &slen,
340
+ "Valid from: %s\n"
341
+ "Valid to: %s\n"
342
+ "Thumbprint: %s\n",
343
+ start, end, fp);
344
+ free(fp);
345
+ free(start);
346
+ free(end);
347
+ return str;
348
+ }
349
+
350
+ DWORD sdl_verify_changed_certificate_ex(freerdp* instance, const char* host, UINT16 port,
351
+ const char* common_name, const char* subject,
352
+ const char* issuer, const char* new_fingerprint,
353
+ const char* old_subject, const char* old_issuer,
354
+ const char* old_fingerprint, DWORD flags)
355
+ {
356
+ const char* type = type_str_for_flags(flags);
357
+
358
+ WINPR_ASSERT(instance);
359
+ WINPR_ASSERT(instance->context);
360
+ WINPR_ASSERT(instance->context->settings);
361
+
362
+ SDLConnectionDialogHider hider(instance);
363
+ /* Newer versions of FreeRDP allow exposing the whole PEM by setting
364
+ * FreeRDP_CertificateCallbackPreferPEM to TRUE
365
+ */
366
+ char* new_fp_str = nullptr;
367
+ size_t len = 0;
368
+ if (flags & VERIFY_CERT_FLAG_FP_IS_PEM)
369
+ new_fp_str = sdl_pem_cert(new_fingerprint);
370
+ else
371
+ winpr_asprintf(&new_fp_str, &len, "Thumbprint: %s\n", new_fingerprint);
372
+
373
+ /* Newer versions of FreeRDP allow exposing the whole PEM by setting
374
+ * FreeRDP_CertificateCallbackPreferPEM to TRUE
375
+ */
376
+ char* old_fp_str = nullptr;
377
+ size_t olen = 0;
378
+ if (flags & VERIFY_CERT_FLAG_FP_IS_PEM)
379
+ old_fp_str = sdl_pem_cert(old_fingerprint);
380
+ else
381
+ winpr_asprintf(&old_fp_str, &olen, "Thumbprint: %s\n", old_fingerprint);
382
+
383
+ const char* collission_str = "";
384
+ if (flags & VERIFY_CERT_FLAG_MATCH_LEGACY_SHA1)
385
+ {
386
+ collission_str =
387
+ "A matching entry with legacy SHA1 was found in local known_hosts2 store.\n"
388
+ "If you just upgraded from a FreeRDP version before 2.0 this is expected.\n"
389
+ "The hashing algorithm has been upgraded from SHA1 to SHA256.\n"
390
+ "All manually accepted certificates must be reconfirmed!\n"
391
+ "\n";
392
+ }
393
+
394
+ char* title = nullptr;
395
+ size_t tlen = 0;
396
+ winpr_asprintf(&title, &tlen, "Certificate for %s:%" PRIu16 " (%s) has changed", host, port,
397
+ type);
398
+
399
+ char* message = nullptr;
400
+ size_t mlen = 0;
401
+ winpr_asprintf(&message, &mlen,
402
+ "New Certificate details:\n"
403
+ "Common Name: %s\n"
404
+ "Subject: %s\n"
405
+ "Issuer: %s\n"
406
+ "%s\n"
407
+ "Old Certificate details:\n"
408
+ "Subject: %s\n"
409
+ "Issuer: %s\n"
410
+ "%s\n"
411
+ "%s\n"
412
+ "The above X.509 certificate does not match the certificate used for previous "
413
+ "connections.\n"
414
+ "This may indicate that the certificate has been tampered with.\n"
415
+ "Please contact the administrator of the RDP server and clarify.\n",
416
+ common_name, subject, issuer, new_fp_str, old_subject, old_issuer, old_fp_str,
417
+ collission_str);
418
+
419
+ const DWORD rc = sdl_show_ceritifcate_dialog(instance->context, title, message);
420
+ free(title);
421
+ free(message);
422
+ free(new_fp_str);
423
+ free(old_fp_str);
424
+
425
+ return rc;
426
+ }
427
+
428
+ DWORD sdl_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port,
429
+ const char* common_name, const char* subject, const char* issuer,
430
+ const char* fingerprint, DWORD flags)
431
+ {
432
+ const char* type = type_str_for_flags(flags);
433
+
434
+ /* Newer versions of FreeRDP allow exposing the whole PEM by setting
435
+ * FreeRDP_CertificateCallbackPreferPEM to TRUE
436
+ */
437
+ char* fp_str = nullptr;
438
+ size_t len = 0;
439
+ if (flags & VERIFY_CERT_FLAG_FP_IS_PEM)
440
+ fp_str = sdl_pem_cert(fingerprint);
441
+ else
442
+ winpr_asprintf(&fp_str, &len, "Thumbprint: %s\n", fingerprint);
443
+
444
+ char* title = nullptr;
445
+ size_t tlen = 0;
446
+ winpr_asprintf(&title, &tlen, "New certificate for %s:%" PRIu16 " (%s)", host, port, type);
447
+
448
+ char* message = nullptr;
449
+ size_t mlen = 0;
450
+ winpr_asprintf(
451
+ &message, &mlen,
452
+ "Common Name: %s\n"
453
+ "Subject: %s\n"
454
+ "Issuer: %s\n"
455
+ "%s\n"
456
+ "The above X.509 certificate could not be verified, possibly because you do not have\n"
457
+ "the CA certificate in your certificate store, or the certificate has expired.\n"
458
+ "Please look at the OpenSSL documentation on how to add a private CA to the store.\n",
459
+ common_name, subject, issuer, fp_str);
460
+
461
+ SDLConnectionDialogHider hider(instance);
462
+ const DWORD rc = sdl_show_ceritifcate_dialog(instance->context, title, message);
463
+ free(fp_str);
464
+ free(title);
465
+ free(message);
466
+ return rc;
467
+ }
468
+
469
+ BOOL sdl_cert_dialog_show(const char* title, const char* message)
470
+ {
471
+ int buttonid = -1;
472
+ enum
473
+ {
474
+ BUTTONID_CERT_ACCEPT_PERMANENT = 23,
475
+ BUTTONID_CERT_ACCEPT_TEMPORARY = 24,
476
+ BUTTONID_CERT_DENY = 25
477
+ };
478
+ const SDL_MessageBoxButtonData buttons[] = {
479
+ { 0, BUTTONID_CERT_ACCEPT_PERMANENT, "permanent" },
480
+ { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, BUTTONID_CERT_ACCEPT_TEMPORARY, "temporary" },
481
+ { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, BUTTONID_CERT_DENY, "cancel" }
482
+ };
483
+
484
+ const SDL_MessageBoxData data = { SDL_MESSAGEBOX_WARNING, nullptr, title, message,
485
+ ARRAYSIZE(buttons), buttons, nullptr };
486
+ const int rc = SDL_ShowMessageBox(&data, &buttonid);
487
+
488
+ Sint32 value = -1;
489
+ if (rc < 0)
490
+ value = 0;
491
+ else
492
+ {
493
+ switch (buttonid)
494
+ {
495
+ case BUTTONID_CERT_ACCEPT_PERMANENT:
496
+ value = 1;
497
+ break;
498
+ case BUTTONID_CERT_ACCEPT_TEMPORARY:
499
+ value = 2;
500
+ break;
501
+ default:
502
+ value = 0;
503
+ break;
504
+ }
505
+ }
506
+
507
+ return sdl_push_user_event(SDL_USEREVENT_CERT_RESULT, value);
508
+ }
509
+
510
+ BOOL sdl_message_dialog_show(const char* title, const char* message, Sint32 flags)
511
+ {
512
+ int buttonid = -1;
513
+ enum
514
+ {
515
+ BUTTONID_SHOW_ACCEPT = 24,
516
+ BUTTONID_SHOW_DENY = 25
517
+ };
518
+ const SDL_MessageBoxButtonData buttons[] = {
519
+ { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, BUTTONID_SHOW_ACCEPT, "accept" },
520
+ { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, BUTTONID_SHOW_DENY, "cancel" }
521
+ };
522
+
523
+ const int button_cnt = (flags & SHOW_DIALOG_ACCEPT_REJECT) ? 2 : 1;
524
+ const SDL_MessageBoxData data = {
525
+ SDL_MESSAGEBOX_WARNING, nullptr, title, message, button_cnt, buttons, nullptr
526
+ };
527
+ const int rc = SDL_ShowMessageBox(&data, &buttonid);
528
+
529
+ Sint32 value = -1;
530
+ if (rc < 0)
531
+ value = 0;
532
+ else
533
+ {
534
+ switch (buttonid)
535
+ {
536
+ case BUTTONID_SHOW_ACCEPT:
537
+ value = 1;
538
+ break;
539
+ default:
540
+ value = 0;
541
+ break;
542
+ }
543
+ }
544
+
545
+ return sdl_push_user_event(SDL_USEREVENT_SHOW_RESULT, value);
546
+ }
547
+
548
+ BOOL sdl_auth_dialog_show(const SDL_UserAuthArg* args)
549
+ {
550
+ std::vector<std::string> auth = { "Username: ", "Domain: ",
551
+ "Password: " };
552
+ std::vector<std::string> authPin = { "Device: ", "PIN: " };
553
+ std::vector<std::string> gw = { "GatewayUsername: ", "GatewayDomain: ", "GatewayPassword: " };
554
+ std::vector<std::string> prompt;
555
+ Sint32 rc = -1;
556
+
557
+ switch (args->result)
558
+ {
559
+ case AUTH_SMARTCARD_PIN:
560
+ prompt = std::move(authPin);
561
+ break;
562
+ case AUTH_TLS:
563
+ case AUTH_RDP:
564
+ case AUTH_NLA:
565
+ prompt = std::move(auth);
566
+ break;
567
+ case GW_AUTH_HTTP:
568
+ case GW_AUTH_RDG:
569
+ case GW_AUTH_RPC:
570
+ prompt = std::move(gw);
571
+ break;
572
+ default:
573
+ break;
574
+ }
575
+
576
+ std::vector<std::string> result;
577
+
578
+ if (!prompt.empty())
579
+ {
580
+ std::vector<std::string> initial{ args->user ? args->user : "Smartcard", "" };
581
+ std::vector<Uint32> flags = { SdlInputWidget::SDL_INPUT_READONLY,
582
+ SdlInputWidget::SDL_INPUT_MASK };
583
+ if (args->result != AUTH_SMARTCARD_PIN)
584
+ {
585
+ initial = { args->user ? args->user : "", args->domain ? args->domain : "",
586
+ args->password ? args->password : "" };
587
+ flags = { 0, 0, SdlInputWidget::SDL_INPUT_MASK };
588
+ }
589
+ SdlInputWidgetList ilist(args->title, prompt, initial, flags);
590
+ rc = ilist.run(result);
591
+ }
592
+
593
+ if ((result.size() < prompt.size()))
594
+ rc = -1;
595
+
596
+ char* user = nullptr;
597
+ char* domain = nullptr;
598
+ char* pwd = nullptr;
599
+ if (rc > 0)
600
+ {
601
+ user = _strdup(result[0].c_str());
602
+ if (args->result == AUTH_SMARTCARD_PIN)
603
+ pwd = _strdup(result[1].c_str());
604
+ else
605
+ {
606
+ domain = _strdup(result[1].c_str());
607
+ pwd = _strdup(result[2].c_str());
608
+ }
609
+ }
610
+ return sdl_push_user_event(SDL_USEREVENT_AUTH_RESULT, user, domain, pwd, rc);
611
+ }
612
+
613
+ BOOL sdl_scard_dialog_show(const char* title, Sint32 count, const char** list)
614
+ {
615
+ const auto scount = WINPR_ASSERTING_INT_CAST(size_t, count);
616
+ std::vector<std::string> vlist;
617
+ vlist.reserve(scount);
618
+ for (size_t x = 0; x < scount; x++)
619
+ vlist.emplace_back(list[x]);
620
+ SdlSelectList slist(title, vlist);
621
+ Sint32 value = slist.run();
622
+ return sdl_push_user_event(SDL_USEREVENT_SCARD_RESULT, value);
623
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_dialogs.hpp ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <winpr/wtypes.h>
23
+ #include <freerdp/freerdp.h>
24
+
25
+ #include "../sdl_types.hpp"
26
+ #include "../sdl_utils.hpp"
27
+
28
+ BOOL sdl_authenticate_ex(freerdp* instance, char** username, char** password, char** domain,
29
+ rdp_auth_reason reason);
30
+ BOOL sdl_choose_smartcard(freerdp* instance, SmartcardCertInfo** cert_list, DWORD count,
31
+ DWORD* choice, BOOL gateway);
32
+
33
+ SSIZE_T sdl_retry_dialog(freerdp* instance, const char* what, size_t current, void* userarg);
34
+
35
+ DWORD sdl_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port,
36
+ const char* common_name, const char* subject, const char* issuer,
37
+ const char* fingerprint, DWORD flags);
38
+
39
+ DWORD sdl_verify_changed_certificate_ex(freerdp* instance, const char* host, UINT16 port,
40
+ const char* common_name, const char* subject,
41
+ const char* issuer, const char* new_fingerprint,
42
+ const char* old_subject, const char* old_issuer,
43
+ const char* old_fingerprint, DWORD flags);
44
+
45
+ int sdl_logon_error_info(freerdp* instance, UINT32 data, UINT32 type);
46
+
47
+ BOOL sdl_present_gateway_message(freerdp* instance, UINT32 type, BOOL isDisplayMandatory,
48
+ BOOL isConsentMandatory, size_t length, const WCHAR* message);
49
+
50
+ BOOL sdl_message_dialog_show(const char* title, const char* message, Sint32 flags);
51
+ BOOL sdl_cert_dialog_show(const char* title, const char* message);
52
+ BOOL sdl_scard_dialog_show(const char* title, Sint32 count, const char** list);
53
+ BOOL sdl_auth_dialog_show(const SDL_UserAuthArg* args);
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input.cpp ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include "sdl_input.hpp"
21
+
22
+ #include <cassert>
23
+
24
+ #include <string>
25
+ #include <utility>
26
+
27
+ #include <SDL.h>
28
+ #include <SDL_ttf.h>
29
+
30
+ #include "sdl_widget.hpp"
31
+ #include "sdl_button.hpp"
32
+ #include "sdl_buttons.hpp"
33
+
34
+ static const SDL_Color inputbackgroundcolor = { 0x56, 0x56, 0x56, 0xff };
35
+ static const SDL_Color inputhighlightcolor = { 0x80, 0, 0, 0x60 };
36
+ static const SDL_Color inputmouseovercolor = { 0, 0x80, 0, 0x60 };
37
+ static const SDL_Color inputfontcolor = { 0xd1, 0xcf, 0xcd, 0xff };
38
+ static const SDL_Color labelbackgroundcolor = { 0x56, 0x56, 0x56, 0xff };
39
+ static const SDL_Color labelfontcolor = { 0xd1, 0xcf, 0xcd, 0xff };
40
+ static const Uint32 vpadding = 5;
41
+ static const Uint32 hpadding = 10;
42
+
43
+ SdlInputWidget::SdlInputWidget(SDL_Renderer* renderer, std::string label, std::string initial,
44
+ Uint32 flags, size_t offset, size_t width, size_t height)
45
+ : _flags(flags), _text(std::move(initial)), _text_label(std::move(label)),
46
+ _label(renderer,
47
+ { 0, static_cast<int>(offset * (height + vpadding)), static_cast<int>(width),
48
+ static_cast<int>(height) },
49
+ false),
50
+ _input(renderer,
51
+ { static_cast<int>(width + hpadding), static_cast<int>(offset * (height + vpadding)),
52
+ static_cast<int>(width), static_cast<int>(height) },
53
+ true),
54
+ _highlight(false), _mouseover(false)
55
+ {
56
+ }
57
+
58
+ SdlInputWidget::SdlInputWidget(SdlInputWidget&& other) noexcept
59
+ : _flags(other._flags), _text(std::move(other._text)),
60
+ _text_label(std::move(other._text_label)), _label(std::move(other._label)),
61
+ _input(std::move(other._input)), _highlight(other._highlight), _mouseover(other._mouseover)
62
+ {
63
+ }
64
+
65
+ bool SdlInputWidget::fill_label(SDL_Renderer* renderer, SDL_Color color)
66
+ {
67
+ if (!_label.fill(renderer, color))
68
+ return false;
69
+ return _label.update_text(renderer, _text_label, labelfontcolor);
70
+ }
71
+
72
+ bool SdlInputWidget::update_label(SDL_Renderer* renderer)
73
+ {
74
+ return _label.update_text(renderer, _text_label, labelfontcolor, labelbackgroundcolor);
75
+ }
76
+
77
+ bool SdlInputWidget::set_mouseover(SDL_Renderer* renderer, bool mouseOver)
78
+ {
79
+ if (readonly())
80
+ return true;
81
+ _mouseover = mouseOver;
82
+ return update_input(renderer);
83
+ }
84
+
85
+ bool SdlInputWidget::set_highlight(SDL_Renderer* renderer, bool highlight)
86
+ {
87
+ if (readonly())
88
+ return true;
89
+ _highlight = highlight;
90
+ return update_input(renderer);
91
+ }
92
+
93
+ bool SdlInputWidget::update_input(SDL_Renderer* renderer)
94
+ {
95
+ std::vector<SDL_Color> colors = { inputbackgroundcolor };
96
+ if (_highlight)
97
+ colors.push_back(inputhighlightcolor);
98
+ if (_mouseover)
99
+ colors.push_back(inputmouseovercolor);
100
+
101
+ if (!_input.fill(renderer, colors))
102
+ return false;
103
+ return update_input(renderer, inputfontcolor);
104
+ }
105
+
106
+ bool SdlInputWidget::resize_input(size_t size)
107
+ {
108
+ _text.resize(size);
109
+
110
+ return true;
111
+ }
112
+
113
+ bool SdlInputWidget::set_str(SDL_Renderer* renderer, const std::string& text)
114
+ {
115
+ if (readonly())
116
+ return true;
117
+ _text = text;
118
+ if (!resize_input(_text.size()))
119
+ return false;
120
+ return update_input(renderer);
121
+ }
122
+
123
+ bool SdlInputWidget::remove_str(SDL_Renderer* renderer, size_t count)
124
+ {
125
+ if (readonly())
126
+ return true;
127
+
128
+ assert(renderer);
129
+ if (_text.empty())
130
+ return true;
131
+
132
+ if (!resize_input(_text.size() - count))
133
+ return false;
134
+ return update_input(renderer);
135
+ }
136
+
137
+ bool SdlInputWidget::append_str(SDL_Renderer* renderer, const std::string& text)
138
+ {
139
+ assert(renderer);
140
+ if (readonly())
141
+ return true;
142
+
143
+ _text.append(text);
144
+ if (!resize_input(_text.size()))
145
+ return false;
146
+ return update_input(renderer);
147
+ }
148
+
149
+ const SDL_Rect& SdlInputWidget::input_rect() const
150
+ {
151
+ return _input.rect();
152
+ }
153
+
154
+ std::string SdlInputWidget::value() const
155
+ {
156
+ return _text;
157
+ }
158
+
159
+ bool SdlInputWidget::readonly() const
160
+ {
161
+ return (_flags & SDL_INPUT_READONLY) != 0;
162
+ }
163
+
164
+ bool SdlInputWidget::update_input(SDL_Renderer* renderer, SDL_Color fgcolor)
165
+ {
166
+ std::string text = _text;
167
+ if (!text.empty())
168
+ {
169
+ if (_flags & SDL_INPUT_MASK)
170
+ {
171
+ for (char& x : text)
172
+ x = '*';
173
+ }
174
+ }
175
+
176
+ return _input.update_text(renderer, text, fgcolor);
177
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input.hpp ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <vector>
23
+ #include <string>
24
+
25
+ #include <SDL.h>
26
+ #include "sdl_widget.hpp"
27
+
28
+ class SdlInputWidget
29
+ {
30
+ public:
31
+ enum
32
+ {
33
+ SDL_INPUT_MASK = 1,
34
+ SDL_INPUT_READONLY = 2
35
+ };
36
+
37
+ SdlInputWidget(SDL_Renderer* renderer, std::string label, std::string initial, Uint32 flags,
38
+ size_t offset, size_t width, size_t height);
39
+ SdlInputWidget(SdlInputWidget&& other) noexcept;
40
+ SdlInputWidget(const SdlInputWidget& other) = delete;
41
+
42
+ SdlInputWidget& operator=(const SdlInputWidget& other) = delete;
43
+ SdlInputWidget& operator=(SdlInputWidget&& other) = delete;
44
+
45
+ bool fill_label(SDL_Renderer* renderer, SDL_Color color);
46
+ bool update_label(SDL_Renderer* renderer);
47
+
48
+ bool set_mouseover(SDL_Renderer* renderer, bool mouseOver);
49
+ bool set_highlight(SDL_Renderer* renderer, bool highlight);
50
+ bool update_input(SDL_Renderer* renderer);
51
+ bool resize_input(size_t size);
52
+
53
+ bool set_str(SDL_Renderer* renderer, const std::string& text);
54
+ bool remove_str(SDL_Renderer* renderer, size_t count);
55
+ bool append_str(SDL_Renderer* renderer, const std::string& text);
56
+
57
+ [[nodiscard]] const SDL_Rect& input_rect() const;
58
+ [[nodiscard]] std::string value() const;
59
+
60
+ [[nodiscard]] bool readonly() const;
61
+
62
+ protected:
63
+ bool update_input(SDL_Renderer* renderer, SDL_Color fgcolor);
64
+
65
+ private:
66
+ Uint32 _flags;
67
+ std::string _text;
68
+ std::string _text_label;
69
+ SdlWidget _label;
70
+ SdlWidget _input;
71
+ bool _highlight;
72
+ bool _mouseover;
73
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input_widgets.cpp ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cassert>
2
+ #include <limits>
3
+ #include <algorithm>
4
+ #include <cinttypes>
5
+
6
+ #include "sdl_input_widgets.hpp"
7
+
8
+ static const Uint32 vpadding = 5;
9
+
10
+ SdlInputWidgetList::SdlInputWidgetList(const std::string& title,
11
+ const std::vector<std::string>& labels,
12
+ const std::vector<std::string>& initial,
13
+ const std::vector<Uint32>& flags)
14
+ : _window(nullptr), _renderer(nullptr)
15
+ {
16
+ assert(labels.size() == initial.size());
17
+ assert(labels.size() == flags.size());
18
+ const std::vector<int> buttonids = { INPUT_BUTTON_ACCEPT, INPUT_BUTTON_CANCEL };
19
+ const std::vector<std::string> buttonlabels = { "accept", "cancel" };
20
+
21
+ const size_t widget_width = 300;
22
+ const size_t widget_heigth = 50;
23
+
24
+ const size_t total_width = widget_width + widget_width;
25
+ const size_t input_height = labels.size() * (widget_heigth + vpadding) + vpadding;
26
+ const size_t total_height = input_height + widget_heigth;
27
+
28
+ assert(total_width <= INT32_MAX);
29
+ assert(total_height <= INT32_MAX);
30
+ Uint32 wflags = SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS;
31
+ auto rc =
32
+ SDL_CreateWindowAndRenderer(static_cast<int>(total_width), static_cast<int>(total_height),
33
+ wflags, &_window, &_renderer);
34
+ if (rc != 0)
35
+ widget_log_error(rc, "SDL_CreateWindowAndRenderer");
36
+ else
37
+ {
38
+ SDL_SetWindowTitle(_window, title.c_str());
39
+ for (size_t x = 0; x < labels.size(); x++)
40
+ _list.emplace_back(_renderer, labels[x], initial[x], flags[x], x, widget_width,
41
+ widget_heigth);
42
+
43
+ _buttons.populate(_renderer, buttonlabels, buttonids, total_width,
44
+ static_cast<Sint32>(input_height), static_cast<Sint32>(widget_width),
45
+ static_cast<Sint32>(widget_heigth));
46
+ _buttons.set_highlight(0);
47
+ }
48
+ }
49
+
50
+ ssize_t SdlInputWidgetList::next(ssize_t current)
51
+ {
52
+ size_t iteration = 0;
53
+ auto val = static_cast<size_t>(current);
54
+
55
+ do
56
+ {
57
+ if (iteration >= _list.size())
58
+ return -1;
59
+
60
+ if (iteration == 0)
61
+ {
62
+ if (current < 0)
63
+ val = 0;
64
+ else
65
+ val++;
66
+ }
67
+ else
68
+ val++;
69
+ iteration++;
70
+ val %= _list.size();
71
+ } while (!valid(static_cast<ssize_t>(val)));
72
+ return static_cast<ssize_t>(val);
73
+ }
74
+
75
+ bool SdlInputWidgetList::valid(ssize_t current) const
76
+ {
77
+ if (current < 0)
78
+ return false;
79
+ auto s = static_cast<size_t>(current);
80
+ if (s >= _list.size())
81
+ return false;
82
+ return !_list[s].readonly();
83
+ }
84
+
85
+ SdlInputWidget* SdlInputWidgetList::get(ssize_t index)
86
+ {
87
+ if (index < 0)
88
+ return nullptr;
89
+ auto s = static_cast<size_t>(index);
90
+ if (s >= _list.size())
91
+ return nullptr;
92
+ return &_list[s];
93
+ }
94
+
95
+ SdlInputWidgetList::~SdlInputWidgetList()
96
+ {
97
+ _list.clear();
98
+ _buttons.clear();
99
+ SDL_DestroyRenderer(_renderer);
100
+ SDL_DestroyWindow(_window);
101
+ }
102
+
103
+ bool SdlInputWidgetList::update(SDL_Renderer* renderer)
104
+ {
105
+ for (auto& btn : _list)
106
+ {
107
+ if (!btn.update_label(renderer))
108
+ return false;
109
+ if (!btn.update_input(renderer))
110
+ return false;
111
+ }
112
+
113
+ return _buttons.update(renderer);
114
+ }
115
+
116
+ ssize_t SdlInputWidgetList::get_index(const SDL_MouseButtonEvent& button)
117
+ {
118
+ const Sint32 x = button.x;
119
+ const Sint32 y = button.y;
120
+
121
+ assert(_list.size() <= std::numeric_limits<ssize_t>::max());
122
+ for (size_t i = 0; i < _list.size(); i++)
123
+ {
124
+ auto& cur = _list[i];
125
+ auto r = cur.input_rect();
126
+
127
+ if ((x >= r.x) && (x <= r.x + r.w) && (y >= r.y) && (y <= r.y + r.h))
128
+ return static_cast<ssize_t>(i);
129
+ }
130
+ return -1;
131
+ }
132
+
133
+ int SdlInputWidgetList::run(std::vector<std::string>& result)
134
+ {
135
+ int res = -1;
136
+ ssize_t LastActiveTextInput = -1;
137
+ ssize_t CurrentActiveTextInput = next(-1);
138
+
139
+ if (!_window || !_renderer)
140
+ return -2;
141
+
142
+ try
143
+ {
144
+ bool running = true;
145
+ std::vector<SDL_Keycode> pressed;
146
+ while (running)
147
+ {
148
+ if (!clear_window(_renderer))
149
+ throw;
150
+
151
+ if (!update(_renderer))
152
+ throw;
153
+
154
+ if (!_buttons.update(_renderer))
155
+ throw;
156
+
157
+ SDL_Event event = {};
158
+ SDL_WaitEvent(&event);
159
+ switch (event.type)
160
+ {
161
+ case SDL_KEYUP:
162
+ {
163
+ auto it = std::remove(pressed.begin(), pressed.end(), event.key.keysym.sym);
164
+ pressed.erase(it, pressed.end());
165
+
166
+ switch (event.key.keysym.sym)
167
+ {
168
+ case SDLK_BACKSPACE:
169
+ {
170
+ auto cur = get(CurrentActiveTextInput);
171
+ if (cur)
172
+ {
173
+ if (!cur->remove_str(_renderer, 1))
174
+ throw;
175
+ }
176
+ }
177
+ break;
178
+ case SDLK_TAB:
179
+ CurrentActiveTextInput = next(CurrentActiveTextInput);
180
+ break;
181
+ case SDLK_RETURN:
182
+ case SDLK_RETURN2:
183
+ case SDLK_KP_ENTER:
184
+ running = false;
185
+ res = INPUT_BUTTON_ACCEPT;
186
+ break;
187
+ case SDLK_ESCAPE:
188
+ running = false;
189
+ res = INPUT_BUTTON_CANCEL;
190
+ break;
191
+ case SDLK_v:
192
+ if (pressed.size() == 2)
193
+ {
194
+ if ((pressed[0] == SDLK_LCTRL) || (pressed[0] == SDLK_RCTRL))
195
+ {
196
+ auto cur = get(CurrentActiveTextInput);
197
+ if (cur)
198
+ {
199
+ auto text = SDL_GetClipboardText();
200
+ cur->set_str(_renderer, text);
201
+ }
202
+ }
203
+ }
204
+ break;
205
+ default:
206
+ break;
207
+ }
208
+ }
209
+ break;
210
+ case SDL_KEYDOWN:
211
+ pressed.push_back(event.key.keysym.sym);
212
+ break;
213
+ case SDL_TEXTINPUT:
214
+ {
215
+ auto cur = get(CurrentActiveTextInput);
216
+ if (cur)
217
+ {
218
+ if (!cur->append_str(_renderer, event.text.text))
219
+ throw;
220
+ }
221
+ }
222
+ break;
223
+ case SDL_MOUSEMOTION:
224
+ {
225
+ auto TextInputIndex = get_index(event.button);
226
+ for (auto& cur : _list)
227
+ {
228
+ if (!cur.set_mouseover(_renderer, false))
229
+ throw;
230
+ }
231
+ if (TextInputIndex >= 0)
232
+ {
233
+ auto& cur = _list[static_cast<size_t>(TextInputIndex)];
234
+ if (!cur.set_mouseover(_renderer, true))
235
+ throw;
236
+ }
237
+
238
+ _buttons.set_mouseover(event.button.x, event.button.y);
239
+ }
240
+ break;
241
+ case SDL_MOUSEBUTTONDOWN:
242
+ {
243
+ auto val = get_index(event.button);
244
+ if (valid(val))
245
+ CurrentActiveTextInput = val;
246
+
247
+ auto button = _buttons.get_selected(event.button);
248
+ if (button)
249
+ {
250
+ running = false;
251
+ if (button->id() == INPUT_BUTTON_CANCEL)
252
+ res = INPUT_BUTTON_CANCEL;
253
+ else
254
+ res = INPUT_BUTTON_ACCEPT;
255
+ }
256
+ }
257
+ break;
258
+ case SDL_QUIT:
259
+ res = INPUT_BUTTON_CANCEL;
260
+ running = false;
261
+ break;
262
+ default:
263
+ break;
264
+ }
265
+
266
+ if (LastActiveTextInput != CurrentActiveTextInput)
267
+ {
268
+ if (CurrentActiveTextInput < 0)
269
+ SDL_StopTextInput();
270
+ else
271
+ SDL_StartTextInput();
272
+ LastActiveTextInput = CurrentActiveTextInput;
273
+ }
274
+
275
+ for (auto& cur : _list)
276
+ {
277
+ if (!cur.set_highlight(_renderer, false))
278
+ throw;
279
+ }
280
+ auto cur = get(CurrentActiveTextInput);
281
+ if (cur)
282
+ {
283
+ if (!cur->set_highlight(_renderer, true))
284
+ throw;
285
+ }
286
+
287
+ SDL_RenderPresent(_renderer);
288
+ }
289
+
290
+ for (auto& cur : _list)
291
+ result.push_back(cur.value());
292
+ }
293
+ catch (...)
294
+ {
295
+ res = -2;
296
+ }
297
+
298
+ return res;
299
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_input_widgets.hpp ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+ #include <vector>
5
+ #include <SDL.h>
6
+
7
+ #include "sdl_input.hpp"
8
+ #include "sdl_buttons.hpp"
9
+
10
+ class SdlInputWidgetList
11
+ {
12
+ public:
13
+ SdlInputWidgetList(const std::string& title, const std::vector<std::string>& labels,
14
+ const std::vector<std::string>& initial, const std::vector<Uint32>& flags);
15
+ SdlInputWidgetList(const SdlInputWidgetList& other) = delete;
16
+ SdlInputWidgetList(SdlInputWidgetList&& other) = delete;
17
+
18
+ SdlInputWidgetList& operator=(const SdlInputWidgetList& other) = delete;
19
+ SdlInputWidgetList& operator=(SdlInputWidgetList&& other) = delete;
20
+
21
+ virtual ~SdlInputWidgetList();
22
+
23
+ int run(std::vector<std::string>& result);
24
+
25
+ protected:
26
+ bool update(SDL_Renderer* renderer);
27
+ ssize_t get_index(const SDL_MouseButtonEvent& button);
28
+
29
+ private:
30
+ enum
31
+ {
32
+ INPUT_BUTTON_ACCEPT = 1,
33
+ INPUT_BUTTON_CANCEL = -2
34
+ };
35
+
36
+ ssize_t next(ssize_t current);
37
+ [[nodiscard]] bool valid(ssize_t current) const;
38
+ SdlInputWidget* get(ssize_t index);
39
+
40
+ SDL_Window* _window;
41
+ SDL_Renderer* _renderer;
42
+ std::vector<SdlInputWidget> _list;
43
+ SdlButtonList _buttons;
44
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_select.cpp ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include <cassert>
21
+
22
+ #include <string>
23
+ #include <utility>
24
+
25
+ #include <SDL.h>
26
+ #include <SDL_ttf.h>
27
+
28
+ #include "sdl_select.hpp"
29
+ #include "sdl_widget.hpp"
30
+ #include "sdl_button.hpp"
31
+ #include "sdl_buttons.hpp"
32
+ #include "sdl_input_widgets.hpp"
33
+
34
+ static const SDL_Color labelmouseovercolor = { 0, 0x80, 0, 0x60 };
35
+ static const SDL_Color labelbackgroundcolor = { 0x69, 0x66, 0x63, 0xff };
36
+ static const SDL_Color labelhighlightcolor = { 0xcd, 0xca, 0x35, 0x60 };
37
+ static const SDL_Color labelfontcolor = { 0xd1, 0xcf, 0xcd, 0xff };
38
+
39
+ SdlSelectWidget::SdlSelectWidget(SDL_Renderer* renderer, std::string label, SDL_Rect rect)
40
+ : SdlWidget(renderer, rect, true), _text(std::move(label)), _mouseover(false), _highlight(false)
41
+ {
42
+ update_text(renderer);
43
+ }
44
+
45
+ SdlSelectWidget::SdlSelectWidget(SdlSelectWidget&& other) noexcept = default;
46
+
47
+ SdlSelectWidget::~SdlSelectWidget() = default;
48
+
49
+ bool SdlSelectWidget::set_mouseover(SDL_Renderer* renderer, bool mouseOver)
50
+ {
51
+ _mouseover = mouseOver;
52
+ return update_text(renderer);
53
+ }
54
+
55
+ bool SdlSelectWidget::set_highlight(SDL_Renderer* renderer, bool highlight)
56
+ {
57
+ _highlight = highlight;
58
+ return update_text(renderer);
59
+ }
60
+
61
+ bool SdlSelectWidget::update_text(SDL_Renderer* renderer)
62
+ {
63
+ assert(renderer);
64
+ std::vector<SDL_Color> colors = { labelbackgroundcolor };
65
+ if (_highlight)
66
+ colors.push_back(labelhighlightcolor);
67
+ if (_mouseover)
68
+ colors.push_back(labelmouseovercolor);
69
+ if (!fill(renderer, colors))
70
+ return false;
71
+ return SdlWidget::update_text(renderer, _text, labelfontcolor);
72
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_select.hpp ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include <SDL.h>
26
+ #include "sdl_widget.hpp"
27
+
28
+ class SdlSelectWidget : public SdlWidget
29
+ {
30
+ public:
31
+ SdlSelectWidget(SDL_Renderer* renderer, std::string label, SDL_Rect rect);
32
+ SdlSelectWidget(SdlSelectWidget&& other) noexcept;
33
+ ~SdlSelectWidget() override;
34
+
35
+ bool set_mouseover(SDL_Renderer* renderer, bool mouseOver);
36
+ bool set_highlight(SDL_Renderer* renderer, bool highlight);
37
+ bool update_text(SDL_Renderer* renderer);
38
+
39
+ SdlSelectWidget(const SdlSelectWidget& other) = delete;
40
+ SdlSelectWidget& operator=(const SdlSelectWidget& other) = delete;
41
+ SdlSelectWidget& operator=(SdlSelectWidget&& other) = delete;
42
+
43
+ private:
44
+ std::string _text;
45
+ bool _mouseover;
46
+ bool _highlight;
47
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_selectlist.cpp ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cassert>
2
+
3
+ #include <winpr/cast.h>
4
+
5
+ #include "sdl_selectlist.hpp"
6
+
7
+ static const Uint32 vpadding = 5;
8
+
9
+ SdlSelectList::SdlSelectList(const std::string& title, const std::vector<std::string>& labels)
10
+ : _window(nullptr), _renderer(nullptr)
11
+ {
12
+ const size_t widget_height = 50;
13
+ const size_t widget_width = 600;
14
+
15
+ const size_t total_height = labels.size() * (widget_height + vpadding) + vpadding;
16
+ const size_t height = total_height + widget_height;
17
+ assert(widget_width <= INT32_MAX);
18
+ assert(height <= INT32_MAX);
19
+
20
+ auto flags = WINPR_ASSERTING_INT_CAST(
21
+ uint32_t, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS);
22
+ auto rc = SDL_CreateWindowAndRenderer(static_cast<int>(widget_width), static_cast<int>(height),
23
+ flags, &_window, &_renderer);
24
+ if (rc != 0)
25
+ widget_log_error(rc, "SDL_CreateWindowAndRenderer");
26
+ else
27
+ {
28
+ SDL_SetWindowTitle(_window, title.c_str());
29
+
30
+ SDL_Rect rect = { 0, 0, widget_width, widget_height };
31
+ for (auto& label : labels)
32
+ {
33
+ _list.emplace_back(_renderer, label, rect);
34
+ rect.y += widget_height + vpadding;
35
+ }
36
+
37
+ const std::vector<int> buttonids = { INPUT_BUTTON_ACCEPT, INPUT_BUTTON_CANCEL };
38
+ const std::vector<std::string> buttonlabels = { "accept", "cancel" };
39
+ _buttons.populate(_renderer, buttonlabels, buttonids, widget_width,
40
+ static_cast<Sint32>(total_height), static_cast<Sint32>(widget_width / 2),
41
+ static_cast<Sint32>(widget_height));
42
+ _buttons.set_highlight(0);
43
+ }
44
+ }
45
+
46
+ SdlSelectList::~SdlSelectList()
47
+ {
48
+ _list.clear();
49
+ _buttons.clear();
50
+ SDL_DestroyRenderer(_renderer);
51
+ SDL_DestroyWindow(_window);
52
+ }
53
+
54
+ int SdlSelectList::run()
55
+ {
56
+ int res = -2;
57
+ ssize_t CurrentActiveTextInput = 0;
58
+ bool running = true;
59
+
60
+ if (!_window || !_renderer)
61
+ return -2;
62
+ try
63
+ {
64
+ while (running)
65
+ {
66
+ if (!clear_window(_renderer))
67
+ throw;
68
+
69
+ if (!update_text())
70
+ throw;
71
+
72
+ if (!_buttons.update(_renderer))
73
+ throw;
74
+
75
+ SDL_Event event = {};
76
+ SDL_WaitEvent(&event);
77
+ switch (event.type)
78
+ {
79
+ case SDL_KEYDOWN:
80
+ switch (event.key.keysym.sym)
81
+ {
82
+ case SDLK_UP:
83
+ case SDLK_BACKSPACE:
84
+ if (CurrentActiveTextInput > 0)
85
+ CurrentActiveTextInput--;
86
+ else
87
+ CurrentActiveTextInput =
88
+ WINPR_ASSERTING_INT_CAST(ssize_t, _list.size() - 1);
89
+ break;
90
+ case SDLK_DOWN:
91
+ case SDLK_TAB:
92
+ {
93
+ if (CurrentActiveTextInput < 0)
94
+ CurrentActiveTextInput = 0;
95
+ else
96
+ CurrentActiveTextInput++;
97
+
98
+ const auto s = _list.size();
99
+ if (s <= 0)
100
+ CurrentActiveTextInput = 0;
101
+ else
102
+ CurrentActiveTextInput =
103
+ CurrentActiveTextInput % WINPR_ASSERTING_INT_CAST(ssize_t, s);
104
+ }
105
+ break;
106
+ case SDLK_RETURN:
107
+ case SDLK_RETURN2:
108
+ case SDLK_KP_ENTER:
109
+ running = false;
110
+ res = WINPR_ASSERTING_INT_CAST(int, CurrentActiveTextInput);
111
+ break;
112
+ case SDLK_ESCAPE:
113
+ running = false;
114
+ res = INPUT_BUTTON_CANCEL;
115
+ break;
116
+ default:
117
+ break;
118
+ }
119
+ break;
120
+ case SDL_MOUSEMOTION:
121
+ {
122
+ ssize_t TextInputIndex = get_index(event.button);
123
+ reset_mouseover();
124
+ if (TextInputIndex >= 0)
125
+ {
126
+ auto& cur = _list[WINPR_ASSERTING_INT_CAST(size_t, TextInputIndex)];
127
+ if (!cur.set_mouseover(_renderer, true))
128
+ throw;
129
+ }
130
+
131
+ _buttons.set_mouseover(event.button.x, event.button.y);
132
+ }
133
+ break;
134
+ case SDL_MOUSEBUTTONDOWN:
135
+ {
136
+ auto button = _buttons.get_selected(event.button);
137
+ if (button)
138
+ {
139
+ running = false;
140
+ if (button->id() == INPUT_BUTTON_CANCEL)
141
+ res = INPUT_BUTTON_CANCEL;
142
+ else
143
+ res = static_cast<int>(CurrentActiveTextInput);
144
+ }
145
+ else
146
+ {
147
+ CurrentActiveTextInput = get_index(event.button);
148
+ }
149
+ }
150
+ break;
151
+ case SDL_QUIT:
152
+ res = INPUT_BUTTON_CANCEL;
153
+ running = false;
154
+ break;
155
+ default:
156
+ break;
157
+ }
158
+
159
+ reset_highlight();
160
+ if (CurrentActiveTextInput >= 0)
161
+ {
162
+ auto& cur = _list[WINPR_ASSERTING_INT_CAST(size_t, CurrentActiveTextInput)];
163
+ if (!cur.set_highlight(_renderer, true))
164
+ throw;
165
+ }
166
+
167
+ SDL_RenderPresent(_renderer);
168
+ }
169
+ }
170
+ catch (...)
171
+ {
172
+ return -1;
173
+ }
174
+ return res;
175
+ }
176
+
177
+ ssize_t SdlSelectList::get_index(const SDL_MouseButtonEvent& button)
178
+ {
179
+ const Sint32 x = button.x;
180
+ const Sint32 y = button.y;
181
+ for (size_t i = 0; i < _list.size(); i++)
182
+ {
183
+ auto& cur = _list[i];
184
+ auto r = cur.rect();
185
+
186
+ if ((x >= r.x) && (x <= r.x + r.w) && (y >= r.y) && (y <= r.y + r.h))
187
+ return WINPR_ASSERTING_INT_CAST(ssize_t, i);
188
+ }
189
+ return -1;
190
+ }
191
+
192
+ bool SdlSelectList::update_text()
193
+ {
194
+ for (auto& cur : _list)
195
+ {
196
+ if (!cur.update_text(_renderer))
197
+ return false;
198
+ }
199
+
200
+ return true;
201
+ }
202
+
203
+ void SdlSelectList::reset_mouseover()
204
+ {
205
+ for (auto& cur : _list)
206
+ {
207
+ cur.set_mouseover(_renderer, false);
208
+ }
209
+ }
210
+
211
+ void SdlSelectList::reset_highlight()
212
+ {
213
+ for (auto& cur : _list)
214
+ {
215
+ cur.set_highlight(_renderer, false);
216
+ }
217
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_selectlist.hpp ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <string>
4
+ #include <vector>
5
+
6
+ #include <SDL.h>
7
+
8
+ #include "sdl_select.hpp"
9
+ #include "sdl_button.hpp"
10
+ #include "sdl_buttons.hpp"
11
+
12
+ class SdlSelectList
13
+ {
14
+ public:
15
+ SdlSelectList(const std::string& title, const std::vector<std::string>& labels);
16
+ virtual ~SdlSelectList();
17
+
18
+ int run();
19
+
20
+ SdlSelectList(const SdlSelectList& other) = delete;
21
+ SdlSelectList(SdlSelectList&& other) = delete;
22
+ SdlSelectList& operator=(const SdlSelectList& other) = delete;
23
+ SdlSelectList& operator=(SdlSelectList&& other) = delete;
24
+
25
+ private:
26
+ enum
27
+ {
28
+ INPUT_BUTTON_ACCEPT = 0,
29
+ INPUT_BUTTON_CANCEL = -2
30
+ };
31
+
32
+ ssize_t get_index(const SDL_MouseButtonEvent& button);
33
+ bool update_text();
34
+ void reset_mouseover();
35
+ void reset_highlight();
36
+
37
+ SDL_Window* _window;
38
+ SDL_Renderer* _renderer;
39
+ std::vector<SdlSelectWidget> _list;
40
+ SdlButtonList _buttons;
41
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_widget.cpp ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include <cassert>
21
+ #include <cstdio>
22
+ #include <cstdlib>
23
+ #include <algorithm>
24
+
25
+ #include <SDL.h>
26
+ #include <SDL_ttf.h>
27
+
28
+ #include "sdl_widget.hpp"
29
+ #include "../sdl_utils.hpp"
30
+
31
+ #include "res/sdl2_resource_manager.hpp"
32
+
33
+ #include <freerdp/log.h>
34
+
35
+ #if defined(WITH_SDL_IMAGE_DIALOGS)
36
+ #include <SDL_image.h>
37
+ #endif
38
+
39
+ #define TAG CLIENT_TAG("SDL.widget")
40
+
41
+ static const SDL_Color backgroundcolor = { 0x38, 0x36, 0x35, 0xff };
42
+
43
+ static const Uint32 hpadding = 10;
44
+
45
+ SdlWidget::SdlWidget(SDL_Renderer* renderer, SDL_Rect rect, bool input) : _rect(rect), _input(input)
46
+ {
47
+ assert(renderer);
48
+
49
+ auto ops = SDL2ResourceManager::get(SDLResourceManager::typeFonts(),
50
+ "OpenSans-VariableFont_wdth,wght.ttf");
51
+ if (!ops)
52
+ widget_log_error(-1, "SDLResourceManager::get");
53
+ else
54
+ {
55
+ _font = TTF_OpenFontRW(ops, 1, 64);
56
+ if (!_font)
57
+ widget_log_error(-1, "TTF_OpenFontRW");
58
+ }
59
+ }
60
+
61
+ #if defined(WITH_SDL_IMAGE_DIALOGS)
62
+ SdlWidget::SdlWidget(SDL_Renderer* renderer, SDL_Rect rect, SDL_RWops* ops) : _rect(rect)
63
+ {
64
+ if (ops)
65
+ {
66
+ _image = IMG_LoadTexture_RW(renderer, ops, 1);
67
+ if (!_image)
68
+ widget_log_error(-1, "IMG_LoadTextureTyped_RW");
69
+ }
70
+ }
71
+ #endif
72
+
73
+ SdlWidget::SdlWidget(SdlWidget&& other) noexcept
74
+ : _font(other._font), _image(other._image), _rect(other._rect), _input(other._input),
75
+ _wrap(other._wrap), _text_width(other._text_width)
76
+ {
77
+ other._font = nullptr;
78
+ other._image = nullptr;
79
+ }
80
+
81
+ SDL_Texture* SdlWidget::render_text(SDL_Renderer* renderer, const std::string& text,
82
+ SDL_Color fgcolor, SDL_Rect& src, SDL_Rect& dst)
83
+ {
84
+ auto surface = TTF_RenderUTF8_Blended(_font, text.c_str(), fgcolor);
85
+ if (!surface)
86
+ {
87
+ widget_log_error(-1, "TTF_RenderText_Blended");
88
+ return nullptr;
89
+ }
90
+
91
+ auto texture = SDL_CreateTextureFromSurface(renderer, surface);
92
+ SDL_FreeSurface(surface);
93
+ if (!texture)
94
+ {
95
+ widget_log_error(-1, "SDL_CreateTextureFromSurface");
96
+ return nullptr;
97
+ }
98
+
99
+ TTF_SizeUTF8(_font, text.c_str(), &src.w, &src.h);
100
+
101
+ /* Do some magic:
102
+ * - Add padding before and after text
103
+ * - if text is too long only show the last elements
104
+ * - if text is too short only update used space
105
+ */
106
+ dst = _rect;
107
+ dst.x += hpadding;
108
+ dst.w -= 2 * hpadding;
109
+ const auto scale = static_cast<float>(dst.h) / static_cast<float>(src.h);
110
+ const auto sws = static_cast<float>(src.w) * scale;
111
+ const auto dws = static_cast<float>(dst.w) / scale;
112
+ if (static_cast<float>(dst.w) > sws)
113
+ dst.w = static_cast<int>(sws);
114
+ if (static_cast<float>(src.w) > dws)
115
+ {
116
+ src.x = src.w - static_cast<int>(dws);
117
+ src.w = static_cast<int>(dws);
118
+ }
119
+ return texture;
120
+ }
121
+
122
+ static int scale(int w, int h)
123
+ {
124
+ const auto dw = static_cast<double>(w);
125
+ const auto dh = static_cast<double>(h);
126
+ const auto scale = dh / dw;
127
+ const auto dr = dh * scale;
128
+ return static_cast<int>(dr);
129
+ }
130
+
131
+ SDL_Texture* SdlWidget::render_text_wrapped(SDL_Renderer* renderer, const std::string& text,
132
+ SDL_Color fgcolor, SDL_Rect& src, SDL_Rect& dst)
133
+ {
134
+ Sint32 w = 0;
135
+ Sint32 h = 0;
136
+ TTF_SizeUTF8(_font, " ", &w, &h);
137
+
138
+ assert(_text_width <= UINT32_MAX);
139
+ auto surface = TTF_RenderUTF8_Blended_Wrapped(_font, text.c_str(), fgcolor,
140
+ static_cast<Uint32>(_text_width));
141
+ if (!surface)
142
+ {
143
+ widget_log_error(-1, "TTF_RenderText_Blended");
144
+ return nullptr;
145
+ }
146
+
147
+ src.w = surface->w;
148
+ src.h = surface->h;
149
+
150
+ auto texture = SDL_CreateTextureFromSurface(renderer, surface);
151
+ SDL_FreeSurface(surface);
152
+ if (!texture)
153
+ {
154
+ widget_log_error(-1, "SDL_CreateTextureFromSurface");
155
+ return nullptr;
156
+ }
157
+
158
+ /* Do some magic:
159
+ * - Add padding before and after text
160
+ * - if text is too long only show the last elements
161
+ * - if text is too short only update used space
162
+ */
163
+ dst = _rect;
164
+ dst.x += hpadding;
165
+ dst.w -= 2 * hpadding;
166
+ auto dh = scale(src.w, src.h);
167
+ dst.h = std::min<int>(dh, dst.h);
168
+
169
+ return texture;
170
+ }
171
+
172
+ SdlWidget::~SdlWidget()
173
+ {
174
+ TTF_CloseFont(_font);
175
+ if (_image)
176
+ SDL_DestroyTexture(_image);
177
+ }
178
+
179
+ bool SdlWidget::error_ex(Sint32 res, const char* what, const char* file, size_t line,
180
+ const char* fkt)
181
+ {
182
+ static wLog* log = nullptr;
183
+ if (!log)
184
+ log = WLog_Get(TAG);
185
+ return sdl_log_error_ex(res, log, what, file, line, fkt);
186
+ }
187
+
188
+ static bool draw_rect(SDL_Renderer* renderer, const SDL_Rect* rect, SDL_Color color)
189
+ {
190
+ const int drc = SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
191
+ if (widget_log_error(drc, "SDL_SetRenderDrawColor"))
192
+ return false;
193
+
194
+ const int rc = SDL_RenderFillRect(renderer, rect);
195
+ return !widget_log_error(rc, "SDL_RenderFillRect");
196
+ }
197
+
198
+ bool SdlWidget::fill(SDL_Renderer* renderer, SDL_Color color)
199
+ {
200
+ std::vector<SDL_Color> colors = { color };
201
+ return fill(renderer, colors);
202
+ }
203
+
204
+ bool SdlWidget::fill(SDL_Renderer* renderer, const std::vector<SDL_Color>& colors)
205
+ {
206
+ assert(renderer);
207
+ SDL_BlendMode mode = SDL_BLENDMODE_INVALID;
208
+ SDL_GetRenderDrawBlendMode(renderer, &mode);
209
+ SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
210
+ for (auto color : colors)
211
+ {
212
+ draw_rect(renderer, &_rect, color);
213
+ SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);
214
+ }
215
+ SDL_SetRenderDrawBlendMode(renderer, mode);
216
+ return true;
217
+ }
218
+
219
+ bool SdlWidget::update_text(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor,
220
+ SDL_Color bgcolor)
221
+ {
222
+ assert(renderer);
223
+
224
+ if (!fill(renderer, bgcolor))
225
+ return false;
226
+ return update_text(renderer, text, fgcolor);
227
+ }
228
+
229
+ bool SdlWidget::wrap() const
230
+ {
231
+ return _wrap;
232
+ }
233
+
234
+ bool SdlWidget::set_wrap(bool wrap, size_t width)
235
+ {
236
+ _wrap = wrap;
237
+ _text_width = width;
238
+ return _wrap;
239
+ }
240
+
241
+ const SDL_Rect& SdlWidget::rect() const
242
+ {
243
+ return _rect;
244
+ }
245
+
246
+ bool SdlWidget::update_text(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor)
247
+ {
248
+
249
+ if (text.empty())
250
+ return true;
251
+
252
+ SDL_Rect src{};
253
+ SDL_Rect dst{};
254
+
255
+ SDL_Texture* texture = nullptr;
256
+ if (_image)
257
+ {
258
+ texture = _image;
259
+ dst = _rect;
260
+ auto rc = SDL_QueryTexture(_image, nullptr, nullptr, &src.w, &src.h);
261
+ if (rc < 0)
262
+ widget_log_error(rc, "SDL_QueryTexture");
263
+ }
264
+ else if (_wrap)
265
+ texture = render_text_wrapped(renderer, text, fgcolor, src, dst);
266
+ else
267
+ texture = render_text(renderer, text, fgcolor, src, dst);
268
+ if (!texture)
269
+ return false;
270
+
271
+ const int rc = SDL_RenderCopy(renderer, texture, &src, &dst);
272
+ if (!_image)
273
+ SDL_DestroyTexture(texture);
274
+ if (rc < 0)
275
+ return !widget_log_error(rc, "SDL_RenderCopy");
276
+ return true;
277
+ }
278
+
279
+ bool clear_window(SDL_Renderer* renderer)
280
+ {
281
+ assert(renderer);
282
+
283
+ const int drc = SDL_SetRenderDrawColor(renderer, backgroundcolor.r, backgroundcolor.g,
284
+ backgroundcolor.b, backgroundcolor.a);
285
+ if (widget_log_error(drc, "SDL_SetRenderDrawColor"))
286
+ return false;
287
+
288
+ const int rcls = SDL_RenderClear(renderer);
289
+ return !widget_log_error(rcls, "SDL_RenderClear");
290
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/sdl_widget.hpp ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <string>
23
+
24
+ #include <vector>
25
+ #include <SDL.h>
26
+ #include <SDL_ttf.h>
27
+
28
+ #if defined(_MSC_VER)
29
+ #include <BaseTsd.h>
30
+ typedef SSIZE_T ssize_t;
31
+ #endif
32
+
33
+ #if !defined(HAS_NOEXCEPT)
34
+ #if defined(__clang__)
35
+ #if __has_feature(cxx_noexcept)
36
+ #define HAS_NOEXCEPT
37
+ #endif
38
+ #elif defined(__GXX_EXPERIMENTAL_CXX0X__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 46 || \
39
+ defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023026
40
+ #define HAS_NOEXCEPT
41
+ #endif
42
+ #endif
43
+
44
+ #ifndef HAS_NOEXCEPT
45
+ #define noexcept
46
+ #endif
47
+
48
+ class SdlWidget
49
+ {
50
+ public:
51
+ SdlWidget(SDL_Renderer* renderer, SDL_Rect rect, bool input);
52
+ #if defined(WITH_SDL_IMAGE_DIALOGS)
53
+ SdlWidget(SDL_Renderer* renderer, SDL_Rect rect, SDL_RWops* ops);
54
+ #endif
55
+ SdlWidget(SdlWidget&& other) noexcept;
56
+ virtual ~SdlWidget();
57
+
58
+ bool fill(SDL_Renderer* renderer, SDL_Color color);
59
+ bool fill(SDL_Renderer* renderer, const std::vector<SDL_Color>& colors);
60
+ bool update_text(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor);
61
+ bool update_text(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor,
62
+ SDL_Color bgcolor);
63
+
64
+ [[nodiscard]] bool wrap() const;
65
+ bool set_wrap(bool wrap = true, size_t width = 0);
66
+ [[nodiscard]] const SDL_Rect& rect() const;
67
+
68
+ #define widget_log_error(res, what) SdlWidget::error_ex(res, what, __FILE__, __LINE__, __func__)
69
+ static bool error_ex(Sint32 res, const char* what, const char* file, size_t line,
70
+ const char* fkt);
71
+
72
+ SdlWidget(const SdlWidget& other) = delete;
73
+ SdlWidget& operator=(const SdlWidget& other) = delete;
74
+ SdlWidget& operator=(SdlWidget&& other) = delete;
75
+
76
+ private:
77
+ SDL_Texture* render_text(SDL_Renderer* renderer, const std::string& text, SDL_Color fgcolor,
78
+ SDL_Rect& src, SDL_Rect& dst);
79
+ SDL_Texture* render_text_wrapped(SDL_Renderer* renderer, const std::string& text,
80
+ SDL_Color fgcolor, SDL_Rect& src, SDL_Rect& dst);
81
+
82
+ TTF_Font* _font = nullptr;
83
+ SDL_Texture* _image = nullptr;
84
+ SDL_Rect _rect;
85
+ bool _input = false;
86
+ bool _wrap = false;
87
+ size_t _text_width = 0;
88
+ };
89
+
90
+ bool clear_window(SDL_Renderer* renderer);
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/test/CMakeLists.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set(MODULE_NAME "TestSDL")
2
+ set(MODULE_PREFIX "TEST_SDL")
3
+
4
+ set(DRIVER ${MODULE_NAME}.cpp)
5
+
6
+ disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR})
7
+
8
+ set(TEST_SRCS TestSDLDialogs.cpp)
9
+
10
+ create_test_sourcelist(SRCS ${DRIVER} ${TEST_SRCS})
11
+
12
+ add_library(${MODULE_NAME} ${SRCS})
13
+
14
+ list(APPEND LIBS dialogs)
15
+
16
+ target_link_libraries(${MODULE_NAME} ${LIBS})
17
+
18
+ set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}")
19
+
20
+ foreach(test ${TESTS})
21
+ get_filename_component(TestName ${test} NAME_WE)
22
+ add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName})
23
+ endforeach()
24
+
25
+ set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "FreeRDP/Client/Test")
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/dialogs/test/TestSDLDialogs.cpp ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../sdl_selectlist.hpp"
2
+ #include "../sdl_input_widgets.hpp"
3
+
4
+ #include <freerdp/api.h>
5
+ #include <winpr/wlog.h>
6
+
7
+ BOOL sdl_log_error_ex(Uint32 res, wLog* log, const char* what, const char* file, size_t line,
8
+ const char* fkt)
9
+ {
10
+ return FALSE;
11
+ }
12
+
13
+ static bool test_input_dialog()
14
+ {
15
+ const auto title = "sometitle";
16
+ std::vector<std::string> labels;
17
+ std::vector<std::string> initial;
18
+ std::vector<Uint32> flags;
19
+ for (size_t x = 0; x < 12; x++)
20
+ {
21
+ labels.push_back("label" + std::to_string(x));
22
+ initial.push_back(std::to_string(x));
23
+
24
+ Uint32 flag = 0;
25
+ if ((x % 2) != 0)
26
+ flag |= SdlInputWidget::SDL_INPUT_MASK;
27
+ if ((x % 3) == 0)
28
+ flag |= SdlInputWidget::SDL_INPUT_READONLY;
29
+
30
+ flags.push_back(flag);
31
+ }
32
+ SdlInputWidgetList list{ title, labels, initial, flags };
33
+ std::vector<std::string> result;
34
+ auto rc = list.run(result);
35
+ if (rc < 0)
36
+ {
37
+ return false;
38
+ }
39
+ if (result.size() != labels.size())
40
+ {
41
+ return false;
42
+ }
43
+ return true;
44
+ }
45
+
46
+ static bool test_select_dialog()
47
+ {
48
+ const auto title = "sometitle";
49
+ std::vector<std::string> labels;
50
+ for (size_t x = 0; x < 12; x++)
51
+ {
52
+ labels.push_back("label" + std::to_string(x));
53
+ }
54
+ SdlSelectList list{ title, labels };
55
+ auto rc = list.run();
56
+ if (rc < 0)
57
+ {
58
+ return false;
59
+ }
60
+ if (static_cast<size_t>(rc) >= labels.size())
61
+ return false;
62
+
63
+ return true;
64
+ }
65
+
66
+ extern "C"
67
+ {
68
+ FREERDP_API int TestSDLDialogs(int argc, char* argv[]);
69
+ }
70
+
71
+ int TestSDLDialogs(int argc, char* argv[])
72
+ {
73
+ int rc = 0;
74
+
75
+ (void)argc;
76
+ (void)argv;
77
+
78
+ #if 0
79
+ SDL_Init(SDL_INIT_VIDEO);
80
+ try
81
+ {
82
+ #if 1
83
+ if (!test_input_dialog())
84
+ throw -1;
85
+ #endif
86
+ #if 1
87
+ if (!test_select_dialog())
88
+ throw -2;
89
+ #endif
90
+ }
91
+ catch (int e)
92
+ {
93
+ rc = e;
94
+ }
95
+ SDL_Quit();
96
+
97
+ #endif
98
+ return rc;
99
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/man/CMakeLists.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ set(DEPS
2
+ ../../../common/man/freerdp-global-options.1 ../../common/man/sdl-freerdp-config.1
3
+ ../../../common/man/freerdp-global-envvar.1 ../../../common/man/freerdp-global-config.1
4
+ ../../common/man/sdl-freerdp-examples.1 ../../../common/man/freerdp-global-links.1
5
+ )
6
+
7
+ set(VAR_NAMES "VENDOR" "PRODUCT" "VENDOR_PRODUCT" "CMAKE_INSTALL_FULL_SYSCONFDIR")
8
+ generate_and_install_freerdp_man_from_xml(${MODULE_NAME} "1" "${DEPS}" "${VAR_NAMES}")
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL2/man/sdl2-freerdp.1.in ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .TH "@MANPAGE_NAME@" "1" "@MAN_TODAY@" "freerdp" "@MANPAGE_NAME@"
2
+ .ie \n(.g .ds Aq \(aq
3
+ .el .ds Aq '
4
+ .nh
5
+ .ad l
6
+ .SH "NAME"
7
+ @MANPAGE_NAME@ \- FreeRDP SDL client
8
+ .SH "SYNOPSIS"
9
+ .PP
10
+ \fB@MANPAGE_NAME@\fR
11
+ [file] [options] [/v:server[:port]]
12
+ .SH "DESCRIPTION"
13
+ .PP
14
+ \fB@MANPAGE_NAME@\fR
15
+ is an SDL Remote Desktop Protocol (RDP) client which is part of the FreeRDP project\&. An RDP server is built\-in to many editions of Windows\&. Alternative servers included ogon, gnome\-remote\-desktop, xrdp and VRDP (VirtualBox)\&.
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/font/OFL.txt ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2020 The Open Sans Project Authors (https://github.com/googlefonts/opensans)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/font/README.txt ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Open Sans Variable Font
2
+ =======================
3
+
4
+ This download contains Open Sans as both variable fonts and static fonts.
5
+
6
+ Open Sans is a variable font with these axes:
7
+ wdth
8
+ wght
9
+
10
+ This means all the styles are contained in these files:
11
+ OpenSans-VariableFont_wdth,wght.ttf
12
+ OpenSans-Italic-VariableFont_wdth,wght.ttf
13
+
14
+ If your app fully supports variable fonts, you can now pick intermediate styles
15
+ that aren’t available as static fonts. Not all apps support variable fonts, and
16
+ in those cases you can use the static font files for Open Sans:
17
+ static/OpenSans_Condensed-Light.ttf
18
+ static/OpenSans_Condensed-Regular.ttf
19
+ static/OpenSans_Condensed-Medium.ttf
20
+ static/OpenSans_Condensed-SemiBold.ttf
21
+ static/OpenSans_Condensed-Bold.ttf
22
+ static/OpenSans_Condensed-ExtraBold.ttf
23
+ static/OpenSans_SemiCondensed-Light.ttf
24
+ static/OpenSans_SemiCondensed-Regular.ttf
25
+ static/OpenSans_SemiCondensed-Medium.ttf
26
+ static/OpenSans_SemiCondensed-SemiBold.ttf
27
+ static/OpenSans_SemiCondensed-Bold.ttf
28
+ static/OpenSans_SemiCondensed-ExtraBold.ttf
29
+ static/OpenSans-Light.ttf
30
+ static/OpenSans-Regular.ttf
31
+ static/OpenSans-Medium.ttf
32
+ static/OpenSans-SemiBold.ttf
33
+ static/OpenSans-Bold.ttf
34
+ static/OpenSans-ExtraBold.ttf
35
+ static/OpenSans_Condensed-LightItalic.ttf
36
+ static/OpenSans_Condensed-Italic.ttf
37
+ static/OpenSans_Condensed-MediumItalic.ttf
38
+ static/OpenSans_Condensed-SemiBoldItalic.ttf
39
+ static/OpenSans_Condensed-BoldItalic.ttf
40
+ static/OpenSans_Condensed-ExtraBoldItalic.ttf
41
+ static/OpenSans_SemiCondensed-LightItalic.ttf
42
+ static/OpenSans_SemiCondensed-Italic.ttf
43
+ static/OpenSans_SemiCondensed-MediumItalic.ttf
44
+ static/OpenSans_SemiCondensed-SemiBoldItalic.ttf
45
+ static/OpenSans_SemiCondensed-BoldItalic.ttf
46
+ static/OpenSans_SemiCondensed-ExtraBoldItalic.ttf
47
+ static/OpenSans-LightItalic.ttf
48
+ static/OpenSans-Italic.ttf
49
+ static/OpenSans-MediumItalic.ttf
50
+ static/OpenSans-SemiBoldItalic.ttf
51
+ static/OpenSans-BoldItalic.ttf
52
+ static/OpenSans-ExtraBoldItalic.ttf
53
+
54
+ Get started
55
+ -----------
56
+
57
+ 1. Install the font files you want to use
58
+
59
+ 2. Use your app's font picker to view the font family and all the
60
+ available styles
61
+
62
+ Learn more about variable fonts
63
+ -------------------------------
64
+
65
+ https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts
66
+ https://variablefonts.typenetwork.com
67
+ https://medium.com/variable-fonts
68
+
69
+ In desktop apps
70
+
71
+ https://theblog.adobe.com/can-variable-fonts-illustrator-cc
72
+ https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts
73
+
74
+ Online
75
+
76
+ https://developers.google.com/fonts/docs/getting_started
77
+ https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide
78
+ https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts
79
+
80
+ Installing fonts
81
+
82
+ MacOS: https://support.apple.com/en-us/HT201749
83
+ Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux
84
+ Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows
85
+
86
+ Android Apps
87
+
88
+ https://developers.google.com/fonts/docs/android
89
+ https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts
90
+
91
+ License
92
+ -------
93
+ Please read the full license text (OFL.txt) to understand the permissions,
94
+ restrictions and requirements for usage, redistribution, and modification.
95
+
96
+ You can use them in your products & projects – print or digital,
97
+ commercial or otherwise.
98
+
99
+ This isn't legal advice, please consider consulting a lawyer and see the full
100
+ license for all details.
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/res/CMakeLists.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FreeRDP: A Remote Desktop Protocol Implementation
2
+ # FreeRDP SDL Client
3
+ #
4
+ # Copyright 2024 Armin Novak <[email protected]>
5
+ # Copyright 2024 Thincast Technologies GmbH
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ set(SRCS sdl3_resource_manager.cpp sdl3_resource_manager.hpp)
19
+
20
+ add_library(sdl3_client_res STATIC ${SRCS})
21
+ if(NOT WITH_SDL_LINK_SHARED)
22
+ target_link_libraries(sdl3_client_res ${SDL3_STATIC_LIBRARIES})
23
+ else()
24
+ target_link_libraries(sdl3_client_res ${SDL3_LIBRARIES})
25
+ endif()
26
+
27
+ target_link_libraries(sdl3_client_res sdl-common-client-res)
28
+
29
+ set_target_properties(sdl3_client_res PROPERTIES POSITION_INDEPENDENT_CODE ON INTERPROCEDURAL_OPTIMIZATION OFF)
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/sdl_input.hpp ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * SDL Client helper dialogs
4
+ *
5
+ * Copyright 2023 Armin Novak <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <vector>
23
+ #include <string>
24
+
25
+ #include <SDL3/SDL.h>
26
+ #include "sdl_widget.hpp"
27
+
28
+ class SdlInputWidget
29
+ {
30
+ public:
31
+ enum
32
+ {
33
+ SDL_INPUT_MASK = 1,
34
+ SDL_INPUT_READONLY = 2
35
+ };
36
+
37
+ SdlInputWidget(SDL_Renderer* renderer, std::string label, std::string initial, Uint32 flags,
38
+ size_t offset, size_t width, size_t height);
39
+ SdlInputWidget(SdlInputWidget&& other) noexcept;
40
+ SdlInputWidget(const SdlInputWidget& other) = delete;
41
+
42
+ SdlInputWidget& operator=(const SdlInputWidget& other) = delete;
43
+ SdlInputWidget& operator=(SdlInputWidget&& other) = delete;
44
+
45
+ bool fill_label(SDL_Renderer* renderer, SDL_Color color);
46
+ bool update_label(SDL_Renderer* renderer);
47
+
48
+ bool set_mouseover(SDL_Renderer* renderer, bool mouseOver);
49
+ bool set_highlight(SDL_Renderer* renderer, bool highlight);
50
+ bool update_input(SDL_Renderer* renderer);
51
+ bool resize_input(size_t size);
52
+
53
+ bool set_str(SDL_Renderer* renderer, const std::string& text);
54
+ bool remove_str(SDL_Renderer* renderer, size_t count);
55
+ bool append_str(SDL_Renderer* renderer, const std::string& text);
56
+
57
+ [[nodiscard]] const SDL_FRect& input_rect() const;
58
+ [[nodiscard]] std::string value() const;
59
+
60
+ [[nodiscard]] bool readonly() const;
61
+
62
+ protected:
63
+ bool update_input(SDL_Renderer* renderer, SDL_Color fgcolor);
64
+
65
+ private:
66
+ Uint32 _flags;
67
+ std::string _text;
68
+ std::string _text_label;
69
+ SdlWidget _label;
70
+ SdlWidget _input;
71
+ bool _highlight;
72
+ bool _mouseover;
73
+ };
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/sdl_selectlist.cpp ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <cassert>
2
+ #include <winpr/cast.h>
3
+ #include "sdl_selectlist.hpp"
4
+
5
+ static const Uint32 vpadding = 5;
6
+
7
+ SdlSelectList::SdlSelectList(const std::string& title, const std::vector<std::string>& labels)
8
+ : _window(nullptr), _renderer(nullptr)
9
+ {
10
+ const size_t widget_height = 50;
11
+ const size_t widget_width = 600;
12
+
13
+ const size_t total_height = labels.size() * (widget_height + vpadding) + vpadding;
14
+ const size_t height = total_height + widget_height;
15
+ static_assert(widget_width <= INT32_MAX);
16
+ assert(height <= INT32_MAX);
17
+ auto rc = SDL_CreateWindowAndRenderer(
18
+ title.c_str(), static_cast<int>(widget_width), static_cast<int>(height),
19
+ SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_INPUT_FOCUS, &_window,
20
+ &_renderer);
21
+ if (rc != 0)
22
+ widget_log_error(rc, "SDL_CreateWindowAndRenderer");
23
+ else
24
+ {
25
+ SDL_FRect rect = { 0, 0, widget_width, widget_height };
26
+ for (auto& label : labels)
27
+ {
28
+ _list.emplace_back(_renderer, label, rect);
29
+ rect.y += widget_height + vpadding;
30
+ }
31
+
32
+ const std::vector<int> buttonids = { INPUT_BUTTON_ACCEPT, INPUT_BUTTON_CANCEL };
33
+ const std::vector<std::string> buttonlabels = { "accept", "cancel" };
34
+ _buttons.populate(_renderer, buttonlabels, buttonids, widget_width,
35
+ static_cast<Sint32>(total_height), static_cast<Sint32>(widget_width / 2),
36
+ static_cast<Sint32>(widget_height));
37
+ _buttons.set_highlight(0);
38
+ }
39
+ }
40
+
41
+ SdlSelectList::~SdlSelectList()
42
+ {
43
+ _list.clear();
44
+ _buttons.clear();
45
+ SDL_DestroyRenderer(_renderer);
46
+ SDL_DestroyWindow(_window);
47
+ }
48
+
49
+ int SdlSelectList::run()
50
+ {
51
+ int res = -2;
52
+ ssize_t CurrentActiveTextInput = 0;
53
+ bool running = true;
54
+
55
+ if (!_window || !_renderer)
56
+ return -2;
57
+ try
58
+ {
59
+ while (running)
60
+ {
61
+ if (!clear_window(_renderer))
62
+ throw;
63
+
64
+ if (!update_text())
65
+ throw;
66
+
67
+ if (!_buttons.update(_renderer))
68
+ throw;
69
+
70
+ SDL_Event event = {};
71
+ SDL_WaitEvent(&event);
72
+ switch (event.type)
73
+ {
74
+ case SDL_EVENT_KEY_DOWN:
75
+ switch (event.key.key)
76
+ {
77
+ case SDLK_UP:
78
+ case SDLK_BACKSPACE:
79
+ if (CurrentActiveTextInput > 0)
80
+ CurrentActiveTextInput--;
81
+ else if (_list.empty())
82
+ CurrentActiveTextInput = 0;
83
+ else
84
+ {
85
+ auto s = _list.size();
86
+ CurrentActiveTextInput = WINPR_ASSERTING_INT_CAST(ssize_t, s) - 1;
87
+ }
88
+ break;
89
+ case SDLK_DOWN:
90
+ case SDLK_TAB:
91
+ if ((CurrentActiveTextInput < 0) || _list.empty())
92
+ CurrentActiveTextInput = 0;
93
+ else
94
+ {
95
+ auto s = _list.size();
96
+ CurrentActiveTextInput++;
97
+ if (s > 0)
98
+ {
99
+ CurrentActiveTextInput = CurrentActiveTextInput %
100
+ WINPR_ASSERTING_INT_CAST(ssize_t, s);
101
+ }
102
+ }
103
+ break;
104
+ case SDLK_RETURN:
105
+ case SDLK_RETURN2:
106
+ case SDLK_KP_ENTER:
107
+ running = false;
108
+ res = static_cast<int>(CurrentActiveTextInput);
109
+ break;
110
+ case SDLK_ESCAPE:
111
+ running = false;
112
+ res = INPUT_BUTTON_CANCEL;
113
+ break;
114
+ default:
115
+ break;
116
+ }
117
+ break;
118
+ case SDL_EVENT_MOUSE_MOTION:
119
+ {
120
+ ssize_t TextInputIndex = get_index(event.button);
121
+ reset_mouseover();
122
+ if (TextInputIndex >= 0)
123
+ {
124
+ auto& cur = _list[WINPR_ASSERTING_INT_CAST(size_t, TextInputIndex)];
125
+ if (!cur.set_mouseover(_renderer, true))
126
+ throw;
127
+ }
128
+
129
+ _buttons.set_mouseover(event.button.x, event.button.y);
130
+ }
131
+ break;
132
+ case SDL_EVENT_MOUSE_BUTTON_DOWN:
133
+ {
134
+ auto button = _buttons.get_selected(event.button);
135
+ if (button)
136
+ {
137
+ running = false;
138
+ if (button->id() == INPUT_BUTTON_CANCEL)
139
+ res = INPUT_BUTTON_CANCEL;
140
+ else
141
+ res = static_cast<int>(CurrentActiveTextInput);
142
+ }
143
+ else
144
+ {
145
+ CurrentActiveTextInput = get_index(event.button);
146
+ }
147
+ }
148
+ break;
149
+ case SDL_EVENT_QUIT:
150
+ res = INPUT_BUTTON_CANCEL;
151
+ running = false;
152
+ break;
153
+ default:
154
+ break;
155
+ }
156
+
157
+ reset_highlight();
158
+ if (CurrentActiveTextInput >= 0)
159
+ {
160
+ auto& cur = _list[WINPR_ASSERTING_INT_CAST(size_t, CurrentActiveTextInput)];
161
+ if (!cur.set_highlight(_renderer, true))
162
+ throw;
163
+ }
164
+
165
+ SDL_RenderPresent(_renderer);
166
+ }
167
+ }
168
+ catch (...)
169
+ {
170
+ return -1;
171
+ }
172
+ return res;
173
+ }
174
+
175
+ ssize_t SdlSelectList::get_index(const SDL_MouseButtonEvent& button)
176
+ {
177
+ const auto x = button.x;
178
+ const auto y = button.y;
179
+ for (size_t i = 0; i < _list.size(); i++)
180
+ {
181
+ auto& cur = _list[i];
182
+ auto r = cur.rect();
183
+
184
+ if ((x >= r.x) && (x <= r.x + r.w) && (y >= r.y) && (y <= r.y + r.h))
185
+ return WINPR_ASSERTING_INT_CAST(ssize_t, i);
186
+ }
187
+ return -1;
188
+ }
189
+
190
+ bool SdlSelectList::update_text()
191
+ {
192
+ for (auto& cur : _list)
193
+ {
194
+ if (!cur.update_text(_renderer))
195
+ return false;
196
+ }
197
+
198
+ return true;
199
+ }
200
+
201
+ void SdlSelectList::reset_mouseover()
202
+ {
203
+ for (auto& cur : _list)
204
+ {
205
+ cur.set_mouseover(_renderer, false);
206
+ }
207
+ }
208
+
209
+ void SdlSelectList::reset_highlight()
210
+ {
211
+ for (auto& cur : _list)
212
+ {
213
+ cur.set_highlight(_renderer, false);
214
+ }
215
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/SDL3/dialogs/test/CMakeLists.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set(MODULE_NAME "TestSDL")
2
+ set(MODULE_PREFIX "TEST_SDL")
3
+
4
+ set(DRIVER ${MODULE_NAME}.cpp)
5
+
6
+ disable_warnings_for_directory(${CMAKE_CURRENT_BINARY_DIR})
7
+
8
+ set(TEST_SRCS TestSDLDialogs.cpp)
9
+
10
+ create_test_sourcelist(SRCS ${DRIVER} ${TEST_SRCS})
11
+
12
+ add_library(${MODULE_NAME} ${SRCS})
13
+
14
+ list(APPEND LIBS dialogs)
15
+
16
+ target_link_libraries(${MODULE_NAME} ${LIBS})
17
+
18
+ set_target_properties(${MODULE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TESTING_OUTPUT_DIRECTORY}")
19
+
20
+ foreach(test ${TESTS})
21
+ get_filename_component(TestName ${test} NAME_WE)
22
+ add_test(${TestName} ${TESTING_OUTPUT_DIRECTORY}/${MODULE_NAME} ${TestName})
23
+ endforeach()
24
+
25
+ set_property(TARGET ${MODULE_NAME} PROPERTY FOLDER "FreeRDP/Client/Test")
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/CMakeLists.txt ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FreeRDP: A Remote Desktop Protocol Implementation
2
+ # FreeRDP SDL Client
3
+ #
4
+ # Copyright 2024 Armin Novak <[email protected]>
5
+ # Copyright 2024 Thincast Technologies GmbH
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ set(WITH_WEBVIEW_DEFAULT OFF)
19
+
20
+ option(WITH_WEBVIEW "Build with WebView support for AAD login popup browser" ${WITH_WEBVIEW_DEFAULT})
21
+ if(WITH_WEBVIEW)
22
+ option(WITH_WEBVIEW_QT "Build with QtWebEngine support for AAD login broweser popup" OFF)
23
+
24
+ set(SRCS sdl_webview.hpp webview_impl.hpp sdl_webview.cpp)
25
+ set(LIBS winpr)
26
+
27
+ if(WITH_WEBVIEW_QT)
28
+ find_package(Qt5 COMPONENTS WebEngineWidgets REQUIRED)
29
+
30
+ list(APPEND SRCS qt/webview_impl.cpp)
31
+
32
+ list(APPEND LIBS Qt5::WebEngineWidgets)
33
+ else()
34
+ list(APPEND SRCS wrapper/webview.h wrapper/webview_impl.cpp)
35
+
36
+ if(APPLE)
37
+ find_library(WEBKIT Webkit REQUIRED)
38
+ list(APPEND LIBS ${WEBKIT})
39
+ elseif(NOT WIN32)
40
+ find_package(PkgConfig REQUIRED)
41
+ pkg_check_modules(WEBVIEW_GTK webkit2gtk-4.1)
42
+ if(NOT WEBVIEW_GTK_FOUND)
43
+ pkg_check_modules(WEBVIEW_GTK webkit2gtk-4.0 REQUIRED)
44
+ endif()
45
+ include_directories(SYSTEM ${WEBVIEW_GTK_INCLUDE_DIRS})
46
+ list(APPEND LIBS ${WEBVIEW_GTK_LIBRARIES})
47
+ endif()
48
+ endif()
49
+ else()
50
+ set(SRCS dummy.cpp)
51
+ endif()
52
+
53
+ cleaning_configure_file(sdl_config.hpp.in sdl_config.hpp @ONLY)
54
+ include_directories(${CMAKE_CURRENT_BINARY_DIR})
55
+
56
+ add_library(sdl-common-aad-view STATIC ${SRCS})
57
+ target_include_directories(sdl-common-aad-view PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
58
+ target_link_libraries(sdl-common-aad-view PRIVATE ${LIBS})
59
+ target_compile_definitions(sdl-common-aad-view PUBLIC ${DEFINITIONS})
60
+ if(WITH_WEBVIEW AND NOT WITH_WEBVIEW_QT)
61
+ include(WebView2)
62
+ target_link_webview2("sdl-common-aad-view")
63
+ endif()
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/dummy.cpp ADDED
File without changes
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/qt/webview_impl.cpp ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * Popup browser for AAD authentication
4
+ *
5
+ * Copyright 2023 Isaac Klein <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include <QApplication>
21
+ #include <QWebEngineView>
22
+ #include <QWebEngineProfile>
23
+ #include <QWebEngineUrlScheme>
24
+ #include <QWebEngineUrlSchemeHandler>
25
+ #include <QWebEngineUrlRequestJob>
26
+
27
+ #include <string>
28
+ #include <cstdlib>
29
+ #include <cstdarg>
30
+ #include <winpr/string.h>
31
+ #include <winpr/assert.h>
32
+ #include <freerdp/log.h>
33
+ #include <freerdp/build-config.h>
34
+
35
+ #include "../webview_impl.hpp"
36
+
37
+ #define TAG CLIENT_TAG("sdl.webview")
38
+
39
+ class SchemeHandler : public QWebEngineUrlSchemeHandler
40
+ {
41
+ public:
42
+ explicit SchemeHandler(QObject* parent = nullptr) : QWebEngineUrlSchemeHandler(parent)
43
+ {
44
+ }
45
+
46
+ void requestStarted(QWebEngineUrlRequestJob* request) override
47
+ {
48
+ QUrl url = request->requestUrl();
49
+
50
+ int rc = -1;
51
+ for (auto& param : url.query().split('&'))
52
+ {
53
+ QStringList pair = param.split('=');
54
+
55
+ if (pair.size() != 2 || pair[0] != QLatin1String("code"))
56
+ continue;
57
+
58
+ auto qc = pair[1];
59
+ m_code = qc.toStdString();
60
+ rc = 0;
61
+ break;
62
+ }
63
+ qApp->exit(rc);
64
+ }
65
+
66
+ [[nodiscard]] std::string code() const
67
+ {
68
+ return m_code;
69
+ }
70
+
71
+ private:
72
+ std::string m_code{};
73
+ };
74
+
75
+ bool webview_impl_run(const std::string& title, const std::string& url, std::string& code)
76
+ {
77
+ int argc = 1;
78
+ const auto vendor = QLatin1String(FREERDP_VENDOR_STRING);
79
+ const auto product = QLatin1String(FREERDP_PRODUCT_STRING);
80
+ QWebEngineUrlScheme::registerScheme(QWebEngineUrlScheme("ms-appx-web"));
81
+
82
+ std::string wtitle = title;
83
+ char* argv[] = { wtitle.data() };
84
+ QCoreApplication::setOrganizationName(vendor);
85
+ QCoreApplication::setApplicationName(product);
86
+ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
87
+ QApplication app(argc, argv);
88
+
89
+ SchemeHandler handler;
90
+ QWebEngineProfile::defaultProfile()->installUrlSchemeHandler("ms-appx-web", &handler);
91
+
92
+ QWebEngineView webview;
93
+ webview.load(QUrl(QString::fromStdString(url)));
94
+ webview.show();
95
+
96
+ if (app.exec() != 0)
97
+ return false;
98
+
99
+ auto val = handler.code();
100
+ if (val.empty())
101
+ return false;
102
+ code = val;
103
+
104
+ return !code.empty();
105
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_config.hpp.in ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #pragma once
2
+
3
+ #cmakedefine WITH_WEBVIEW
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_webview.cpp ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * Popup browser for AAD authentication
4
+ *
5
+ * Copyright 2023 Isaac Klein <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #include <string>
21
+ #include <sstream>
22
+ #include <cstdlib>
23
+ #include <winpr/string.h>
24
+ #include <freerdp/log.h>
25
+ #include <freerdp/utils/aad.h>
26
+
27
+ #include "sdl_webview.hpp"
28
+ #include "webview_impl.hpp"
29
+
30
+ #define TAG CLIENT_TAG("SDL.webview")
31
+
32
+ static std::string from_settings(const rdpSettings* settings, FreeRDP_Settings_Keys_String id)
33
+ {
34
+ auto val = freerdp_settings_get_string(settings, id);
35
+ if (!val)
36
+ {
37
+ WLog_WARN(TAG, "Settings key %s is NULL", freerdp_settings_get_name_for_key(id));
38
+ return "";
39
+ }
40
+ return val;
41
+ }
42
+
43
+ static std::string from_aad_wellknown(rdpContext* context, AAD_WELLKNOWN_VALUES which)
44
+ {
45
+ auto val = freerdp_utils_aad_get_wellknown_string(context, which);
46
+
47
+ if (!val)
48
+ {
49
+ WLog_WARN(TAG, "[wellknown] key %s is NULL", freerdp_utils_aad_wellknwon_value_name(which));
50
+ return "";
51
+ }
52
+ return val;
53
+ }
54
+
55
+ static BOOL sdl_webview_get_rdsaad_access_token(freerdp* instance, const char* scope,
56
+ const char* req_cnf, char** token)
57
+ {
58
+ WINPR_ASSERT(instance);
59
+ WINPR_ASSERT(scope);
60
+ WINPR_ASSERT(req_cnf);
61
+ WINPR_ASSERT(token);
62
+
63
+ WINPR_UNUSED(instance);
64
+ WINPR_UNUSED(instance->context);
65
+
66
+ auto client_id = from_settings(instance->context->settings, FreeRDP_GatewayAvdClientID);
67
+ std::string redirect_uri = "ms-appx-web%3a%2f%2fMicrosoft.AAD.BrokerPlugin%2f" + client_id;
68
+
69
+ *token = nullptr;
70
+
71
+ auto ep = from_aad_wellknown(instance->context, AAD_WELLKNOWN_authorization_endpoint);
72
+ auto url = ep + "?client_id=" + client_id + "&response_type=code&scope=" + scope +
73
+ "&redirect_uri=" + redirect_uri;
74
+
75
+ const std::string title = "FreeRDP WebView - AAD access token";
76
+ std::string code;
77
+ auto rc = webview_impl_run(title, url, code);
78
+ if (!rc || code.empty())
79
+ return FALSE;
80
+
81
+ auto token_request = "grant_type=authorization_code&code=" + code + "&client_id=" + client_id +
82
+ "&scope=" + scope + "&redirect_uri=" + redirect_uri +
83
+ "&req_cnf=" + req_cnf;
84
+ return client_common_get_access_token(instance, token_request.c_str(), token);
85
+ }
86
+
87
+ static BOOL sdl_webview_get_avd_access_token(freerdp* instance, char** token)
88
+ {
89
+ WINPR_ASSERT(token);
90
+ WINPR_ASSERT(instance);
91
+ WINPR_ASSERT(instance->context);
92
+
93
+ auto client_id = from_settings(instance->context->settings, FreeRDP_GatewayAvdClientID);
94
+ std::string redirect_uri = "ms-appx-web%3a%2f%2fMicrosoft.AAD.BrokerPlugin%2f" + client_id;
95
+ std::string scope = "https%3A%2F%2Fwww.wvd.microsoft.com%2F.default";
96
+
97
+ *token = nullptr;
98
+
99
+ auto ep = from_aad_wellknown(instance->context, AAD_WELLKNOWN_authorization_endpoint);
100
+ auto url = ep + "?client_id=" + client_id + "&response_type=code&scope=" + scope +
101
+ "&redirect_uri=" + redirect_uri;
102
+ const std::string title = "FreeRDP WebView - AVD access token";
103
+ std::string code;
104
+ auto rc = webview_impl_run(title, url, code);
105
+ if (!rc || code.empty())
106
+ return FALSE;
107
+
108
+ auto token_request = "grant_type=authorization_code&code=" + code + "&client_id=" + client_id +
109
+ "&scope=" + scope + "&redirect_uri=" + redirect_uri;
110
+ return client_common_get_access_token(instance, token_request.c_str(), token);
111
+ }
112
+
113
+ BOOL sdl_webview_get_access_token(freerdp* instance, AccessTokenType tokenType, char** token,
114
+ size_t count, ...)
115
+ {
116
+ WINPR_ASSERT(instance);
117
+ WINPR_ASSERT(token);
118
+ switch (tokenType)
119
+ {
120
+ case ACCESS_TOKEN_TYPE_AAD:
121
+ {
122
+ if (count < 2)
123
+ {
124
+ WLog_ERR(TAG,
125
+ "ACCESS_TOKEN_TYPE_AAD expected 2 additional arguments, but got %" PRIuz
126
+ ", aborting",
127
+ count);
128
+ return FALSE;
129
+ }
130
+ else if (count > 2)
131
+ WLog_WARN(TAG,
132
+ "ACCESS_TOKEN_TYPE_AAD expected 2 additional arguments, but got %" PRIuz
133
+ ", ignoring",
134
+ count);
135
+ va_list ap = {};
136
+ va_start(ap, count);
137
+ const char* scope = va_arg(ap, const char*);
138
+ const char* req_cnf = va_arg(ap, const char*);
139
+ const BOOL rc = sdl_webview_get_rdsaad_access_token(instance, scope, req_cnf, token);
140
+ va_end(ap);
141
+ return rc;
142
+ }
143
+ case ACCESS_TOKEN_TYPE_AVD:
144
+ if (count != 0)
145
+ WLog_WARN(TAG,
146
+ "ACCESS_TOKEN_TYPE_AVD expected 0 additional arguments, but got %" PRIuz
147
+ ", ignoring",
148
+ count);
149
+ return sdl_webview_get_avd_access_token(instance, token);
150
+ default:
151
+ WLog_ERR(TAG, "Unexpected value for AccessTokenType [%" PRIuz "], aborting", tokenType);
152
+ return FALSE;
153
+ }
154
+ }
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/sdl_webview.hpp ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * Popup browser for AAD authentication
4
+ *
5
+ * Copyright 2023 Isaac Klein <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <freerdp/freerdp.h>
23
+
24
+ #include <sdl_config.hpp>
25
+
26
+ #if defined(WITH_WEBVIEW)
27
+ #ifdef __cplusplus
28
+ extern "C"
29
+ {
30
+ #endif
31
+
32
+ BOOL sdl_webview_get_access_token(freerdp* instance, AccessTokenType tokenType, char** token,
33
+ size_t count, ...);
34
+
35
+ #ifdef __cplusplus
36
+ }
37
+ #endif
38
+ #endif
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/webview_impl.hpp ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FreeRDP: A Remote Desktop Protocol Implementation
3
+ * Popup browser for AAD authentication
4
+ *
5
+ * Copyright 2023 Isaac Klein <[email protected]>
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include <string>
23
+
24
+ bool webview_impl_run(const std::string& title, const std::string& url, std::string& code);
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/wrapper/README ADDED
@@ -0,0 +1 @@
 
 
1
+ upstream at https://github.com/webview/webview/
local-test-freerdp-delta-01/afc-freerdp/client/SDL/common/aad/wrapper/webview.h ADDED
@@ -0,0 +1,2811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2017 Serge Zaitsev
5
+ * Copyright (c) 2022 Steffen André Langnes
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ * SOFTWARE.
24
+ */
25
+ #ifndef WEBVIEW_H
26
+ #define WEBVIEW_H
27
+
28
+ #ifndef WEBVIEW_API
29
+ #define WEBVIEW_API extern
30
+ #endif
31
+
32
+ #ifndef WEBVIEW_VERSION_MAJOR
33
+ // The current library major version.
34
+ #define WEBVIEW_VERSION_MAJOR 0
35
+ #endif
36
+
37
+ #ifndef WEBVIEW_VERSION_MINOR
38
+ // The current library minor version.
39
+ #define WEBVIEW_VERSION_MINOR 10
40
+ #endif
41
+
42
+ #ifndef WEBVIEW_VERSION_PATCH
43
+ // The current library patch version.
44
+ #define WEBVIEW_VERSION_PATCH 0
45
+ #endif
46
+
47
+ #ifndef WEBVIEW_VERSION_PRE_RELEASE
48
+ // SemVer 2.0.0 pre-release labels prefixed with "-".
49
+ #define WEBVIEW_VERSION_PRE_RELEASE ""
50
+ #endif
51
+
52
+ #ifndef WEBVIEW_VERSION_BUILD_METADATA
53
+ // SemVer 2.0.0 build metadata prefixed with "+".
54
+ #define WEBVIEW_VERSION_BUILD_METADATA ""
55
+ #endif
56
+
57
+ // Utility macro for stringifying a macro argument.
58
+ #define WEBVIEW_STRINGIFY(x) #x
59
+
60
+ // Utility macro for stringifying the result of a macro argument expansion.
61
+ #define WEBVIEW_EXPAND_AND_STRINGIFY(x) WEBVIEW_STRINGIFY(x)
62
+
63
+ // SemVer 2.0.0 version number in MAJOR.MINOR.PATCH format.
64
+ #define WEBVIEW_VERSION_NUMBER \
65
+ WEBVIEW_EXPAND_AND_STRINGIFY(WEBVIEW_VERSION_MAJOR) \
66
+ "." WEBVIEW_EXPAND_AND_STRINGIFY(WEBVIEW_VERSION_MINOR) "." WEBVIEW_EXPAND_AND_STRINGIFY( \
67
+ WEBVIEW_VERSION_PATCH)
68
+
69
+ // Holds the elements of a MAJOR.MINOR.PATCH version number.
70
+ typedef struct
71
+ {
72
+ // Major version.
73
+ unsigned int major;
74
+ // Minor version.
75
+ unsigned int minor;
76
+ // Patch version.
77
+ unsigned int patch;
78
+ } webview_version_t;
79
+
80
+ // Holds the library's version information.
81
+ typedef struct
82
+ {
83
+ // The elements of the version number.
84
+ webview_version_t version;
85
+ // SemVer 2.0.0 version number in MAJOR.MINOR.PATCH format.
86
+ char version_number[32];
87
+ // SemVer 2.0.0 pre-release labels prefixed with "-" if specified, otherwise
88
+ // an empty string.
89
+ char pre_release[48];
90
+ // SemVer 2.0.0 build metadata prefixed with "+", otherwise an empty string.
91
+ char build_metadata[48];
92
+ } webview_version_info_t;
93
+
94
+ #ifdef __cplusplus
95
+ extern "C"
96
+ {
97
+ #endif
98
+
99
+ typedef void* webview_t;
100
+
101
+ // Creates a new webview instance. If debug is non-zero - developer tools will
102
+ // be enabled (if the platform supports them). Window parameter can be a
103
+ // pointer to the native window handle. If it's non-null - then child WebView
104
+ // is embedded into the given parent window. Otherwise a new window is created.
105
+ // Depending on the platform, a GtkWindow, NSWindow or HWND pointer can be
106
+ // passed here. Returns null on failure. Creation can fail for various reasons
107
+ // such as when required runtime dependencies are missing or when window creation
108
+ // fails.
109
+ WEBVIEW_API webview_t webview_create(int debug, void* window);
110
+
111
+ // Destroys a webview and closes the native window.
112
+ WEBVIEW_API void webview_destroy(webview_t w);
113
+
114
+ // Runs the main loop until it's terminated. After this function exits - you
115
+ // must destroy the webview.
116
+ WEBVIEW_API void webview_run(webview_t w);
117
+
118
+ // Stops the main loop. It is safe to call this function from another other
119
+ // background thread.
120
+ WEBVIEW_API void webview_terminate(webview_t w);
121
+
122
+ // Posts a function to be executed on the main thread. You normally do not need
123
+ // to call this function, unless you want to tweak the native window.
124
+ WEBVIEW_API void webview_dispatch(webview_t w, void (*fn)(webview_t w, void* arg), void* arg);
125
+
126
+ // Returns a native window handle pointer. When using GTK backend the pointer
127
+ // is GtkWindow pointer, when using Cocoa backend the pointer is NSWindow
128
+ // pointer, when using Win32 backend the pointer is HWND pointer.
129
+ WEBVIEW_API void* webview_get_window(webview_t w);
130
+
131
+ // Updates the title of the native window. Must be called from the UI thread.
132
+ WEBVIEW_API void webview_set_title(webview_t w, const char* title);
133
+
134
+ // Window size hints
135
+ #define WEBVIEW_HINT_NONE 0 // Width and height are default size
136
+ #define WEBVIEW_HINT_MIN 1 // Width and height are minimum bounds
137
+ #define WEBVIEW_HINT_MAX 2 // Width and height are maximum bounds
138
+ #define WEBVIEW_HINT_FIXED 3 // Window size can not be changed by a user
139
+ // Updates native window size. See WEBVIEW_HINT constants.
140
+ WEBVIEW_API void webview_set_size(webview_t w, int width, int height, int hints);
141
+
142
+ // Navigates webview to the given URL. URL may be a properly encoded data URI.
143
+ // Examples:
144
+ // webview_navigate(w, "https://github.com/webview/webview");
145
+ // webview_navigate(w, "data:text/html,%3Ch1%3EHello%3C%2Fh1%3E");
146
+ // webview_navigate(w, "data:text/html;base64,PGgxPkhlbGxvPC9oMT4=");
147
+ WEBVIEW_API void webview_navigate(webview_t w, const char* url);
148
+
149
+ // Set webview HTML directly.
150
+ // Example: webview_set_html(w, "<h1>Hello</h1>");
151
+ WEBVIEW_API void webview_set_html(webview_t w, const char* html);
152
+
153
+ // Injects JavaScript code at the initialization of the new page. Every time
154
+ // the webview will open a the new page - this initialization code will be
155
+ // executed. It is guaranteed that code is executed before window.onload.
156
+ WEBVIEW_API void webview_init(webview_t w, const char* js);
157
+
158
+ // Evaluates arbitrary JavaScript code. Evaluation happens asynchronously, also
159
+ // the result of the expression is ignored. Use RPC bindings if you want to
160
+ // receive notifications about the results of the evaluation.
161
+ WEBVIEW_API void webview_eval(webview_t w, const char* js);
162
+
163
+ // Binds a native C callback so that it will appear under the given name as a
164
+ // global JavaScript function. Internally it uses webview_init(). Callback
165
+ // receives a request string and a user-provided argument pointer. Request
166
+ // string is a JSON array of all the arguments passed to the JavaScript
167
+ // function.
168
+ WEBVIEW_API void webview_bind(webview_t w, const char* name,
169
+ void (*fn)(const char* seq, const char* req, void* arg),
170
+ void* arg);
171
+
172
+ // Removes a native C callback that was previously set by webview_bind.
173
+ WEBVIEW_API void webview_unbind(webview_t w, const char* name);
174
+
175
+ // Allows to return a value from the native binding. Original request pointer
176
+ // must be provided to help internal RPC engine match requests with responses.
177
+ // If status is zero - result is expected to be a valid JSON result value.
178
+ // If status is not zero - result is an error JSON object.
179
+ WEBVIEW_API void webview_return(webview_t w, const char* seq, int status, const char* result);
180
+
181
+ // Get the library's version information.
182
+ // @since 0.10
183
+ WEBVIEW_API const webview_version_info_t* webview_version();
184
+
185
+ #ifdef __cplusplus
186
+ }
187
+
188
+ #ifndef WEBVIEW_HEADER
189
+
190
+ #if !defined(WEBVIEW_GTK) && !defined(WEBVIEW_COCOA) && !defined(WEBVIEW_EDGE)
191
+ #if defined(__APPLE__)
192
+ #define WEBVIEW_COCOA
193
+ #elif defined(__unix__)
194
+ #define WEBVIEW_GTK
195
+ #elif defined(_WIN32)
196
+ #define WEBVIEW_EDGE
197
+ #else
198
+ #error "please, specify webview backend"
199
+ #endif
200
+ #endif
201
+
202
+ #ifndef WEBVIEW_DEPRECATED
203
+ #if __cplusplus >= 201402L
204
+ #define WEBVIEW_DEPRECATED(reason) [[deprecated(reason)]]
205
+ #elif defined(_MSC_VER)
206
+ #define WEBVIEW_DEPRECATED(reason) __declspec(deprecated(reason))
207
+ #else
208
+ #define WEBVIEW_DEPRECATED(reason) __attribute__((deprecated(reason)))
209
+ #endif
210
+ #endif
211
+
212
+ #ifndef WEBVIEW_DEPRECATED_PRIVATE
213
+ #define WEBVIEW_DEPRECATED_PRIVATE WEBVIEW_DEPRECATED("Private API should not be used")
214
+ #endif
215
+
216
+ #include <array>
217
+ #include <atomic>
218
+ #include <functional>
219
+ #include <future>
220
+ #include <map>
221
+ #include <string>
222
+ #include <utility>
223
+ #include <vector>
224
+ #include <locale>
225
+ #include <codecvt>
226
+ #include <cstring>
227
+
228
+ namespace webview
229
+ {
230
+
231
+ using dispatch_fn_t = std::function<void()>;
232
+
233
+ namespace detail
234
+ {
235
+
236
+ // The library's version information.
237
+ constexpr const webview_version_info_t library_version_info{
238
+ { WEBVIEW_VERSION_MAJOR, WEBVIEW_VERSION_MINOR, WEBVIEW_VERSION_PATCH },
239
+ WEBVIEW_VERSION_NUMBER,
240
+ WEBVIEW_VERSION_PRE_RELEASE,
241
+ WEBVIEW_VERSION_BUILD_METADATA
242
+ };
243
+
244
+ inline int json_parse_c(const char* s, size_t sz, const char* key, size_t keysz,
245
+ const char** value, size_t* valuesz)
246
+ {
247
+ enum
248
+ {
249
+ JSON_STATE_VALUE,
250
+ JSON_STATE_LITERAL,
251
+ JSON_STATE_STRING,
252
+ JSON_STATE_ESCAPE,
253
+ JSON_STATE_UTF8
254
+ } state = JSON_STATE_VALUE;
255
+ const char* k = nullptr;
256
+ int index = 1;
257
+ int depth = 0;
258
+ int utf8_bytes = 0;
259
+
260
+ *value = nullptr;
261
+ *valuesz = 0;
262
+
263
+ if (key == nullptr)
264
+ {
265
+ index = static_cast<decltype(index)>(keysz);
266
+ if (index < 0)
267
+ {
268
+ return -1;
269
+ }
270
+ keysz = 0;
271
+ }
272
+
273
+ for (; sz > 0; s++, sz--)
274
+ {
275
+ enum
276
+ {
277
+ JSON_ACTION_NONE,
278
+ JSON_ACTION_START,
279
+ JSON_ACTION_END,
280
+ JSON_ACTION_START_STRUCT,
281
+ JSON_ACTION_END_STRUCT
282
+ } action = JSON_ACTION_NONE;
283
+ auto c = static_cast<unsigned char>(*s);
284
+ switch (state)
285
+ {
286
+ case JSON_STATE_VALUE:
287
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' || c == ':')
288
+ {
289
+ continue;
290
+ }
291
+ else if (c == '"')
292
+ {
293
+ action = JSON_ACTION_START;
294
+ state = JSON_STATE_STRING;
295
+ }
296
+ else if (c == '{' || c == '[')
297
+ {
298
+ action = JSON_ACTION_START_STRUCT;
299
+ }
300
+ else if (c == '}' || c == ']')
301
+ {
302
+ action = JSON_ACTION_END_STRUCT;
303
+ }
304
+ else if (c == 't' || c == 'f' || c == 'n' || c == '-' ||
305
+ (c >= '0' && c <= '9'))
306
+ {
307
+ action = JSON_ACTION_START;
308
+ state = JSON_STATE_LITERAL;
309
+ }
310
+ else
311
+ {
312
+ return -1;
313
+ }
314
+ break;
315
+ case JSON_STATE_LITERAL:
316
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' ||
317
+ c == ']' || c == '}' || c == ':')
318
+ {
319
+ state = JSON_STATE_VALUE;
320
+ s--;
321
+ sz++;
322
+ action = JSON_ACTION_END;
323
+ }
324
+ else if (c < 32 || c > 126)
325
+ {
326
+ return -1;
327
+ } // fallthrough
328
+ case JSON_STATE_STRING:
329
+ if (c < 32 || (c > 126 && c < 192))
330
+ {
331
+ return -1;
332
+ }
333
+ else if (c == '"')
334
+ {
335
+ action = JSON_ACTION_END;
336
+ state = JSON_STATE_VALUE;
337
+ }
338
+ else if (c == '\\')
339
+ {
340
+ state = JSON_STATE_ESCAPE;
341
+ }
342
+ else if (c >= 192 && c < 224)
343
+ {
344
+ utf8_bytes = 1;
345
+ state = JSON_STATE_UTF8;
346
+ }
347
+ else if (c >= 224 && c < 240)
348
+ {
349
+ utf8_bytes = 2;
350
+ state = JSON_STATE_UTF8;
351
+ }
352
+ else if (c >= 240 && c < 247)
353
+ {
354
+ utf8_bytes = 3;
355
+ state = JSON_STATE_UTF8;
356
+ }
357
+ else if (c >= 128 && c < 192)
358
+ {
359
+ return -1;
360
+ }
361
+ break;
362
+ case JSON_STATE_ESCAPE:
363
+ if (c == '"' || c == '\\' || c == '/' || c == 'b' || c == 'f' || c == 'n' ||
364
+ c == 'r' || c == 't' || c == 'u')
365
+ {
366
+ state = JSON_STATE_STRING;
367
+ }
368
+ else
369
+ {
370
+ return -1;
371
+ }
372
+ break;
373
+ case JSON_STATE_UTF8:
374
+ if (c < 128 || c > 191)
375
+ {
376
+ return -1;
377
+ }
378
+ utf8_bytes--;
379
+ if (utf8_bytes == 0)
380
+ {
381
+ state = JSON_STATE_STRING;
382
+ }
383
+ break;
384
+ default:
385
+ return -1;
386
+ }
387
+
388
+ if (action == JSON_ACTION_END_STRUCT)
389
+ {
390
+ depth--;
391
+ }
392
+
393
+ if (depth == 1)
394
+ {
395
+ if (action == JSON_ACTION_START || action == JSON_ACTION_START_STRUCT)
396
+ {
397
+ if (index == 0)
398
+ {
399
+ *value = s;
400
+ }
401
+ else if (keysz > 0 && index == 1)
402
+ {
403
+ k = s;
404
+ }
405
+ else
406
+ {
407
+ index--;
408
+ }
409
+ }
410
+ else if (action == JSON_ACTION_END || action == JSON_ACTION_END_STRUCT)
411
+ {
412
+ if (*value != nullptr && index == 0)
413
+ {
414
+ *valuesz = (size_t)(s + 1 - *value);
415
+ return 0;
416
+ }
417
+ else if (keysz > 0 && k != nullptr)
418
+ {
419
+ if (keysz == (size_t)(s - k - 1) && memcmp(key, k + 1, keysz) == 0)
420
+ {
421
+ index = 0;
422
+ }
423
+ else
424
+ {
425
+ index = 2;
426
+ }
427
+ k = nullptr;
428
+ }
429
+ }
430
+ }
431
+
432
+ if (action == JSON_ACTION_START_STRUCT)
433
+ {
434
+ depth++;
435
+ }
436
+ }
437
+ return -1;
438
+ }
439
+
440
+ inline std::string json_escape(const std::string& s)
441
+ {
442
+ // TODO: implement
443
+ return '"' + s + '"';
444
+ }
445
+
446
+ inline int json_unescape(const char* s, size_t n, char* out)
447
+ {
448
+ int r = 0;
449
+ if (*s++ != '"')
450
+ {
451
+ return -1;
452
+ }
453
+ while (n > 2)
454
+ {
455
+ char c = *s;
456
+ if (c == '\\')
457
+ {
458
+ s++;
459
+ n--;
460
+ switch (*s)
461
+ {
462
+ case 'b':
463
+ c = '\b';
464
+ break;
465
+ case 'f':
466
+ c = '\f';
467
+ break;
468
+ case 'n':
469
+ c = '\n';
470
+ break;
471
+ case 'r':
472
+ c = '\r';
473
+ break;
474
+ case 't':
475
+ c = '\t';
476
+ break;
477
+ case '\\':
478
+ c = '\\';
479
+ break;
480
+ case '/':
481
+ c = '/';
482
+ break;
483
+ case '\"':
484
+ c = '\"';
485
+ break;
486
+ default: // TODO: support unicode decoding
487
+ return -1;
488
+ }
489
+ }
490
+ if (out != nullptr)
491
+ {
492
+ *out++ = c;
493
+ }
494
+ s++;
495
+ n--;
496
+ r++;
497
+ }
498
+ if (*s != '"')
499
+ {
500
+ return -1;
501
+ }
502
+ if (out != nullptr)
503
+ {
504
+ *out = '\0';
505
+ }
506
+ return r;
507
+ }
508
+
509
+ inline std::string json_parse(const std::string& s, const std::string& key, const int index)
510
+ {
511
+ const char* value = nullptr;
512
+ size_t value_sz = 0;
513
+ if (key.empty())
514
+ {
515
+ json_parse_c(s.c_str(), s.length(), nullptr, index, &value, &value_sz);
516
+ }
517
+ else
518
+ {
519
+ json_parse_c(s.c_str(), s.length(), key.c_str(), key.length(), &value, &value_sz);
520
+ }
521
+ if (value != nullptr)
522
+ {
523
+ if (value[0] != '"')
524
+ {
525
+ return { value, value_sz };
526
+ }
527
+ int n = json_unescape(value, value_sz, nullptr);
528
+ if (n > 0)
529
+ {
530
+ char* decoded = new char[1ull + n];
531
+ json_unescape(value, value_sz, decoded);
532
+ std::string result(decoded, n);
533
+ delete[] decoded;
534
+ return result;
535
+ }
536
+ }
537
+ return "";
538
+ }
539
+
540
+ } // namespace detail
541
+
542
+ WEBVIEW_DEPRECATED_PRIVATE
543
+ inline int json_parse_c(const char* s, size_t sz, const char* key, size_t keysz,
544
+ const char** value, size_t* valuesz)
545
+ {
546
+ return detail::json_parse_c(s, sz, key, keysz, value, valuesz);
547
+ }
548
+
549
+ WEBVIEW_DEPRECATED_PRIVATE
550
+ inline std::string json_escape(const std::string& s)
551
+ {
552
+ return detail::json_escape(s);
553
+ }
554
+
555
+ WEBVIEW_DEPRECATED_PRIVATE
556
+ inline int json_unescape(const char* s, size_t n, char* out)
557
+ {
558
+ return detail::json_unescape(s, n, out);
559
+ }
560
+
561
+ WEBVIEW_DEPRECATED_PRIVATE
562
+ inline std::string json_parse(const std::string& s, const std::string& key, const int index)
563
+ {
564
+ return detail::json_parse(s, key, index);
565
+ }
566
+
567
+ } // namespace webview
568
+
569
+ #if defined(WEBVIEW_GTK)
570
+ //
571
+ // ====================================================================
572
+ //
573
+ // This implementation uses webkit2gtk backend. It requires gtk+3.0 and
574
+ // webkit2gtk-4.0 libraries. Proper compiler flags can be retrieved via:
575
+ //
576
+ // pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0
577
+ //
578
+ // ====================================================================
579
+ //
580
+ #include <JavaScriptCore/JavaScript.h>
581
+ #include <gtk/gtk.h>
582
+ #include <webkit2/webkit2.h>
583
+
584
+ namespace webview
585
+ {
586
+ namespace detail
587
+ {
588
+
589
+ class gtk_webkit_engine
590
+ {
591
+ public:
592
+ gtk_webkit_engine(bool debug, void* window) : m_window(static_cast<GtkWidget*>(window))
593
+ {
594
+ if (gtk_init_check(nullptr, nullptr) == FALSE)
595
+ {
596
+ return;
597
+ }
598
+ m_window = static_cast<GtkWidget*>(window);
599
+ if (m_window == nullptr)
600
+ {
601
+ m_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
602
+ }
603
+ g_signal_connect(G_OBJECT(m_window), "destroy",
604
+ G_CALLBACK(+[](GtkWidget*, gpointer arg)
605
+ { static_cast<gtk_webkit_engine*>(arg)->terminate(); }),
606
+ this);
607
+ // Initialize webview widget
608
+ m_webview = webkit_web_view_new();
609
+ WebKitUserContentManager* manager =
610
+ webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview));
611
+ g_signal_connect(manager, "script-message-received::external",
612
+ G_CALLBACK(+[](WebKitUserContentManager*,
613
+ WebKitJavascriptResult* r, gpointer arg)
614
+ {
615
+ auto* w = static_cast<gtk_webkit_engine*>(arg);
616
+ char* s = get_string_from_js_result(r);
617
+ w->on_message(s);
618
+ g_free(s);
619
+ }),
620
+ this);
621
+ webkit_user_content_manager_register_script_message_handler(manager, "external");
622
+ init("window.external={invoke:function(s){window.webkit.messageHandlers."
623
+ "external.postMessage(s);}}");
624
+
625
+ gtk_container_add(GTK_CONTAINER(m_window), GTK_WIDGET(m_webview));
626
+ gtk_widget_grab_focus(GTK_WIDGET(m_webview));
627
+
628
+ WebKitSettings* settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(m_webview));
629
+ webkit_settings_set_javascript_can_access_clipboard(settings, true);
630
+ if (debug)
631
+ {
632
+ webkit_settings_set_enable_write_console_messages_to_stdout(settings, true);
633
+ webkit_settings_set_enable_developer_extras(settings, true);
634
+ }
635
+
636
+ gtk_widget_show_all(m_window);
637
+ }
638
+ virtual ~gtk_webkit_engine() = default;
639
+ void* window()
640
+ {
641
+ return (void*)m_window;
642
+ }
643
+ void run()
644
+ {
645
+ gtk_main();
646
+ }
647
+ void terminate()
648
+ {
649
+ gtk_main_quit();
650
+ }
651
+ void dispatch(std::function<void()> f)
652
+ {
653
+ g_idle_add_full(G_PRIORITY_HIGH_IDLE, (GSourceFunc)([](void* f) -> int {
654
+ (*static_cast<dispatch_fn_t*>(f))();
655
+ return G_SOURCE_REMOVE;
656
+ }),
657
+ new std::function<void()>(f),
658
+ [](void* f) { delete static_cast<dispatch_fn_t*>(f); });
659
+ }
660
+
661
+ void set_title(const std::string& title)
662
+ {
663
+ gtk_window_set_title(GTK_WINDOW(m_window), title.c_str());
664
+ }
665
+
666
+ void set_size(int width, int height, int hints)
667
+ {
668
+ gtk_window_set_resizable(GTK_WINDOW(m_window), hints != WEBVIEW_HINT_FIXED);
669
+ if (hints == WEBVIEW_HINT_NONE)
670
+ {
671
+ gtk_window_resize(GTK_WINDOW(m_window), width, height);
672
+ }
673
+ else if (hints == WEBVIEW_HINT_FIXED)
674
+ {
675
+ gtk_widget_set_size_request(m_window, width, height);
676
+ }
677
+ else
678
+ {
679
+ GdkGeometry g;
680
+ g.min_width = g.max_width = width;
681
+ g.min_height = g.max_height = height;
682
+ GdkWindowHints h =
683
+ (hints == WEBVIEW_HINT_MIN ? GDK_HINT_MIN_SIZE : GDK_HINT_MAX_SIZE);
684
+ // This defines either MIN_SIZE, or MAX_SIZE, but not both:
685
+ gtk_window_set_geometry_hints(GTK_WINDOW(m_window), nullptr, &g, h);
686
+ }
687
+ }
688
+
689
+ void navigate(const std::string& url)
690
+ {
691
+ webkit_web_view_load_uri(WEBKIT_WEB_VIEW(m_webview), url.c_str());
692
+ }
693
+
694
+ void add_navigate_listener(std::function<void(const std::string&, void*)> callback,
695
+ void* arg)
696
+ {
697
+ g_signal_connect(WEBKIT_WEB_VIEW(m_webview), "load-changed",
698
+ G_CALLBACK(on_load_changed), this);
699
+ navigateCallbackArg = arg;
700
+ navigateCallback = std::move(callback);
701
+ }
702
+
703
+ void add_scheme_handler(const std::string& scheme,
704
+ std::function<void(const std::string&, void*)> callback,
705
+ void* arg)
706
+ {
707
+ auto view = WEBKIT_WEB_VIEW(m_webview);
708
+ auto context = webkit_web_view_get_context(view);
709
+
710
+ scheme_handlers.insert({ scheme, { .arg = arg, .fkt = callback } });
711
+ webkit_web_context_register_uri_scheme(context, scheme.c_str(), scheme_handler,
712
+ static_cast<gpointer>(this), nullptr);
713
+ }
714
+
715
+ void set_html(const std::string& html)
716
+ {
717
+ webkit_web_view_load_html(WEBKIT_WEB_VIEW(m_webview), html.c_str(), nullptr);
718
+ }
719
+
720
+ void init(const std::string& js)
721
+ {
722
+ WebKitUserContentManager* manager =
723
+ webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(m_webview));
724
+ webkit_user_content_manager_add_script(
725
+ manager, webkit_user_script_new(
726
+ js.c_str(), WEBKIT_USER_CONTENT_INJECT_TOP_FRAME,
727
+ WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, nullptr, nullptr));
728
+ }
729
+
730
+ void eval(const std::string& js)
731
+ {
732
+ webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(m_webview), js.c_str(), nullptr,
733
+ nullptr, nullptr);
734
+ }
735
+
736
+ private:
737
+ virtual void on_message(const std::string& msg) = 0;
738
+
739
+ struct handler_t
740
+ {
741
+ void* arg;
742
+ std::function<void(const std::string&, void*)> fkt;
743
+ };
744
+
745
+ std::map<std::string, handler_t> scheme_handlers;
746
+
747
+ void scheme_handler_call(const std::string& scheme, const std::string& url)
748
+ {
749
+ auto handler = scheme_handlers.find(scheme);
750
+ if (handler != scheme_handlers.end())
751
+ {
752
+ const auto& arg = handler->second;
753
+ arg.fkt(url, arg.arg);
754
+ }
755
+ }
756
+
757
+ static void scheme_handler(WebKitURISchemeRequest* request, gpointer user_data)
758
+ {
759
+ auto _this = static_cast<gtk_webkit_engine*>(user_data);
760
+
761
+ auto scheme = webkit_uri_scheme_request_get_scheme(request);
762
+ auto uri = webkit_uri_scheme_request_get_uri(request);
763
+ _this->scheme_handler_call(scheme, uri);
764
+ }
765
+
766
+ static char* get_string_from_js_result(WebKitJavascriptResult* r)
767
+ {
768
+ char* s = nullptr;
769
+ #if WEBKIT_MAJOR_VERSION >= 2 && WEBKIT_MINOR_VERSION >= 22
770
+ JSCValue* value = webkit_javascript_result_get_js_value(r);
771
+ s = jsc_value_to_string(value);
772
+ #else
773
+ JSGlobalContextRef ctx = webkit_javascript_result_get_global_context(r);
774
+ JSValueRef value = webkit_javascript_result_get_value(r);
775
+ JSStringRef js = JSValueToStringCopy(ctx, value, nullptr);
776
+ size_t n = JSStringGetMaximumUTF8CStringSize(js);
777
+ s = g_new(char, n);
778
+ JSStringGetUTF8CString(js, s, n);
779
+ JSStringRelease(js);
780
+ #endif
781
+ return s;
782
+ }
783
+
784
+ GtkWidget* m_window;
785
+ GtkWidget* m_webview;
786
+
787
+ void* navigateCallbackArg = nullptr;
788
+ std::function<void(const std::string&, void*)> navigateCallback = nullptr;
789
+
790
+ static void on_load_changed(WebKitWebView* web_view, WebKitLoadEvent load_event,
791
+ gpointer arg)
792
+ {
793
+ if (load_event == WEBKIT_LOAD_FINISHED)
794
+ {
795
+ auto inst = static_cast<gtk_webkit_engine*>(arg);
796
+ inst->navigateCallback(webkit_web_view_get_uri(web_view),
797
+ inst->navigateCallbackArg);
798
+ }
799
+ }
800
+ };
801
+
802
+ } // namespace detail
803
+
804
+ using browser_engine = detail::gtk_webkit_engine;
805
+
806
+ } // namespace webview
807
+
808
+ #elif defined(WEBVIEW_COCOA)
809
+
810
+ //
811
+ // ====================================================================
812
+ //
813
+ // This implementation uses Cocoa WKWebView backend on macOS. It is
814
+ // written using ObjC runtime and uses WKWebView class as a browser runtime.
815
+ // You should pass "-framework Webkit" flag to the compiler.
816
+ //
817
+ // ====================================================================
818
+ //
819
+
820
+ #include <CoreGraphics/CoreGraphics.h>
821
+ #include <objc/NSObjCRuntime.h>
822
+ #include <objc/objc-runtime.h>
823
+
824
+ namespace webview
825
+ {
826
+ namespace detail
827
+ {
828
+ namespace objc
829
+ {
830
+
831
+ // A convenient template function for unconditionally casting the specified
832
+ // C-like function into a function that can be called with the given return
833
+ // type and arguments. Caller takes full responsibility for ensuring that
834
+ // the function call is valid. It is assumed that the function will not
835
+ // throw exceptions.
836
+ template <typename Result, typename Callable, typename... Args>
837
+ Result invoke(Callable callable, Args... args) noexcept
838
+ {
839
+ return reinterpret_cast<Result (*)(Args...)>(callable)(args...);
840
+ }
841
+
842
+ // Calls objc_msgSend.
843
+ template <typename Result, typename... Args> Result msg_send(Args... args) noexcept
844
+ {
845
+ return invoke<Result>(objc_msgSend, args...);
846
+ }
847
+
848
+ } // namespace objc
849
+
850
+ enum NSBackingStoreType : NSUInteger
851
+ {
852
+ NSBackingStoreBuffered = 2
853
+ };
854
+
855
+ enum NSWindowStyleMask : NSUInteger
856
+ {
857
+ NSWindowStyleMaskTitled = 1,
858
+ NSWindowStyleMaskClosable = 2,
859
+ NSWindowStyleMaskMiniaturizable = 4,
860
+ NSWindowStyleMaskResizable = 8
861
+ };
862
+
863
+ enum NSApplicationActivationPolicy : NSInteger
864
+ {
865
+ NSApplicationActivationPolicyRegular = 0
866
+ };
867
+
868
+ enum WKUserScriptInjectionTime : NSInteger
869
+ {
870
+ WKUserScriptInjectionTimeAtDocumentStart = 0
871
+ };
872
+
873
+ enum NSModalResponse : NSInteger
874
+ {
875
+ NSModalResponseOK = 1
876
+ };
877
+
878
+ // Convenient conversion of string literals.
879
+ inline id operator"" _cls(const char* s, std::size_t)
880
+ {
881
+ return (id)objc_getClass(s);
882
+ }
883
+ inline SEL operator"" _sel(const char* s, std::size_t)
884
+ {
885
+ return sel_registerName(s);
886
+ }
887
+ inline id operator"" _str(const char* s, std::size_t)
888
+ {
889
+ return objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, s);
890
+ }
891
+
892
+ class cocoa_wkwebview_engine
893
+ {
894
+ public:
895
+ cocoa_wkwebview_engine(bool debug, void* window)
896
+ : m_debug{ debug }, m_parent_window{ window }
897
+ {
898
+ auto app = get_shared_application();
899
+ auto delegate = create_app_delegate();
900
+ objc_setAssociatedObject(delegate, "webview", (id)this, OBJC_ASSOCIATION_ASSIGN);
901
+ objc::msg_send<void>(app, "setDelegate:"_sel, delegate);
902
+
903
+ // See comments related to application lifecycle in create_app_delegate().
904
+ if (window)
905
+ {
906
+ on_application_did_finish_launching(delegate, app);
907
+ }
908
+ else
909
+ {
910
+ // Start the main run loop so that the app delegate gets the
911
+ // NSApplicationDidFinishLaunchingNotification notification after the run
912
+ // loop has started in order to perform further initialization.
913
+ // We need to return from this constructor so this run loop is only
914
+ // temporary.
915
+ objc::msg_send<void>(app, "run"_sel);
916
+ }
917
+ }
918
+ virtual ~cocoa_wkwebview_engine() = default;
919
+ void* window()
920
+ {
921
+ return (void*)m_window;
922
+ }
923
+ void terminate()
924
+ {
925
+ auto app = get_shared_application();
926
+ objc::msg_send<void>(app, "terminate:"_sel, nullptr);
927
+ }
928
+ void run()
929
+ {
930
+ auto app = get_shared_application();
931
+ objc::msg_send<void>(app, "run"_sel);
932
+ }
933
+ void dispatch(std::function<void()> f)
934
+ {
935
+ dispatch_async_f(dispatch_get_main_queue(), new dispatch_fn_t(f),
936
+ (dispatch_function_t)([](void* arg) {
937
+ auto f = static_cast<dispatch_fn_t*>(arg);
938
+ (*f)();
939
+ delete f;
940
+ }));
941
+ }
942
+ void set_title(const std::string& title)
943
+ {
944
+ objc::msg_send<void>(
945
+ m_window, "setTitle:"_sel,
946
+ objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, title.c_str()));
947
+ }
948
+ void set_size(int width, int height, int hints)
949
+ {
950
+ auto style = static_cast<NSWindowStyleMask>(NSWindowStyleMaskTitled |
951
+ NSWindowStyleMaskClosable |
952
+ NSWindowStyleMaskMiniaturizable);
953
+ if (hints != WEBVIEW_HINT_FIXED)
954
+ {
955
+ style = static_cast<NSWindowStyleMask>(style | NSWindowStyleMaskResizable);
956
+ }
957
+ objc::msg_send<void>(m_window, "setStyleMask:"_sel, style);
958
+
959
+ if (hints == WEBVIEW_HINT_MIN)
960
+ {
961
+ objc::msg_send<void>(m_window, "setContentMinSize:"_sel,
962
+ CGSizeMake(width, height));
963
+ }
964
+ else if (hints == WEBVIEW_HINT_MAX)
965
+ {
966
+ objc::msg_send<void>(m_window, "setContentMaxSize:"_sel,
967
+ CGSizeMake(width, height));
968
+ }
969
+ else
970
+ {
971
+ objc::msg_send<void>(m_window, "setFrame:display:animate:"_sel,
972
+ CGRectMake(0, 0, width, height), YES, NO);
973
+ }
974
+ objc::msg_send<void>(m_window, "center"_sel);
975
+ }
976
+ void navigate(const std::string& url)
977
+ {
978
+ auto nsurl = objc::msg_send<id>(
979
+ "NSURL"_cls, "URLWithString:"_sel,
980
+ objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, url.c_str()));
981
+
982
+ objc::msg_send<void>(
983
+ m_webview, "loadRequest:"_sel,
984
+ objc::msg_send<id>("NSURLRequest"_cls, "requestWithURL:"_sel, nsurl));
985
+ }
986
+
987
+ void add_navigate_listener(std::function<void(const std::string&, void*)> callback,
988
+ void* arg)
989
+ {
990
+ m_navigateCallback = callback;
991
+ m_navigateCallbackArg = arg;
992
+ }
993
+
994
+ void add_scheme_handler(const std::string& scheme,
995
+ std::function<void(const std::string&, void*)> callback,
996
+ void* arg)
997
+ {
998
+ // TODO: Implement
999
+ }
1000
+
1001
+ void set_html(const std::string& html)
1002
+ {
1003
+ objc::msg_send<void>(
1004
+ m_webview, "loadHTMLString:baseURL:"_sel,
1005
+ objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, html.c_str()),
1006
+ nullptr);
1007
+ }
1008
+ void init(const std::string& js)
1009
+ {
1010
+ // Equivalent Obj-C:
1011
+ // [m_manager addUserScript:[[WKUserScript alloc] initWithSource:[NSString
1012
+ // stringWithUTF8String:js.c_str()]
1013
+ // injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]]
1014
+ objc::msg_send<void>(
1015
+ m_manager, "addUserScript:"_sel,
1016
+ objc::msg_send<id>(
1017
+ objc::msg_send<id>("WKUserScript"_cls, "alloc"_sel),
1018
+ "initWithSource:injectionTime:forMainFrameOnly:"_sel,
1019
+ objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, js.c_str()),
1020
+ WKUserScriptInjectionTimeAtDocumentStart, YES));
1021
+ }
1022
+ void eval(const std::string& js)
1023
+ {
1024
+ objc::msg_send<void>(
1025
+ m_webview, "evaluateJavaScript:completionHandler:"_sel,
1026
+ objc::msg_send<id>("NSString"_cls, "stringWithUTF8String:"_sel, js.c_str()),
1027
+ nullptr);
1028
+ }
1029
+
1030
+ private:
1031
+ virtual void on_message(const std::string& msg) = 0;
1032
+ id create_app_delegate()
1033
+ {
1034
+ // Note: Avoid registering the class name "AppDelegate" as it is the
1035
+ // default name in projects created with Xcode, and using the same name
1036
+ // causes objc_registerClassPair to crash.
1037
+ auto cls =
1038
+ objc_allocateClassPair((Class) "NSResponder"_cls, "WebviewAppDelegate", 0);
1039
+ class_addProtocol(cls, objc_getProtocol("NSTouchBarProvider"));
1040
+ class_addMethod(cls, "applicationShouldTerminateAfterLastWindowClosed:"_sel,
1041
+ (IMP)(+[](id, SEL, id) -> BOOL { return 1; }), "c@:@");
1042
+ // If the library was not initialized with an existing window then the user
1043
+ // is likely managing the application lifecycle and we would not get the
1044
+ // "applicationDidFinishLaunching:" message and therefore do not need to
1045
+ // add this method.
1046
+ if (!m_parent_window)
1047
+ {
1048
+ class_addMethod(cls, "applicationDidFinishLaunching:"_sel,
1049
+ (IMP)(+[](id self, SEL, id notification)
1050
+ {
1051
+ auto app =
1052
+ objc::msg_send<id>(notification, "object"_sel);
1053
+ auto w = get_associated_webview(self);
1054
+ w->on_application_did_finish_launching(self, app);
1055
+ }),
1056
+ "v@:@");
1057
+ }
1058
+ objc_registerClassPair(cls);
1059
+ return objc::msg_send<id>((id)cls, "new"_sel);
1060
+ }
1061
+ id create_script_message_handler()
1062
+ {
1063
+ auto cls = objc_allocateClassPair((Class) "NSResponder"_cls,
1064
+ "WebkitScriptMessageHandler", 0);
1065
+ class_addProtocol(cls, objc_getProtocol("WKScriptMessageHandler"));
1066
+ class_addMethod(
1067
+ cls, "userContentController:didReceiveScriptMessage:"_sel,
1068
+ (IMP)(+[](id self, SEL, id, id msg)
1069
+ {
1070
+ auto w = get_associated_webview(self);
1071
+ w->on_message(objc::msg_send<const char*>(
1072
+ objc::msg_send<id>(msg, "body"_sel), "UTF8String"_sel));
1073
+ }),
1074
+ "v@:@@");
1075
+ objc_registerClassPair(cls);
1076
+ auto instance = objc::msg_send<id>((id)cls, "new"_sel);
1077
+ objc_setAssociatedObject(instance, "webview", (id)this, OBJC_ASSOCIATION_ASSIGN);
1078
+ return instance;
1079
+ }
1080
+ static id create_webkit_ui_delegate()
1081
+ {
1082
+ auto cls = objc_allocateClassPair((Class) "NSObject"_cls, "WebkitUIDelegate", 0);
1083
+ class_addProtocol(cls, objc_getProtocol("WKUIDelegate"));
1084
+ class_addMethod(
1085
+ cls,
1086
+ "webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:"_sel,
1087
+ (IMP)(+[](id, SEL, id, id parameters, id, id completion_handler)
1088
+ {
1089
+ auto allows_multiple_selection =
1090
+ objc::msg_send<BOOL>(parameters, "allowsMultipleSelection"_sel);
1091
+ auto allows_directories =
1092
+ objc::msg_send<BOOL>(parameters, "allowsDirectories"_sel);
1093
+
1094
+ // Show a panel for selecting files.
1095
+ auto panel = objc::msg_send<id>("NSOpenPanel"_cls, "openPanel"_sel);
1096
+ objc::msg_send<void>(panel, "setCanChooseFiles:"_sel, YES);
1097
+ objc::msg_send<void>(panel, "setCanChooseDirectories:"_sel,
1098
+ allows_directories);
1099
+ objc::msg_send<void>(panel, "setAllowsMultipleSelection:"_sel,
1100
+ allows_multiple_selection);
1101
+ auto modal_response =
1102
+ objc::msg_send<NSModalResponse>(panel, "runModal"_sel);
1103
+
1104
+ // Get the URLs for the selected files. If the modal was canceled
1105
+ // then we pass null to the completion handler to signify
1106
+ // cancellation.
1107
+ id urls = modal_response == NSModalResponseOK
1108
+ ? objc::msg_send<id>(panel, "URLs"_sel)
1109
+ : nullptr;
1110
+
1111
+ // Invoke the completion handler block.
1112
+ auto sig = objc::msg_send<id>("NSMethodSignature"_cls,
1113
+ "signatureWithObjCTypes:"_sel, "v@?@");
1114
+ auto invocation = objc::msg_send<id>(
1115
+ "NSInvocation"_cls, "invocationWithMethodSignature:"_sel, sig);
1116
+ objc::msg_send<void>(invocation, "setTarget:"_sel,
1117
+ completion_handler);
1118
+ objc::msg_send<void>(invocation, "setArgument:atIndex:"_sel, &urls,
1119
+ 1);
1120
+ objc::msg_send<void>(invocation, "invoke"_sel);
1121
+ }),
1122
+ "v@:@@@@");
1123
+ objc_registerClassPair(cls);
1124
+ return objc::msg_send<id>((id)cls, "new"_sel);
1125
+ }
1126
+ id create_webkit_navigation_delegate()
1127
+ {
1128
+ auto cls =
1129
+ objc_allocateClassPair((Class) "NSObject"_cls, "WebkitNavigationDelegate", 0);
1130
+ class_addProtocol(cls, objc_getProtocol("WKNavigationDelegate"));
1131
+ class_addMethod(cls, "webView:didFinishNavigation:"_sel,
1132
+ (IMP)(+[](id delegate, SEL sel, id webview, id navigation)
1133
+ {
1134
+ auto w = get_associated_webview(delegate);
1135
+ auto url = objc::msg_send<id>(webview, "URL"_sel);
1136
+ auto nstr = objc::msg_send<id>(url, "absoluteString"_sel);
1137
+ auto str = objc::msg_send<char*>(nstr, "UTF8String"_sel);
1138
+ w->m_navigateCallback(str, w->m_navigateCallbackArg);
1139
+ }),
1140
+ "v@:@");
1141
+ objc_registerClassPair(cls);
1142
+ auto instance = objc::msg_send<id>((id)cls, "new"_sel);
1143
+ objc_setAssociatedObject(instance, "webview", (id)this, OBJC_ASSOCIATION_ASSIGN);
1144
+ return instance;
1145
+ }
1146
+ static id get_shared_application()
1147
+ {
1148
+ return objc::msg_send<id>("NSApplication"_cls, "sharedApplication"_sel);
1149
+ }
1150
+ static cocoa_wkwebview_engine* get_associated_webview(id object)
1151
+ {
1152
+ auto w = (cocoa_wkwebview_engine*)objc_getAssociatedObject(object, "webview");
1153
+ assert(w);
1154
+ return w;
1155
+ }
1156
+ static id get_main_bundle() noexcept
1157
+ {
1158
+ return objc::msg_send<id>("NSBundle"_cls, "mainBundle"_sel);
1159
+ }
1160
+ static bool is_app_bundled() noexcept
1161
+ {
1162
+ auto bundle = get_main_bundle();
1163
+ if (!bundle)
1164
+ {
1165
+ return false;
1166
+ }
1167
+ auto bundle_path = objc::msg_send<id>(bundle, "bundlePath"_sel);
1168
+ auto bundled = objc::msg_send<BOOL>(bundle_path, "hasSuffix:"_sel, ".app"_str);
1169
+ return !!bundled;
1170
+ }
1171
+ void on_application_did_finish_launching(id /*delegate*/, id app)
1172
+ {
1173
+ // See comments related to application lifecycle in create_app_delegate().
1174
+ if (!m_parent_window)
1175
+ {
1176
+ // Stop the main run loop so that we can return
1177
+ // from the constructor.
1178
+ objc::msg_send<void>(app, "stop:"_sel, nullptr);
1179
+ }
1180
+
1181
+ // Activate the app if it is not bundled.
1182
+ // Bundled apps launched from Finder are activated automatically but
1183
+ // otherwise not. Activating the app even when it has been launched from
1184
+ // Finder does not seem to be harmful but calling this function is rarely
1185
+ // needed as proper activation is normally taken care of for us.
1186
+ // Bundled apps have a default activation policy of
1187
+ // NSApplicationActivationPolicyRegular while non-bundled apps have a
1188
+ // default activation policy of NSApplicationActivationPolicyProhibited.
1189
+ if (!is_app_bundled())
1190
+ {
1191
+ // "setActivationPolicy:" must be invoked before
1192
+ // "activateIgnoringOtherApps:" for activation to work.
1193
+ objc::msg_send<void>(app, "setActivationPolicy:"_sel,
1194
+ NSApplicationActivationPolicyRegular);
1195
+ // Activate the app regardless of other active apps.
1196
+ // This can be obtrusive so we only do it when necessary.
1197
+ objc::msg_send<void>(app, "activateIgnoringOtherApps:"_sel, YES);
1198
+ }
1199
+
1200
+ // Main window
1201
+ if (!m_parent_window)
1202
+ {
1203
+ m_window = objc::msg_send<id>("NSWindow"_cls, "alloc"_sel);
1204
+ auto style = NSWindowStyleMaskTitled;
1205
+ m_window = objc::msg_send<id>(
1206
+ m_window, "initWithContentRect:styleMask:backing:defer:"_sel,
1207
+ CGRectMake(0, 0, 0, 0), style, NSBackingStoreBuffered, NO);
1208
+ }
1209
+ else
1210
+ {
1211
+ m_window = (id)m_parent_window;
1212
+ }
1213
+
1214
+ // Webview
1215
+ auto config = objc::msg_send<id>("WKWebViewConfiguration"_cls, "new"_sel);
1216
+ m_manager = objc::msg_send<id>(config, "userContentController"_sel);
1217
+ m_webview = objc::msg_send<id>("WKWebView"_cls, "alloc"_sel);
1218
+
1219
+ if (m_debug)
1220
+ {
1221
+ // Equivalent Obj-C:
1222
+ // [[config preferences] setValue:@YES forKey:@"developerExtrasEnabled"];
1223
+ objc::msg_send<id>(
1224
+ objc::msg_send<id>(config, "preferences"_sel), "setValue:forKey:"_sel,
1225
+ objc::msg_send<id>("NSNumber"_cls, "numberWithBool:"_sel, YES),
1226
+ "developerExtrasEnabled"_str);
1227
+ }
1228
+
1229
+ // Equivalent Obj-C:
1230
+ // [[config preferences] setValue:@YES forKey:@"fullScreenEnabled"];
1231
+ objc::msg_send<id>(objc::msg_send<id>(config, "preferences"_sel),
1232
+ "setValue:forKey:"_sel,
1233
+ objc::msg_send<id>("NSNumber"_cls, "numberWithBool:"_sel, YES),
1234
+ "fullScreenEnabled"_str);
1235
+
1236
+ // Equivalent Obj-C:
1237
+ // [[config preferences] setValue:@YES forKey:@"javaScriptCanAccessClipboard"];
1238
+ objc::msg_send<id>(objc::msg_send<id>(config, "preferences"_sel),
1239
+ "setValue:forKey:"_sel,
1240
+ objc::msg_send<id>("NSNumber"_cls, "numberWithBool:"_sel, YES),
1241
+ "javaScriptCanAccessClipboard"_str);
1242
+
1243
+ // Equivalent Obj-C:
1244
+ // [[config preferences] setValue:@YES forKey:@"DOMPasteAllowed"];
1245
+ objc::msg_send<id>(objc::msg_send<id>(config, "preferences"_sel),
1246
+ "setValue:forKey:"_sel,
1247
+ objc::msg_send<id>("NSNumber"_cls, "numberWithBool:"_sel, YES),
1248
+ "DOMPasteAllowed"_str);
1249
+
1250
+ auto ui_delegate = create_webkit_ui_delegate();
1251
+ objc::msg_send<void>(m_webview, "initWithFrame:configuration:"_sel,
1252
+ CGRectMake(0, 0, 0, 0), config);
1253
+ objc::msg_send<void>(m_webview, "setUIDelegate:"_sel, ui_delegate);
1254
+
1255
+ auto navigation_delegate = create_webkit_navigation_delegate();
1256
+ objc::msg_send<void>(m_webview, "setNavigationDelegate:"_sel, navigation_delegate);
1257
+ auto script_message_handler = create_script_message_handler();
1258
+ objc::msg_send<void>(m_manager, "addScriptMessageHandler:name:"_sel,
1259
+ script_message_handler, "external"_str);
1260
+
1261
+ init(R""(
1262
+ window.external = {
1263
+ invoke: function(s) {
1264
+ window.webkit.messageHandlers.external.postMessage(s);
1265
+ },
1266
+ };
1267
+ )"");
1268
+ objc::msg_send<void>(m_window, "setContentView:"_sel, m_webview);
1269
+ objc::msg_send<void>(m_window, "makeKeyAndOrderFront:"_sel, nullptr);
1270
+ }
1271
+ bool m_debug;
1272
+ void* m_parent_window;
1273
+ id m_window;
1274
+ id m_webview;
1275
+ id m_manager;
1276
+ void* m_navigateCallbackArg = nullptr;
1277
+ std::function<void(const std::string&, void*)> m_navigateCallback = 0;
1278
+ };
1279
+
1280
+ } // namespace detail
1281
+
1282
+ using browser_engine = detail::cocoa_wkwebview_engine;
1283
+
1284
+ } // namespace webview
1285
+
1286
+ #elif defined(WEBVIEW_EDGE)
1287
+
1288
+ //
1289
+ // ====================================================================
1290
+ //
1291
+ // This implementation uses Win32 API to create a native window. It
1292
+ // uses Edge/Chromium webview2 backend as a browser engine.
1293
+ //
1294
+ // ====================================================================
1295
+ //
1296
+
1297
+ #define WIN32_LEAN_AND_MEAN
1298
+ #include <shlobj.h>
1299
+ #include <shlwapi.h>
1300
+ #include <stdlib.h>
1301
+ #include <windows.h>
1302
+
1303
+ #include "WebView2.h"
1304
+
1305
+ #ifdef _MSC_VER
1306
+ #pragma comment(lib, "advapi32.lib")
1307
+ #pragma comment(lib, "ole32.lib")
1308
+ #pragma comment(lib, "shell32.lib")
1309
+ #pragma comment(lib, "shlwapi.lib")
1310
+ #pragma comment(lib, "user32.lib")
1311
+ #pragma comment(lib, "version.lib")
1312
+ #endif
1313
+
1314
+ namespace webview
1315
+ {
1316
+ namespace detail
1317
+ {
1318
+
1319
+ using msg_cb_t = std::function<void(const std::string)>;
1320
+
1321
+ // Converts a narrow (UTF-8-encoded) string into a wide (UTF-16-encoded) string.
1322
+ inline std::wstring widen_string(const std::string& input)
1323
+ {
1324
+ if (input.empty())
1325
+ {
1326
+ return std::wstring();
1327
+ }
1328
+ UINT cp = CP_UTF8;
1329
+ DWORD flags = MB_ERR_INVALID_CHARS;
1330
+ auto input_c = input.c_str();
1331
+ auto input_length = static_cast<int>(input.size());
1332
+ auto required_length =
1333
+ MultiByteToWideChar(cp, flags, input_c, input_length, nullptr, 0);
1334
+ if (required_length > 0)
1335
+ {
1336
+ std::wstring output(static_cast<std::size_t>(required_length), L'\0');
1337
+ if (MultiByteToWideChar(cp, flags, input_c, input_length, &output[0],
1338
+ required_length) > 0)
1339
+ {
1340
+ return output;
1341
+ }
1342
+ }
1343
+ // Failed to convert string from UTF-8 to UTF-16
1344
+ return std::wstring();
1345
+ }
1346
+
1347
+ // Converts a wide (UTF-16-encoded) string into a narrow (UTF-8-encoded) string.
1348
+ inline std::string narrow_string(const std::wstring& input)
1349
+ {
1350
+ if (input.empty())
1351
+ {
1352
+ return std::string();
1353
+ }
1354
+ UINT cp = CP_UTF8;
1355
+ DWORD flags = WC_ERR_INVALID_CHARS;
1356
+ auto input_c = input.c_str();
1357
+ auto input_length = static_cast<int>(input.size());
1358
+ auto required_length =
1359
+ WideCharToMultiByte(cp, flags, input_c, input_length, nullptr, 0, nullptr, nullptr);
1360
+ if (required_length > 0)
1361
+ {
1362
+ std::string output(static_cast<std::size_t>(required_length), '\0');
1363
+ if (WideCharToMultiByte(cp, flags, input_c, input_length, &output[0],
1364
+ required_length, nullptr, nullptr) > 0)
1365
+ {
1366
+ return output;
1367
+ }
1368
+ }
1369
+ // Failed to convert string from UTF-16 to UTF-8
1370
+ return std::string();
1371
+ }
1372
+
1373
+ // Parses a version string with 1-4 integral components, e.g. "1.2.3.4".
1374
+ // Missing or invalid components default to 0, and excess components are ignored.
1375
+ template <typename T>
1376
+ std::array<unsigned int, 4> parse_version(const std::basic_string<T>& version) noexcept
1377
+ {
1378
+ auto parse_component = [](auto sb, auto se) -> unsigned int
1379
+ {
1380
+ try
1381
+ {
1382
+ auto n = std::stol(std::basic_string<T>(sb, se));
1383
+ return n < 0 ? 0 : n;
1384
+ }
1385
+ catch (std::exception&)
1386
+ {
1387
+ return 0;
1388
+ }
1389
+ };
1390
+ auto end = version.end();
1391
+ auto sb = version.begin(); // subrange begin
1392
+ auto se = sb; // subrange end
1393
+ unsigned int ci = 0; // component index
1394
+ std::array<unsigned int, 4> components{};
1395
+ while (sb != end && se != end && ci < components.size())
1396
+ {
1397
+ if (*se == static_cast<T>('.'))
1398
+ {
1399
+ components[ci++] = parse_component(sb, se);
1400
+ sb = ++se;
1401
+ continue;
1402
+ }
1403
+ ++se;
1404
+ }
1405
+ if (sb < se && ci < components.size())
1406
+ {
1407
+ components[ci] = parse_component(sb, se);
1408
+ }
1409
+ return components;
1410
+ }
1411
+
1412
+ template <typename T, std::size_t Length>
1413
+ auto parse_version(const T (&version)[Length]) noexcept
1414
+ {
1415
+ return parse_version(std::basic_string<T>(version, Length));
1416
+ }
1417
+
1418
+ std::wstring get_file_version_string(const std::wstring& file_path) noexcept
1419
+ {
1420
+ DWORD dummy_handle; // Unused
1421
+ DWORD info_buffer_length = GetFileVersionInfoSizeW(file_path.c_str(), &dummy_handle);
1422
+ if (info_buffer_length == 0)
1423
+ {
1424
+ return std::wstring();
1425
+ }
1426
+ std::vector<char> info_buffer;
1427
+ info_buffer.reserve(info_buffer_length);
1428
+ if (!GetFileVersionInfoW(file_path.c_str(), 0, info_buffer_length, info_buffer.data()))
1429
+ {
1430
+ return std::wstring();
1431
+ }
1432
+ auto sub_block = L"\\StringFileInfo\\040904B0\\ProductVersion";
1433
+ LPWSTR version = nullptr;
1434
+ unsigned int version_length = 0;
1435
+ if (!VerQueryValueW(info_buffer.data(), sub_block, reinterpret_cast<LPVOID*>(&version),
1436
+ &version_length))
1437
+ {
1438
+ return std::wstring();
1439
+ }
1440
+ if (!version || version_length == 0)
1441
+ {
1442
+ return std::wstring();
1443
+ }
1444
+ return std::wstring(version, version_length);
1445
+ }
1446
+
1447
+ // A wrapper around COM library initialization. Calls CoInitializeEx in the
1448
+ // constructor and CoUninitialize in the destructor.
1449
+ class com_init_wrapper
1450
+ {
1451
+ public:
1452
+ com_init_wrapper(DWORD dwCoInit)
1453
+ {
1454
+ // We can safely continue as long as COM was either successfully
1455
+ // initialized or already initialized.
1456
+ // RPC_E_CHANGED_MODE means that CoInitializeEx was already called with
1457
+ // a different concurrency model.
1458
+ switch (CoInitializeEx(nullptr, dwCoInit))
1459
+ {
1460
+ case S_OK:
1461
+ case S_FALSE:
1462
+ m_initialized = true;
1463
+ break;
1464
+ }
1465
+ }
1466
+
1467
+ ~com_init_wrapper()
1468
+ {
1469
+ if (m_initialized)
1470
+ {
1471
+ CoUninitialize();
1472
+ m_initialized = false;
1473
+ }
1474
+ }
1475
+
1476
+ com_init_wrapper(const com_init_wrapper& other) = delete;
1477
+ com_init_wrapper& operator=(const com_init_wrapper& other) = delete;
1478
+ com_init_wrapper(com_init_wrapper&& other) = delete;
1479
+ com_init_wrapper& operator=(com_init_wrapper&& other) = delete;
1480
+
1481
+ bool is_initialized() const
1482
+ {
1483
+ return m_initialized;
1484
+ }
1485
+
1486
+ private:
1487
+ bool m_initialized = false;
1488
+ };
1489
+
1490
+ // Holds a symbol name and associated type for code clarity.
1491
+ template <typename T> class library_symbol
1492
+ {
1493
+ public:
1494
+ using type = T;
1495
+
1496
+ constexpr explicit library_symbol(const char* name) : m_name(name)
1497
+ {
1498
+ }
1499
+ constexpr const char* get_name() const
1500
+ {
1501
+ return m_name;
1502
+ }
1503
+
1504
+ private:
1505
+ const char* m_name;
1506
+ };
1507
+
1508
+ // Loads a native shared library and allows one to get addresses for those
1509
+ // symbols.
1510
+ class native_library
1511
+ {
1512
+ public:
1513
+ explicit native_library(const wchar_t* name) : m_handle(LoadLibraryW(name))
1514
+ {
1515
+ }
1516
+
1517
+ ~native_library()
1518
+ {
1519
+ if (m_handle)
1520
+ {
1521
+ FreeLibrary(m_handle);
1522
+ m_handle = nullptr;
1523
+ }
1524
+ }
1525
+
1526
+ native_library(const native_library& other) = delete;
1527
+ native_library& operator=(const native_library& other) = delete;
1528
+ native_library(native_library&& other) = default;
1529
+ native_library& operator=(native_library&& other) = default;
1530
+
1531
+ // Returns true if the library is currently loaded; otherwise false.
1532
+ operator bool() const
1533
+ {
1534
+ return is_loaded();
1535
+ }
1536
+
1537
+ // Get the address for the specified symbol or nullptr if not found.
1538
+ template <typename Symbol> typename Symbol::type get(const Symbol& symbol) const
1539
+ {
1540
+ if (is_loaded())
1541
+ {
1542
+ return reinterpret_cast<typename Symbol::type>(
1543
+ GetProcAddress(m_handle, symbol.get_name()));
1544
+ }
1545
+ return nullptr;
1546
+ }
1547
+
1548
+ // Returns true if the library is currently loaded; otherwise false.
1549
+ bool is_loaded() const
1550
+ {
1551
+ return !!m_handle;
1552
+ }
1553
+
1554
+ void detach()
1555
+ {
1556
+ m_handle = nullptr;
1557
+ }
1558
+
1559
+ private:
1560
+ HMODULE m_handle = nullptr;
1561
+ };
1562
+
1563
+ struct user32_symbols
1564
+ {
1565
+ using DPI_AWARENESS_CONTEXT = HANDLE;
1566
+ using SetProcessDpiAwarenessContext_t = BOOL(WINAPI*)(DPI_AWARENESS_CONTEXT);
1567
+ using SetProcessDPIAware_t = BOOL(WINAPI*)();
1568
+
1569
+ static constexpr auto SetProcessDpiAwarenessContext =
1570
+ library_symbol<SetProcessDpiAwarenessContext_t>("SetProcessDpiAwarenessContext");
1571
+ static constexpr auto SetProcessDPIAware =
1572
+ library_symbol<SetProcessDPIAware_t>("SetProcessDPIAware");
1573
+ };
1574
+
1575
+ struct shcore_symbols
1576
+ {
1577
+ typedef enum
1578
+ {
1579
+ PROCESS_PER_MONITOR_DPI_AWARE = 2
1580
+ } PROCESS_DPI_AWARENESS;
1581
+ using SetProcessDpiAwareness_t = HRESULT(WINAPI*)(PROCESS_DPI_AWARENESS);
1582
+
1583
+ static constexpr auto SetProcessDpiAwareness =
1584
+ library_symbol<SetProcessDpiAwareness_t>("SetProcessDpiAwareness");
1585
+ };
1586
+
1587
+ class reg_key
1588
+ {
1589
+ public:
1590
+ explicit reg_key(HKEY root_key, const wchar_t* sub_key, DWORD options,
1591
+ REGSAM sam_desired)
1592
+ {
1593
+ HKEY handle;
1594
+ auto status = RegOpenKeyExW(root_key, sub_key, options, sam_desired, &handle);
1595
+ if (status == ERROR_SUCCESS)
1596
+ {
1597
+ m_handle = handle;
1598
+ }
1599
+ }
1600
+
1601
+ explicit reg_key(HKEY root_key, const std::wstring& sub_key, DWORD options,
1602
+ REGSAM sam_desired)
1603
+ : reg_key(root_key, sub_key.c_str(), options, sam_desired)
1604
+ {
1605
+ }
1606
+
1607
+ virtual ~reg_key()
1608
+ {
1609
+ if (m_handle)
1610
+ {
1611
+ RegCloseKey(m_handle);
1612
+ m_handle = nullptr;
1613
+ }
1614
+ }
1615
+
1616
+ reg_key(const reg_key& other) = delete;
1617
+ reg_key& operator=(const reg_key& other) = delete;
1618
+ reg_key(reg_key&& other) = delete;
1619
+ reg_key& operator=(reg_key&& other) = delete;
1620
+
1621
+ bool is_open() const
1622
+ {
1623
+ return !!m_handle;
1624
+ }
1625
+ bool get_handle() const
1626
+ {
1627
+ return m_handle;
1628
+ }
1629
+
1630
+ std::wstring query_string(const wchar_t* name) const
1631
+ {
1632
+ DWORD buf_length = 0;
1633
+ // Get the size of the data in bytes.
1634
+ auto status =
1635
+ RegQueryValueExW(m_handle, name, nullptr, nullptr, nullptr, &buf_length);
1636
+ if (status != ERROR_SUCCESS && status != ERROR_MORE_DATA)
1637
+ {
1638
+ return std::wstring();
1639
+ }
1640
+ // Read the data.
1641
+ std::wstring result(buf_length / sizeof(wchar_t), 0);
1642
+ auto buf = reinterpret_cast<LPBYTE>(&result[0]);
1643
+ status = RegQueryValueExW(m_handle, name, nullptr, nullptr, buf, &buf_length);
1644
+ if (status != ERROR_SUCCESS)
1645
+ {
1646
+ return std::wstring();
1647
+ }
1648
+ // Remove trailing null-characters.
1649
+ for (std::size_t length = result.size(); length > 0; --length)
1650
+ {
1651
+ if (result[length - 1] != 0)
1652
+ {
1653
+ result.resize(length);
1654
+ break;
1655
+ }
1656
+ }
1657
+ return result;
1658
+ }
1659
+
1660
+ private:
1661
+ HKEY m_handle = nullptr;
1662
+ };
1663
+
1664
+ inline bool enable_dpi_awareness()
1665
+ {
1666
+ auto user32 = native_library(L"user32.dll");
1667
+ if (auto fn = user32.get(user32_symbols::SetProcessDpiAwarenessContext))
1668
+ {
1669
+ if (fn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE))
1670
+ {
1671
+ return true;
1672
+ }
1673
+ return GetLastError() == ERROR_ACCESS_DENIED;
1674
+ }
1675
+ if (auto shcore = native_library(L"shcore.dll"))
1676
+ {
1677
+ if (auto fn = shcore.get(shcore_symbols::SetProcessDpiAwareness))
1678
+ {
1679
+ auto result = fn(shcore_symbols::PROCESS_PER_MONITOR_DPI_AWARE);
1680
+ return result == S_OK || result == E_ACCESSDENIED;
1681
+ }
1682
+ }
1683
+ if (auto fn = user32.get(user32_symbols::SetProcessDPIAware))
1684
+ {
1685
+ return !!fn();
1686
+ }
1687
+ return true;
1688
+ }
1689
+
1690
+ // Enable built-in WebView2Loader implementation by default.
1691
+ #ifndef WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL
1692
+ #define WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL 1
1693
+ #endif
1694
+
1695
+ // Link WebView2Loader.dll explicitly by default only if the built-in
1696
+ // implementation is enabled.
1697
+ #ifndef WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK
1698
+ #define WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL
1699
+ #endif
1700
+
1701
+ // Explicit linking of WebView2Loader.dll should be used along with
1702
+ // the built-in implementation.
1703
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1 && WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK != 1
1704
+ #undef WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK
1705
+ #error Please set WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK=1.
1706
+ #endif
1707
+
1708
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1
1709
+ // Gets the last component of a Windows native file path.
1710
+ // For example, if the path is "C:\a\b" then the result is "b".
1711
+ template <typename T>
1712
+ std::basic_string<T> get_last_native_path_component(const std::basic_string<T>& path)
1713
+ {
1714
+ if (auto pos = path.find_last_of(static_cast<T>('\\'));
1715
+ pos != std::basic_string<T>::npos)
1716
+ {
1717
+ return path.substr(pos + 1);
1718
+ }
1719
+ return std::basic_string<T>();
1720
+ }
1721
+ #endif /* WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL */
1722
+
1723
+ template <typename T> struct cast_info_t
1724
+ {
1725
+ using type = T;
1726
+ IID iid;
1727
+ };
1728
+
1729
+ namespace mswebview2
1730
+ {
1731
+ static constexpr IID IID_ICoreWebView2CreateCoreWebView2ControllerCompletedHandler{
1732
+ 0x6C4819F3, 0xC9B7, 0x4260, 0x81, 0x27, 0xC9, 0xF5, 0xBD, 0xE7, 0xF6, 0x8C
1733
+ };
1734
+ static constexpr IID IID_ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler{
1735
+ 0x4E8A3389, 0xC9D8, 0x4BD2, 0xB6, 0xB5, 0x12, 0x4F, 0xEE, 0x6C, 0xC1, 0x4D
1736
+ };
1737
+ static constexpr IID IID_ICoreWebView2PermissionRequestedEventHandler{
1738
+ 0x15E1C6A3, 0xC72A, 0x4DF3, 0x91, 0xD7, 0xD0, 0x97, 0xFB, 0xEC, 0x6B, 0xFD
1739
+ };
1740
+ static constexpr IID IID_ICoreWebView2WebMessageReceivedEventHandler{
1741
+ 0x57213F19, 0x00E6, 0x49FA, 0x8E, 0x07, 0x89, 0x8E, 0xA0, 0x1E, 0xCB, 0xD2
1742
+ };
1743
+
1744
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1
1745
+ enum class webview2_runtime_type
1746
+ {
1747
+ installed = 0,
1748
+ embedded = 1
1749
+ };
1750
+
1751
+ namespace webview2_symbols
1752
+ {
1753
+ using CreateWebViewEnvironmentWithOptionsInternal_t = HRESULT(STDMETHODCALLTYPE*)(
1754
+ bool, webview2_runtime_type, PCWSTR, IUnknown*,
1755
+ ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
1756
+ using DllCanUnloadNow_t = HRESULT(STDMETHODCALLTYPE*)();
1757
+
1758
+ static constexpr auto CreateWebViewEnvironmentWithOptionsInternal =
1759
+ library_symbol<CreateWebViewEnvironmentWithOptionsInternal_t>(
1760
+ "CreateWebViewEnvironmentWithOptionsInternal");
1761
+ static constexpr auto DllCanUnloadNow =
1762
+ library_symbol<DllCanUnloadNow_t>("DllCanUnloadNow");
1763
+ } // namespace webview2_symbols
1764
+ #endif /* WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL */
1765
+
1766
+ #if WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK == 1
1767
+ namespace webview2_symbols
1768
+ {
1769
+ using CreateCoreWebView2EnvironmentWithOptions_t = HRESULT(STDMETHODCALLTYPE*)(
1770
+ PCWSTR, PCWSTR, ICoreWebView2EnvironmentOptions*,
1771
+ ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler*);
1772
+ using GetAvailableCoreWebView2BrowserVersionString_t =
1773
+ HRESULT(STDMETHODCALLTYPE*)(PCWSTR, LPWSTR*);
1774
+
1775
+ static constexpr auto CreateCoreWebView2EnvironmentWithOptions =
1776
+ library_symbol<CreateCoreWebView2EnvironmentWithOptions_t>(
1777
+ "CreateCoreWebView2EnvironmentWithOptions");
1778
+ static constexpr auto GetAvailableCoreWebView2BrowserVersionString =
1779
+ library_symbol<GetAvailableCoreWebView2BrowserVersionString_t>(
1780
+ "GetAvailableCoreWebView2BrowserVersionString");
1781
+ } // namespace webview2_symbols
1782
+ #endif /* WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK */
1783
+
1784
+ class loader
1785
+ {
1786
+ public:
1787
+ HRESULT create_environment_with_options(
1788
+ PCWSTR browser_dir, PCWSTR user_data_dir,
1789
+ ICoreWebView2EnvironmentOptions* env_options,
1790
+ ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* created_handler)
1791
+ const
1792
+ {
1793
+ #if WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK == 1
1794
+ if (m_lib.is_loaded())
1795
+ {
1796
+ if (auto fn = m_lib.get(
1797
+ webview2_symbols::CreateCoreWebView2EnvironmentWithOptions))
1798
+ {
1799
+ return fn(browser_dir, user_data_dir, env_options, created_handler);
1800
+ }
1801
+ }
1802
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1
1803
+ return create_environment_with_options_impl(browser_dir, user_data_dir,
1804
+ env_options, created_handler);
1805
+ #else
1806
+ return S_FALSE;
1807
+ #endif
1808
+ #else
1809
+ return ::CreateCoreWebView2EnvironmentWithOptions(browser_dir, user_data_dir,
1810
+ env_options, created_handler);
1811
+ #endif /* WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK */
1812
+ }
1813
+
1814
+ HRESULT
1815
+ get_available_browser_version_string(PCWSTR browser_dir, LPWSTR* version) const
1816
+ {
1817
+ #if WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK == 1
1818
+ if (m_lib.is_loaded())
1819
+ {
1820
+ if (auto fn = m_lib.get(
1821
+ webview2_symbols::GetAvailableCoreWebView2BrowserVersionString))
1822
+ {
1823
+ return fn(browser_dir, version);
1824
+ }
1825
+ }
1826
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1
1827
+ return get_available_browser_version_string_impl(browser_dir, version);
1828
+ #else
1829
+ return S_FALSE;
1830
+ #endif
1831
+ #else
1832
+ return ::GetAvailableCoreWebView2BrowserVersionString(browser_dir, version);
1833
+ #endif /* WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK */
1834
+ }
1835
+
1836
+ private:
1837
+ #if WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL == 1
1838
+ struct client_info_t
1839
+ {
1840
+ bool found = false;
1841
+ std::wstring dll_path;
1842
+ std::wstring version;
1843
+ webview2_runtime_type runtime_type;
1844
+ };
1845
+
1846
+ HRESULT create_environment_with_options_impl(
1847
+ PCWSTR browser_dir, PCWSTR user_data_dir,
1848
+ ICoreWebView2EnvironmentOptions* env_options,
1849
+ ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler* created_handler)
1850
+ const
1851
+ {
1852
+ auto found_client = find_available_client(browser_dir);
1853
+ if (!found_client.found)
1854
+ {
1855
+ return -1;
1856
+ }
1857
+ auto client_dll = native_library(found_client.dll_path.c_str());
1858
+ if (auto fn = client_dll.get(
1859
+ webview2_symbols::CreateWebViewEnvironmentWithOptionsInternal))
1860
+ {
1861
+ return fn(true, found_client.runtime_type, user_data_dir, env_options,
1862
+ created_handler);
1863
+ }
1864
+ if (auto fn = client_dll.get(webview2_symbols::DllCanUnloadNow))
1865
+ {
1866
+ if (!fn())
1867
+ {
1868
+ client_dll.detach();
1869
+ }
1870
+ }
1871
+ return ERROR_SUCCESS;
1872
+ }
1873
+
1874
+ HRESULT
1875
+ get_available_browser_version_string_impl(PCWSTR browser_dir, LPWSTR* version) const
1876
+ {
1877
+ if (!version)
1878
+ {
1879
+ return -1;
1880
+ }
1881
+ auto found_client = find_available_client(browser_dir);
1882
+ if (!found_client.found)
1883
+ {
1884
+ return -1;
1885
+ }
1886
+ auto info_length_bytes =
1887
+ found_client.version.size() * sizeof(found_client.version[0]);
1888
+ auto info = static_cast<LPWSTR>(CoTaskMemAlloc(info_length_bytes));
1889
+ if (!info)
1890
+ {
1891
+ return -1;
1892
+ }
1893
+ CopyMemory(info, found_client.version.c_str(), info_length_bytes);
1894
+ *version = info;
1895
+ return 0;
1896
+ }
1897
+
1898
+ client_info_t find_available_client(PCWSTR browser_dir) const
1899
+ {
1900
+ if (browser_dir)
1901
+ {
1902
+ return find_embedded_client(api_version, browser_dir);
1903
+ }
1904
+ auto found_client =
1905
+ find_installed_client(api_version, true, default_release_channel_guid);
1906
+ if (!found_client.found)
1907
+ {
1908
+ found_client =
1909
+ find_installed_client(api_version, false, default_release_channel_guid);
1910
+ }
1911
+ return found_client;
1912
+ }
1913
+
1914
+ std::wstring make_client_dll_path(const std::wstring& dir) const
1915
+ {
1916
+ auto dll_path = dir;
1917
+ if (!dll_path.empty())
1918
+ {
1919
+ auto last_char = dir[dir.size() - 1];
1920
+ if (last_char != L'\\' && last_char != L'/')
1921
+ {
1922
+ dll_path += L'\\';
1923
+ }
1924
+ }
1925
+ dll_path += L"EBWebView\\";
1926
+ #if defined(_M_X64) || defined(__x86_64__)
1927
+ dll_path += L"x64";
1928
+ #elif defined(_M_IX86) || defined(__i386__)
1929
+ dll_path += L"x86";
1930
+ #elif defined(_M_ARM64) || defined(__aarch64__)
1931
+ dll_path += L"arm64";
1932
+ #else
1933
+ #error WebView2 integration for this platform is not yet supported.
1934
+ #endif
1935
+ dll_path += L"\\EmbeddedBrowserWebView.dll";
1936
+ return dll_path;
1937
+ }
1938
+
1939
+ client_info_t find_installed_client(unsigned int min_api_version, bool system,
1940
+ const std::wstring& release_channel) const
1941
+ {
1942
+ std::wstring sub_key = client_state_reg_sub_key;
1943
+ sub_key += release_channel;
1944
+ auto root_key = system ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
1945
+ reg_key key(root_key, sub_key, 0, KEY_READ | KEY_WOW64_32KEY);
1946
+ if (!key.is_open())
1947
+ {
1948
+ return {};
1949
+ }
1950
+ auto ebwebview_value = key.query_string(L"EBWebView");
1951
+
1952
+ auto client_version_string = get_last_native_path_component(ebwebview_value);
1953
+ auto client_version = parse_version(client_version_string);
1954
+ if (client_version[2] < min_api_version)
1955
+ {
1956
+ // Our API version is greater than the runtime API version.
1957
+ return {};
1958
+ }
1959
+
1960
+ auto client_dll_path = make_client_dll_path(ebwebview_value);
1961
+ return { true, client_dll_path, client_version_string,
1962
+ webview2_runtime_type::installed };
1963
+ }
1964
+
1965
+ client_info_t find_embedded_client(unsigned int min_api_version,
1966
+ const std::wstring& dir) const
1967
+ {
1968
+ auto client_dll_path = make_client_dll_path(dir);
1969
+
1970
+ auto client_version_string = get_file_version_string(client_dll_path);
1971
+ auto client_version = parse_version(client_version_string);
1972
+ if (client_version[2] < min_api_version)
1973
+ {
1974
+ // Our API version is greater than the runtime API version.
1975
+ return {};
1976
+ }
1977
+
1978
+ return { true, client_dll_path, client_version_string,
1979
+ webview2_runtime_type::embedded };
1980
+ }
1981
+
1982
+ // The minimum WebView2 API version we need regardless of the SDK release
1983
+ // actually used. The number comes from the SDK release version,
1984
+ // e.g. 1.0.1150.38. To be safe the SDK should have a number that is greater
1985
+ // than or equal to this number. The Edge browser webview client must
1986
+ // have a number greater than or equal to this number.
1987
+ static constexpr unsigned int api_version = 1150;
1988
+
1989
+ static constexpr auto client_state_reg_sub_key =
1990
+ L"SOFTWARE\\Microsoft\\EdgeUpdate\\ClientState\\";
1991
+
1992
+ // GUID for the stable release channel.
1993
+ static constexpr auto stable_release_guid =
1994
+ L"{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";
1995
+
1996
+ static constexpr auto default_release_channel_guid = stable_release_guid;
1997
+ #endif /* WEBVIEW_MSWEBVIEW2_BUILTIN_IMPL */
1998
+
1999
+ #if WEBVIEW_MSWEBVIEW2_EXPLICIT_LINK == 1
2000
+ native_library m_lib{ L"WebView2Loader.dll" };
2001
+ #endif
2002
+ };
2003
+
2004
+ namespace cast_info
2005
+ {
2006
+ static constexpr auto controller_completed =
2007
+ cast_info_t<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>{
2008
+ IID_ICoreWebView2CreateCoreWebView2ControllerCompletedHandler
2009
+ };
2010
+
2011
+ static constexpr auto environment_completed =
2012
+ cast_info_t<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>{
2013
+ IID_ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler
2014
+ };
2015
+
2016
+ static constexpr auto message_received =
2017
+ cast_info_t<ICoreWebView2WebMessageReceivedEventHandler>{
2018
+ IID_ICoreWebView2WebMessageReceivedEventHandler
2019
+ };
2020
+
2021
+ static constexpr auto permission_requested =
2022
+ cast_info_t<ICoreWebView2PermissionRequestedEventHandler>{
2023
+ IID_ICoreWebView2PermissionRequestedEventHandler
2024
+ };
2025
+ } // namespace cast_info
2026
+ } // namespace mswebview2
2027
+
2028
+ class webview2_com_handler
2029
+ : public ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler,
2030
+ public ICoreWebView2CreateCoreWebView2ControllerCompletedHandler,
2031
+ public ICoreWebView2WebMessageReceivedEventHandler,
2032
+ public ICoreWebView2PermissionRequestedEventHandler,
2033
+ public ICoreWebView2NavigationCompletedEventHandler
2034
+ {
2035
+ using webview2_com_handler_cb_t =
2036
+ std::function<void(ICoreWebView2Controller*, ICoreWebView2* webview)>;
2037
+
2038
+ public:
2039
+ webview2_com_handler(HWND hwnd, msg_cb_t msgCb, webview2_com_handler_cb_t cb)
2040
+ : m_window(hwnd), m_msgCb(msgCb), m_cb(cb)
2041
+ {
2042
+ }
2043
+
2044
+ virtual ~webview2_com_handler() = default;
2045
+ webview2_com_handler(const webview2_com_handler& other) = delete;
2046
+ webview2_com_handler& operator=(const webview2_com_handler& other) = delete;
2047
+ webview2_com_handler(webview2_com_handler&& other) = delete;
2048
+ webview2_com_handler& operator=(webview2_com_handler&& other) = delete;
2049
+
2050
+ ULONG STDMETHODCALLTYPE AddRef()
2051
+ {
2052
+ return ++m_ref_count;
2053
+ }
2054
+ ULONG STDMETHODCALLTYPE Release()
2055
+ {
2056
+ if (m_ref_count > 1)
2057
+ {
2058
+ return --m_ref_count;
2059
+ }
2060
+ delete this;
2061
+ return 0;
2062
+ }
2063
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, LPVOID* ppv)
2064
+ {
2065
+ using namespace mswebview2::cast_info;
2066
+
2067
+ if (!ppv)
2068
+ {
2069
+ return E_POINTER;
2070
+ }
2071
+
2072
+ // All of the COM interfaces we implement should be added here regardless
2073
+ // of whether they are required.
2074
+ // This is just to be on the safe side in case the WebView2 Runtime ever
2075
+ // requests a pointer to an interface we implement.
2076
+ // The WebView2 Runtime must at the very least be able to get a pointer to
2077
+ // ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler when we use
2078
+ // our custom WebView2 loader implementation, and observations have shown
2079
+ // that it is the only interface requested in this case. None have been
2080
+ // observed to be requested when using the official WebView2 loader.
2081
+
2082
+ if (cast_if_equal_iid(riid, controller_completed, ppv) ||
2083
+ cast_if_equal_iid(riid, environment_completed, ppv) ||
2084
+ cast_if_equal_iid(riid, message_received, ppv) ||
2085
+ cast_if_equal_iid(riid, permission_requested, ppv))
2086
+ {
2087
+ return S_OK;
2088
+ }
2089
+
2090
+ return E_NOINTERFACE;
2091
+ }
2092
+ HRESULT STDMETHODCALLTYPE Invoke(HRESULT res, ICoreWebView2Environment* env)
2093
+ {
2094
+ if (SUCCEEDED(res))
2095
+ {
2096
+ res = env->CreateCoreWebView2Controller(m_window, this);
2097
+ if (SUCCEEDED(res))
2098
+ {
2099
+ return S_OK;
2100
+ }
2101
+ }
2102
+ try_create_environment();
2103
+ return S_OK;
2104
+ }
2105
+ HRESULT STDMETHODCALLTYPE Invoke(HRESULT res, ICoreWebView2Controller* controller)
2106
+ {
2107
+ if (FAILED(res))
2108
+ {
2109
+ // See try_create_environment() regarding
2110
+ // HRESULT_FROM_WIN32(ERROR_INVALID_STATE).
2111
+ // The result is E_ABORT if the parent window has been destroyed already.
2112
+ switch (res)
2113
+ {
2114
+ case HRESULT_FROM_WIN32(ERROR_INVALID_STATE):
2115
+ case E_ABORT:
2116
+ return S_OK;
2117
+ }
2118
+ try_create_environment();
2119
+ return S_OK;
2120
+ }
2121
+
2122
+ ICoreWebView2* webview;
2123
+ ::EventRegistrationToken token;
2124
+ controller->get_CoreWebView2(&webview);
2125
+ webview->add_WebMessageReceived(this, &token);
2126
+ webview->add_PermissionRequested(this, &token);
2127
+ webview->add_NavigationCompleted(this, &token);
2128
+
2129
+ m_cb(controller, webview);
2130
+ return S_OK;
2131
+ }
2132
+ HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2* sender,
2133
+ ICoreWebView2WebMessageReceivedEventArgs* args)
2134
+ {
2135
+ LPWSTR message;
2136
+ args->TryGetWebMessageAsString(&message);
2137
+ m_msgCb(narrow_string(message));
2138
+ sender->PostWebMessageAsString(message);
2139
+
2140
+ CoTaskMemFree(message);
2141
+ return S_OK;
2142
+ }
2143
+ HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2* sender,
2144
+ ICoreWebView2PermissionRequestedEventArgs* args)
2145
+ {
2146
+ COREWEBVIEW2_PERMISSION_KIND kind;
2147
+ args->get_PermissionKind(&kind);
2148
+ if (kind == COREWEBVIEW2_PERMISSION_KIND_CLIPBOARD_READ)
2149
+ {
2150
+ args->put_State(COREWEBVIEW2_PERMISSION_STATE_ALLOW);
2151
+ }
2152
+ return S_OK;
2153
+ }
2154
+ HRESULT STDMETHODCALLTYPE Invoke(ICoreWebView2* sender,
2155
+ ICoreWebView2NavigationCompletedEventArgs* args)
2156
+ {
2157
+ PWSTR uri = nullptr;
2158
+ auto hr = sender->get_Source(&uri);
2159
+ if (SUCCEEDED(hr))
2160
+ {
2161
+ auto curi = std::wstring_convert<std::codecvt_utf8<wchar_t> >().to_bytes(uri);
2162
+ if (navigateCallback)
2163
+ navigateCallback(curi, navigateCallbackArg);
2164
+ }
2165
+ CoTaskMemFree(uri);
2166
+ return hr;
2167
+ }
2168
+
2169
+ // Checks whether the specified IID equals the IID of the specified type and
2170
+ // if so casts the "this" pointer to T and returns it. Returns nullptr on
2171
+ // mismatching IIDs.
2172
+ // If ppv is specified then the pointer will also be assigned to *ppv.
2173
+ template <typename T>
2174
+ T* cast_if_equal_iid(REFIID riid, const cast_info_t<T>& info,
2175
+ LPVOID* ppv = nullptr) noexcept
2176
+ {
2177
+ T* ptr = nullptr;
2178
+ if (IsEqualIID(riid, info.iid))
2179
+ {
2180
+ ptr = static_cast<T*>(this);
2181
+ ptr->AddRef();
2182
+ }
2183
+ if (ppv)
2184
+ {
2185
+ *ppv = ptr;
2186
+ }
2187
+ return ptr;
2188
+ }
2189
+
2190
+ // Set the function that will perform the initiating logic for creating
2191
+ // the WebView2 environment.
2192
+ void set_attempt_handler(std::function<HRESULT()> attempt_handler) noexcept
2193
+ {
2194
+ m_attempt_handler = attempt_handler;
2195
+ }
2196
+
2197
+ // Retry creating a WebView2 environment.
2198
+ // The initiating logic for creating the environment is defined by the
2199
+ // caller of set_attempt_handler().
2200
+ void try_create_environment() noexcept
2201
+ {
2202
+ // WebView creation fails with HRESULT_FROM_WIN32(ERROR_INVALID_STATE) if
2203
+ // a running instance using the same user data folder exists, and the
2204
+ // Environment objects have different EnvironmentOptions.
2205
+ // Source:
2206
+ // https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2environment?view=webview2-1.0.1150.38
2207
+ if (m_attempts < m_max_attempts)
2208
+ {
2209
+ ++m_attempts;
2210
+ auto res = m_attempt_handler();
2211
+ if (SUCCEEDED(res))
2212
+ {
2213
+ return;
2214
+ }
2215
+ // Not entirely sure if this error code only applies to
2216
+ // CreateCoreWebView2Controller so we check here as well.
2217
+ if (res == HRESULT_FROM_WIN32(ERROR_INVALID_STATE))
2218
+ {
2219
+ return;
2220
+ }
2221
+ try_create_environment();
2222
+ return;
2223
+ }
2224
+ // Give up.
2225
+ m_cb(nullptr, nullptr);
2226
+ }
2227
+
2228
+ void STDMETHODCALLTYPE add_navigate_listener(
2229
+ std::function<void(const std::string&, void*)> callback, void* arg)
2230
+ {
2231
+ navigateCallback = std::move(callback);
2232
+ navigateCallbackArg = arg;
2233
+ }
2234
+
2235
+ private:
2236
+ HWND m_window;
2237
+ msg_cb_t m_msgCb;
2238
+ webview2_com_handler_cb_t m_cb;
2239
+ std::atomic<ULONG> m_ref_count{ 1 };
2240
+ std::function<HRESULT()> m_attempt_handler;
2241
+ unsigned int m_max_attempts = 5;
2242
+ unsigned int m_attempts = 0;
2243
+ void* navigateCallbackArg = nullptr;
2244
+ std::function<void(const std::string&, void*)> navigateCallback = 0;
2245
+ };
2246
+
2247
+ class win32_edge_engine
2248
+ {
2249
+ public:
2250
+ win32_edge_engine(bool debug, void* window)
2251
+ {
2252
+ if (!is_webview2_available())
2253
+ {
2254
+ return;
2255
+ }
2256
+ if (!m_com_init.is_initialized())
2257
+ {
2258
+ return;
2259
+ }
2260
+ enable_dpi_awareness();
2261
+ if (window == nullptr)
2262
+ {
2263
+ HINSTANCE hInstance = GetModuleHandle(nullptr);
2264
+ HICON icon = (HICON)LoadImage(hInstance, IDI_APPLICATION, IMAGE_ICON,
2265
+ GetSystemMetrics(SM_CXICON),
2266
+ GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
2267
+
2268
+ WNDCLASSEXW wc;
2269
+ ZeroMemory(&wc, sizeof(WNDCLASSEX));
2270
+ wc.cbSize = sizeof(WNDCLASSEX);
2271
+ wc.hInstance = hInstance;
2272
+ wc.lpszClassName = L"webview";
2273
+ wc.hIcon = icon;
2274
+ wc.lpfnWndProc =
2275
+ (WNDPROC)(+[](HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) -> LRESULT
2276
+ {
2277
+ auto w =
2278
+ (win32_edge_engine*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
2279
+ switch (msg)
2280
+ {
2281
+ case WM_SIZE:
2282
+ w->resize(hwnd);
2283
+ break;
2284
+ case WM_CLOSE:
2285
+ DestroyWindow(hwnd);
2286
+ break;
2287
+ case WM_DESTROY:
2288
+ w->terminate();
2289
+ break;
2290
+ case WM_GETMINMAXINFO:
2291
+ {
2292
+ auto lpmmi = (LPMINMAXINFO)lp;
2293
+ if (w == nullptr)
2294
+ {
2295
+ return 0;
2296
+ }
2297
+ if (w->m_maxsz.x > 0 && w->m_maxsz.y > 0)
2298
+ {
2299
+ lpmmi->ptMaxSize = w->m_maxsz;
2300
+ lpmmi->ptMaxTrackSize = w->m_maxsz;
2301
+ }
2302
+ if (w->m_minsz.x > 0 && w->m_minsz.y > 0)
2303
+ {
2304
+ lpmmi->ptMinTrackSize = w->m_minsz;
2305
+ }
2306
+ }
2307
+ break;
2308
+ default:
2309
+ return DefWindowProcW(hwnd, msg, wp, lp);
2310
+ }
2311
+ return 0;
2312
+ });
2313
+ RegisterClassExW(&wc);
2314
+ m_window = CreateWindowW(L"webview", L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
2315
+ CW_USEDEFAULT, 640, 480, nullptr, nullptr, hInstance,
2316
+ nullptr);
2317
+ if (m_window == nullptr)
2318
+ {
2319
+ return;
2320
+ }
2321
+ SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);
2322
+ }
2323
+ else
2324
+ {
2325
+ m_window = *(static_cast<HWND*>(window));
2326
+ }
2327
+
2328
+ ShowWindow(m_window, SW_SHOW);
2329
+ UpdateWindow(m_window);
2330
+ SetFocus(m_window);
2331
+
2332
+ auto cb = std::bind(&win32_edge_engine::on_message, this, std::placeholders::_1);
2333
+
2334
+ embed(m_window, debug, cb);
2335
+ resize(m_window);
2336
+ m_controller->MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC);
2337
+ }
2338
+
2339
+ virtual ~win32_edge_engine()
2340
+ {
2341
+ if (m_com_handler)
2342
+ {
2343
+ m_com_handler->Release();
2344
+ m_com_handler = nullptr;
2345
+ }
2346
+ if (m_webview)
2347
+ {
2348
+ m_webview->Release();
2349
+ m_webview = nullptr;
2350
+ }
2351
+ if (m_controller)
2352
+ {
2353
+ m_controller->Release();
2354
+ m_controller = nullptr;
2355
+ }
2356
+ }
2357
+
2358
+ win32_edge_engine(const win32_edge_engine& other) = delete;
2359
+ win32_edge_engine& operator=(const win32_edge_engine& other) = delete;
2360
+ win32_edge_engine(win32_edge_engine&& other) = delete;
2361
+ win32_edge_engine& operator=(win32_edge_engine&& other) = delete;
2362
+
2363
+ void run()
2364
+ {
2365
+ MSG msg;
2366
+ BOOL res;
2367
+ while ((res = GetMessage(&msg, nullptr, 0, 0)) != -1)
2368
+ {
2369
+ if (msg.hwnd)
2370
+ {
2371
+ TranslateMessage(&msg);
2372
+ DispatchMessage(&msg);
2373
+ continue;
2374
+ }
2375
+ if (msg.message == WM_APP)
2376
+ {
2377
+ auto f = (dispatch_fn_t*)(msg.lParam);
2378
+ (*f)();
2379
+ delete f;
2380
+ }
2381
+ else if (msg.message == WM_QUIT)
2382
+ {
2383
+ return;
2384
+ }
2385
+ }
2386
+ }
2387
+ void* window()
2388
+ {
2389
+ return (void*)m_window;
2390
+ }
2391
+ void terminate()
2392
+ {
2393
+ PostQuitMessage(0);
2394
+ }
2395
+ void dispatch(dispatch_fn_t f)
2396
+ {
2397
+ PostThreadMessage(m_main_thread, WM_APP, 0, (LPARAM) new dispatch_fn_t(f));
2398
+ }
2399
+
2400
+ void set_title(const std::string& title)
2401
+ {
2402
+ SetWindowTextW(m_window, widen_string(title).c_str());
2403
+ }
2404
+
2405
+ void set_size(int width, int height, int hints)
2406
+ {
2407
+ auto style = GetWindowLong(m_window, GWL_STYLE);
2408
+ if (hints == WEBVIEW_HINT_FIXED)
2409
+ {
2410
+ style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
2411
+ }
2412
+ else
2413
+ {
2414
+ style |= (WS_THICKFRAME | WS_MAXIMIZEBOX);
2415
+ }
2416
+ SetWindowLong(m_window, GWL_STYLE, style);
2417
+
2418
+ if (hints == WEBVIEW_HINT_MAX)
2419
+ {
2420
+ m_maxsz.x = width;
2421
+ m_maxsz.y = height;
2422
+ }
2423
+ else if (hints == WEBVIEW_HINT_MIN)
2424
+ {
2425
+ m_minsz.x = width;
2426
+ m_minsz.y = height;
2427
+ }
2428
+ else
2429
+ {
2430
+ RECT r;
2431
+ r.left = r.top = 0;
2432
+ r.right = width;
2433
+ r.bottom = height;
2434
+ AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, 0);
2435
+ SetWindowPos(m_window, nullptr, r.left, r.top, r.right - r.left,
2436
+ r.bottom - r.top,
2437
+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_FRAMECHANGED);
2438
+ resize(m_window);
2439
+ }
2440
+ }
2441
+
2442
+ void navigate(const std::string& url)
2443
+ {
2444
+ auto wurl = widen_string(url);
2445
+ m_webview->Navigate(wurl.c_str());
2446
+ }
2447
+
2448
+ void init(const std::string& js)
2449
+ {
2450
+ auto wjs = widen_string(js);
2451
+ m_webview->AddScriptToExecuteOnDocumentCreated(wjs.c_str(), nullptr);
2452
+ }
2453
+
2454
+ void eval(const std::string& js)
2455
+ {
2456
+ auto wjs = widen_string(js);
2457
+ m_webview->ExecuteScript(wjs.c_str(), nullptr);
2458
+ }
2459
+
2460
+ void add_navigate_listener(std::function<void(const std::string&, void*)> callback,
2461
+ void* arg)
2462
+ {
2463
+ m_com_handler->add_navigate_listener(callback, arg);
2464
+ }
2465
+
2466
+ void add_scheme_handler(const std::string& scheme,
2467
+ std::function<void(const std::string&, void*)> callback,
2468
+ void* arg)
2469
+ {
2470
+ // TODO: Implement
2471
+ }
2472
+
2473
+ void set_html(const std::string& html)
2474
+ {
2475
+ m_webview->NavigateToString(widen_string(html).c_str());
2476
+ }
2477
+
2478
+ private:
2479
+ bool embed(HWND wnd, bool debug, msg_cb_t cb)
2480
+ {
2481
+ std::atomic_flag flag = ATOMIC_FLAG_INIT;
2482
+ flag.test_and_set();
2483
+
2484
+ wchar_t currentExePath[MAX_PATH];
2485
+ GetModuleFileNameW(nullptr, currentExePath, MAX_PATH);
2486
+ wchar_t* currentExeName = PathFindFileNameW(currentExePath);
2487
+
2488
+ wchar_t dataPath[MAX_PATH];
2489
+ if (!SUCCEEDED(SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, 0, dataPath)))
2490
+ {
2491
+ return false;
2492
+ }
2493
+ wchar_t userDataFolder[MAX_PATH];
2494
+ PathCombineW(userDataFolder, dataPath, currentExeName);
2495
+
2496
+ m_com_handler = new webview2_com_handler(
2497
+ wnd, cb,
2498
+ [&](ICoreWebView2Controller* controller, ICoreWebView2* webview)
2499
+ {
2500
+ if (!controller || !webview)
2501
+ {
2502
+ flag.clear();
2503
+ return;
2504
+ }
2505
+ controller->AddRef();
2506
+ webview->AddRef();
2507
+ m_controller = controller;
2508
+ m_webview = webview;
2509
+ flag.clear();
2510
+ });
2511
+
2512
+ m_com_handler->set_attempt_handler(
2513
+ [&]
2514
+ {
2515
+ return m_webview2_loader.create_environment_with_options(
2516
+ nullptr, userDataFolder, nullptr, m_com_handler);
2517
+ });
2518
+ m_com_handler->try_create_environment();
2519
+
2520
+ MSG msg = {};
2521
+ while (flag.test_and_set() && GetMessage(&msg, nullptr, 0, 0))
2522
+ {
2523
+ TranslateMessage(&msg);
2524
+ DispatchMessage(&msg);
2525
+ }
2526
+ if (!m_controller || !m_webview)
2527
+ {
2528
+ return false;
2529
+ }
2530
+ ICoreWebView2Settings* settings = nullptr;
2531
+ auto res = m_webview->get_Settings(&settings);
2532
+ if (res != S_OK)
2533
+ {
2534
+ return false;
2535
+ }
2536
+ res = settings->put_AreDevToolsEnabled(debug ? TRUE : FALSE);
2537
+ if (res != S_OK)
2538
+ {
2539
+ return false;
2540
+ }
2541
+ init("window.external={invoke:s=>window.chrome.webview.postMessage(s)}");
2542
+ return true;
2543
+ }
2544
+
2545
+ void resize(HWND wnd)
2546
+ {
2547
+ if (m_controller == nullptr)
2548
+ {
2549
+ return;
2550
+ }
2551
+ RECT bounds;
2552
+ GetClientRect(wnd, &bounds);
2553
+ m_controller->put_Bounds(bounds);
2554
+ }
2555
+
2556
+ bool is_webview2_available() const noexcept
2557
+ {
2558
+ LPWSTR version_info = nullptr;
2559
+ auto res =
2560
+ m_webview2_loader.get_available_browser_version_string(nullptr, &version_info);
2561
+ // The result will be equal to HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)
2562
+ // if the WebView2 runtime is not installed.
2563
+ auto ok = SUCCEEDED(res) && version_info;
2564
+ if (version_info)
2565
+ {
2566
+ CoTaskMemFree(version_info);
2567
+ }
2568
+ return ok;
2569
+ }
2570
+
2571
+ virtual void on_message(const std::string& msg) = 0;
2572
+
2573
+ // The app is expected to call CoInitializeEx before
2574
+ // CreateCoreWebView2EnvironmentWithOptions.
2575
+ // Source:
2576
+ // https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environmentwithoptions
2577
+ com_init_wrapper m_com_init{ COINIT_APARTMENTTHREADED };
2578
+ HWND m_window = nullptr;
2579
+ POINT m_minsz = POINT{ 0, 0 };
2580
+ POINT m_maxsz = POINT{ 0, 0 };
2581
+ DWORD m_main_thread = GetCurrentThreadId();
2582
+ ICoreWebView2* m_webview = nullptr;
2583
+ ICoreWebView2Controller* m_controller = nullptr;
2584
+ webview2_com_handler* m_com_handler = nullptr;
2585
+ mswebview2::loader m_webview2_loader;
2586
+ };
2587
+
2588
+ } // namespace detail
2589
+
2590
+ using browser_engine = detail::win32_edge_engine;
2591
+
2592
+ } // namespace webview
2593
+
2594
+ #endif /* WEBVIEW_GTK, WEBVIEW_COCOA, WEBVIEW_EDGE */
2595
+
2596
+ namespace webview
2597
+ {
2598
+
2599
+ class webview : public browser_engine
2600
+ {
2601
+ public:
2602
+ webview(bool debug = false, void* wnd = nullptr) : browser_engine(debug, wnd)
2603
+ {
2604
+ }
2605
+
2606
+ void navigate(const std::string& url)
2607
+ {
2608
+ if (url.empty())
2609
+ {
2610
+ browser_engine::navigate("about:blank");
2611
+ return;
2612
+ }
2613
+ browser_engine::navigate(url);
2614
+ }
2615
+
2616
+ using binding_t = std::function<void(std::string, std::string, void*)>;
2617
+ class binding_ctx_t
2618
+ {
2619
+ public:
2620
+ binding_ctx_t(binding_t callback, void* arg) : callback(callback), arg(arg)
2621
+ {
2622
+ }
2623
+ // This function is called upon execution of the bound JS function
2624
+ binding_t callback;
2625
+ // This user-supplied argument is passed to the callback
2626
+ void* arg;
2627
+ };
2628
+
2629
+ using sync_binding_t = std::function<std::string(std::string)>;
2630
+
2631
+ // Synchronous bind
2632
+ void bind(const std::string& name, sync_binding_t fn)
2633
+ {
2634
+ auto wrapper = [this, fn](const std::string& seq, const std::string& req, void* /*arg*/)
2635
+ { resolve(seq, 0, fn(req)); };
2636
+ bind(name, wrapper, nullptr);
2637
+ }
2638
+
2639
+ // Asynchronous bind
2640
+ void bind(const std::string& name, binding_t fn, void* arg)
2641
+ {
2642
+ if (bindings.count(name) > 0)
2643
+ {
2644
+ return;
2645
+ }
2646
+ bindings.emplace(name, binding_ctx_t(fn, arg));
2647
+ auto js = "(function() { var name = '" + name + "';" + R""(
2648
+ var RPC = window._rpc = (window._rpc || {nextSeq: 1});
2649
+ window[name] = function() {
2650
+ var seq = RPC.nextSeq++;
2651
+ var promise = new Promise(function(resolve, reject) {
2652
+ RPC[seq] = {
2653
+ resolve: resolve,
2654
+ reject: reject,
2655
+ };
2656
+ });
2657
+ window.external.invoke(JSON.stringify({
2658
+ id: seq,
2659
+ method: name,
2660
+ params: Array.prototype.slice.call(arguments),
2661
+ }));
2662
+ return promise;
2663
+ }
2664
+ })())"";
2665
+ init(js);
2666
+ eval(js);
2667
+ }
2668
+
2669
+ void unbind(const std::string& name)
2670
+ {
2671
+ auto found = bindings.find(name);
2672
+ if (found != bindings.end())
2673
+ {
2674
+ auto js = "delete window['" + name + "'];";
2675
+ init(js);
2676
+ eval(js);
2677
+ bindings.erase(found);
2678
+ }
2679
+ }
2680
+
2681
+ void resolve(const std::string& seq, int status, const std::string& result)
2682
+ {
2683
+ dispatch(
2684
+ [seq, status, result, this]()
2685
+ {
2686
+ if (status == 0)
2687
+ {
2688
+ eval("window._rpc[" + seq + "].resolve(" + result +
2689
+ "); delete window._rpc[" + seq + "]");
2690
+ }
2691
+ else
2692
+ {
2693
+ eval("window._rpc[" + seq + "].reject(" + result +
2694
+ "); delete window._rpc[" + seq + "]");
2695
+ }
2696
+ });
2697
+ }
2698
+
2699
+ private:
2700
+ void on_message(const std::string& msg) override
2701
+ {
2702
+ auto seq = detail::json_parse(msg, "id", 0);
2703
+ auto name = detail::json_parse(msg, "method", 0);
2704
+ auto args = detail::json_parse(msg, "params", 0);
2705
+ auto found = bindings.find(name);
2706
+ if (found == bindings.end())
2707
+ {
2708
+ return;
2709
+ }
2710
+ const auto& context = found->second;
2711
+ context.callback(seq, args, context.arg);
2712
+ }
2713
+
2714
+ std::map<std::string, binding_ctx_t> bindings;
2715
+ };
2716
+ } // namespace webview
2717
+
2718
+ WEBVIEW_API webview_t webview_create(int debug, void* wnd)
2719
+ {
2720
+ auto w = new webview::webview(debug, wnd);
2721
+ if (!w->window())
2722
+ {
2723
+ delete w;
2724
+ return nullptr;
2725
+ }
2726
+ return w;
2727
+ }
2728
+
2729
+ WEBVIEW_API void webview_destroy(webview_t w)
2730
+ {
2731
+ delete static_cast<webview::webview*>(w);
2732
+ }
2733
+
2734
+ WEBVIEW_API void webview_run(webview_t w)
2735
+ {
2736
+ static_cast<webview::webview*>(w)->run();
2737
+ }
2738
+
2739
+ WEBVIEW_API void webview_terminate(webview_t w)
2740
+ {
2741
+ static_cast<webview::webview*>(w)->terminate();
2742
+ }
2743
+
2744
+ WEBVIEW_API void webview_dispatch(webview_t w, void (*fn)(webview_t, void*), void* arg)
2745
+ {
2746
+ static_cast<webview::webview*>(w)->dispatch([=]() { fn(w, arg); });
2747
+ }
2748
+
2749
+ WEBVIEW_API void* webview_get_window(webview_t w)
2750
+ {
2751
+ return static_cast<webview::webview*>(w)->window();
2752
+ }
2753
+
2754
+ WEBVIEW_API void webview_set_title(webview_t w, const char* title)
2755
+ {
2756
+ static_cast<webview::webview*>(w)->set_title(title);
2757
+ }
2758
+
2759
+ WEBVIEW_API void webview_set_size(webview_t w, int width, int height, int hints)
2760
+ {
2761
+ static_cast<webview::webview*>(w)->set_size(width, height, hints);
2762
+ }
2763
+
2764
+ WEBVIEW_API void webview_navigate(webview_t w, const char* url)
2765
+ {
2766
+ static_cast<webview::webview*>(w)->navigate(url);
2767
+ }
2768
+
2769
+ WEBVIEW_API void webview_set_html(webview_t w, const char* html)
2770
+ {
2771
+ static_cast<webview::webview*>(w)->set_html(html);
2772
+ }
2773
+
2774
+ WEBVIEW_API void webview_init(webview_t w, const char* js)
2775
+ {
2776
+ static_cast<webview::webview*>(w)->init(js);
2777
+ }
2778
+
2779
+ WEBVIEW_API void webview_eval(webview_t w, const char* js)
2780
+ {
2781
+ static_cast<webview::webview*>(w)->eval(js);
2782
+ }
2783
+
2784
+ WEBVIEW_API void webview_bind(webview_t w, const char* name,
2785
+ void (*fn)(const char* seq, const char* req, void* arg), void* arg)
2786
+ {
2787
+ static_cast<webview::webview*>(w)->bind(
2788
+ name,
2789
+ [=](const std::string& seq, const std::string& req, void* arg)
2790
+ { fn(seq.c_str(), req.c_str(), arg); },
2791
+ arg);
2792
+ }
2793
+
2794
+ WEBVIEW_API void webview_unbind(webview_t w, const char* name)
2795
+ {
2796
+ static_cast<webview::webview*>(w)->unbind(name);
2797
+ }
2798
+
2799
+ WEBVIEW_API void webview_return(webview_t w, const char* seq, int status, const char* result)
2800
+ {
2801
+ static_cast<webview::webview*>(w)->resolve(seq, status, result);
2802
+ }
2803
+
2804
+ WEBVIEW_API const webview_version_info_t* webview_version()
2805
+ {
2806
+ return &webview::detail::library_version_info;
2807
+ }
2808
+
2809
+ #endif /* WEBVIEW_HEADER */
2810
+ #endif /* __cplusplus */
2811
+ #endif /* WEBVIEW_H */