Move everything under kotlin-native folder

I was forced to manually do update the following files, because otherwise
they would be ignored according .gitignore settings. Probably they
should be deleted from repo.

Interop/.idea/compiler.xml
Interop/.idea/gradle.xml
Interop/.idea/libraries/Gradle__org_jetbrains_kotlin_kotlin_runtime_1_0_3.xml
Interop/.idea/libraries/Gradle__org_jetbrains_kotlin_kotlin_stdlib_1_0_3.xml
Interop/.idea/modules.xml
Interop/.idea/modules/Indexer/Indexer.iml
Interop/.idea/modules/Runtime/Runtime.iml
Interop/.idea/modules/StubGenerator/StubGenerator.iml
backend.native/backend.native.iml
backend.native/bc.frontend/bc.frontend.iml
backend.native/cli.bc/cli.bc.iml
backend.native/cli.bc/src/org/jetbrains/kotlin/cli/bc/K2Native.kt
backend.native/cli.bc/src/org/jetbrains/kotlin/cli/bc/K2NativeCompilerArguments.kt
backend.native/tests/link/lib/foo.kt
backend.native/tests/link/lib/foo2.kt
backend.native/tests/teamcity-test.property
This commit is contained in:
Stanislav Erokhin
2020-10-27 21:00:28 +03:00
parent 91e4162dad
commit f624800b84
2830 changed files with 0 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
# Samples
This directory contains a set of samples demonstrating how one can work with Kotlin/Native. The samples can be
built using Gradle build tool. See `README.md` in sample directories to learn more about specific samples and
the building process.
* `androidNativeActivity` - Android Native Activity rendering 3D graphics using OpenGLES
* `calculator` - iOS Swift application, using Kotlin/Native code compiled into the framework
* `cocoapods` - A Kotlin/Native application using the `AFNetworking` library from CocoaPods.
* `csvparser` - simple CSV file parser and analyzer
* `echoServer` - TCP/IP echo server
* `gitchurn` - program interoperating with `libgit2` for GIT repository analysis
* `gtk` - GTK3 interoperability example
* `html5Canvas` - WebAssembly example
* `libcurl` - using of FTP/HTTP/HTTPS client library `libcurl`
* `nonBlockingEchoServer` - multi-client TCP/IP echo server using co-routines
* `objc` - AppKit Objective-C interoperability example for macOS
* `opengl` - OpenGL/GLUT teapot example
* `python_extension` - Python extension written in Kotlin/Native
* `tensorflow` - simple client for TensorFlow Machine Intelligence library
* `tetris` - Tetris game implementation (using SDL2 for rendering)
* `uikit` - UIKit Objective-C interoperability example for iOS
* `videoplayer` - SDL and FFMPEG-based video and audio player
* `win32` - trivial Win32 GUI application
* `workers` - example of using workers API
**Note**: If the samples are built from a source tree (not from a distribution archive) the compiler built from
the sources is used. So you must build the compiler and the necessary platform libraries by running
`./gradlew bundle` from the Kotlin/Native root directory before building samples (see
[README.md](https://github.com/JetBrains/kotlin-native/blob/master/README.md) for details).
Alternatively you may remove a line `kotlin.native.home=<...>` from all `gradle.properties` files.
In this case the Gradle plugin downloads and uses a default compiler for this plugin version.
One may also build all the samples with one command. To build them using Gradle run:
./gradlew buildAllSamples
@@ -0,0 +1,22 @@
# Android Native Activity
This example shows how to build an Android Native Activity. Also, we provide an example
bridging mechanism for the Java APIs, callable from Native side.
The example will render a textured dodecahedron using OpenGL ES library. It can be rotated with fingers.
Please make sure that Android SDK version 28 is installed, using Android SDK manager in Android Studio.
See https://developer.android.com/studio/index.html for more details on Android Studio or
`$ANDROID_HOME/tools/bin/sdkmanager "platforms;android-28" "build-tools;28.0.3"` from command line.
We use JniBridge to call vibration service on the Java side for short tremble on startup.
To build use `ANDROID_HOME=<your path to android sdk> ../gradlew assemble`.
Run `$ANDROID_HOME/platform-tools/adb install -r build/outputs/apk/debug/androidNativeActivity-debug.apk`
to deploy the apk on the Android device or emulator.
Note that "Emulated Performance - Graphics" in AVD manager must be set to "Software - GLES 2.0".
Note: If you are importing project to IDEA for the first time, you might need to put `local.properties` file
with the following content:
sdk.dir=<your path to Android SDK>
@@ -0,0 +1,108 @@
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTargetPreset
import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType
repositories {
google()
jcenter()
mavenCentral()
maven("https://dl.bintray.com/kotlin/kotlin-dev")
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
plugins {
kotlin("multiplatform")
id("com.android.application") version("3.6.0")
}
val appDir = buildDir.resolve("Polyhedron")
val libsDir = appDir.resolve("libs")
// Set to true to build only for the simulator.
val simulatorOnly = true
val androidPresets = mapOf(
"arm32" to ("androidNativeArm32" to "$libsDir/armeabi-v7a"),
"arm64" to ("androidNativeArm64" to "$libsDir/arm64-v8a"),
"x86" to ("androidNativeX86" to "$libsDir/x86"),
"x64" to ("androidNativeX64" to "$libsDir/x86_64")
)
android {
compileSdkVersion(28)
defaultConfig {
applicationId = "com.jetbrains.konan_activity2"
minSdkVersion(9)
targetSdkVersion(28)
ndk {
abiFilters("armeabi-v7a", "arm64-v8a", "x86", "x86_64")
}
}
sourceSets {
val main by getting {
setRoot("src/x86Main")
jniLibs.srcDir(libsDir)
}
}
}
kotlin {
androidPresets.forEach { (targetName, presetInfo) ->
val (presetName, _) = presetInfo
val preset = kotlin.presets[presetName] as KotlinNativeTargetPreset
targetFromPreset(preset, targetName) {
binaries {
executable {
entryPoint = "sample.androidnative.main"
}
}
compilations["main"].cinterops {
val bmpformat by creating
}
}
}
sourceSets {
val x86Main by getting
if (!simulatorOnly) {
val x64Main by getting
val arm32Main by getting
val arm64Main by getting
arm32Main.dependsOn(x86Main)
arm64Main.dependsOn(x86Main)
x64Main.dependsOn(x86Main)
}
}
}
// Disable generating Kotlin metadata.
tasks.compileKotlinMetadata {
enabled = false
}
afterEvaluate {
androidPresets.forEach { (targetName, presetInfo) ->
val target = kotlin.targets[targetName] as KotlinNativeTarget
val (_, libDir) = presetInfo
NativeBuildType.values().forEach {
val executable = target.binaries.getExecutable(it)
val linkTask = executable.linkTask
val binaryFile = executable.outputFile
linkTask.doLast {
copy {
from(binaryFile)
into(libDir)
rename { "libpoly.so" }
}
}
tasks.preBuild {
dependsOn(linkTask)
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )
$DIR/../gradlew -p $DIR assemble
@@ -0,0 +1,15 @@
kotlin.code.style=official
# Run parallel builds in Gradle:
org.gradle.parallel=true
org.gradle.workers.max=4
# Pin Kotlin version:
# CHANGE_VERSION_WITH_RELEASE
kotlin_version=1.4.10
# Use custom Kotlin/Native home:
kotlin.native.home=../../dist
# Increase memory for in-process compiler execution.
org.gradle.jvmargs=-Xmx3g
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
+89
View File
@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,22 @@
pluginManagement {
val kotlin_version: String by settings
resolutionStrategy {
eachPlugin {
if (requested.id.id == "org.jetbrains.kotlin.multiplatform") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
}
if (requested.id.id == "com.android.application") {
useModule("com.android.tools.build:gradle:${requested.version}")
}
}
}
repositories {
gradlePluginPortal()
google()
jcenter()
mavenCentral()
maven("https://dl.bintray.com/kotlin/kotlin-dev")
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
}
@@ -0,0 +1,16 @@
package = sample.androidnative.bmpformat
---
#include <stdint.h>
typedef struct __attribute__((packed)) {
uint16_t magic;
uint32_t size;
uint32_t zero;
uint8_t padding1[8];
int32_t width;
int32_t height;
uint8_t padding2[2];
uint16_t bits;
uint8_t padding3[24];
} BMPHeader;
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="polyhedron"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<!-- This .apk has no Java code itself, so set hasCode to false. -->
<application
android:allowBackup="false"
android:fullBackupContent="false"
android:icon="@mipmap/konan_activity"
android:label="@string/app_name"
android:hasCode="false">
<!-- Our activity is the built-in NativeActivity framework class.
This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<!-- Tell NativeActivity the name of our .so -->
<meta-data android:name="android.app.lib_name"
android:value="poly" />
<meta-data android:name="android.app.func_name"
android:value="Konan_main" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- END_INCLUDE(manifest) -->
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

@@ -0,0 +1,7 @@
package sample.androidnative
import kotlinx.cinterop.*
import sample.androidnative.bmpformat.BMPHeader
val BMPHeader.data
get() = (ptr.reinterpret<ByteVar>() + sizeOf<BMPHeader>()) as CArrayPointer<ByteVar>
@@ -0,0 +1,62 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
/**
* Disposable class manages and owns all its native resources. It allocates some resources
* during construction and may allocate some additional resources during operation.
* It must free all its resource once [dispose] is invoked. "Disposed" is a final state of the disposable
* class. It is not supposed to be used after being disposed.
*/
interface Disposable {
/**
* Disposes all native resources owned by this class. This function must be invoked
* exactly once as the last operation on the corresponding class.
*/
fun dispose()
}
/**
* Helper class to implement [Disposable] interface. It contains an [arena] for native
* memory allocations and a number of helper methods to simplify management of other
* kinds of native resources.
*
* It is important to wrap all potentially exception-throwing code in the class constructor
* into [tryConstruct] invocation, because, when object construction fails with exception,
* it ensures that all the resource that were allocated so far will get freed.
*/
abstract class DisposableContainer : Disposable {
val arena = Arena()
override fun dispose() {
arena.clear()
}
inline fun <T> tryConstruct(init: () -> T): T =
try { init() }
catch (e: Throwable) {
dispose()
throw e
}
inline fun <T> disposable(
message: String = "disposable",
create: () -> T?,
crossinline dispose: (T) -> Unit
): T =
tryConstruct {
create()?.also {
arena.defer { dispose(it) }
} ?: throw Error(message)
}
inline fun <T : Disposable> disposable(create: () -> T): T =
disposable(
create = create,
dispose = { it.dispose() })
}
@@ -0,0 +1,226 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
import platform.android.*
import platform.posix.*
import platform.gles3.*
import platform.linux.*
fun logError(message: String) {
__android_log_write(ANDROID_LOG_ERROR.convert(), "KonanActivity", message)
}
fun logInfo(message: String) {
__android_log_write(ANDROID_LOG_INFO.convert(), "KonanActivity", message)
}
private fun getUnixError() = strerror(posix_errno())!!.toKString()
const val LOOPER_ID_INPUT = 2
inline fun <reified T : CPointed> CPointer<*>?.dereferenceAs(): T = this!!.reinterpret<T>().pointed
class Engine(val state: NativeActivityState) : DisposableContainer() {
private val renderer = Renderer(this, state.activity!!.pointed, state.savedState)
private var queue: CPointer<AInputQueue>? = null
private var rendererState: COpaquePointer? = null
private var currentPoint = Vector2.Zero
private var startPoint = Vector2.Zero
private var startTime = 0.0f
private var animationEndTime = 0.0f
private var velocity = Vector2.Zero
private var acceleration = Vector2.Zero
private var needRedraw = true
private var animating = false
private val pointerSize = CPointerVar.size
private val now = arena.alloc<timespec>()
private val eventPointer = arena.alloc<COpaquePointerVar>()
private val inputEvent = arena.alloc<CPointerVar<AInputEvent>>()
fun mainLoop() {
callToManagedAPI()
val fd = arena.alloc<IntVar>()
while (true) {
// Process events.
eventLoop@ while (true) {
val id = ALooper_pollAll(if (needRedraw || animating) 0 else -1, fd.ptr, null, null)
if (id < 0) break@eventLoop
when (id) {
LOOPER_ID_SYS -> if (!processSysEvent(fd)) return // An error occured.
LOOPER_ID_INPUT -> processUserInput()
else -> logError("Unprocessed event: $id")
}
}
when {
animating -> {
val elapsed = getTime() - startTime
if (elapsed >= animationEndTime) {
animating = false
} else {
move(startPoint + velocity * elapsed + acceleration * (elapsed * elapsed * 0.5f))
renderer.draw()
}
}
needRedraw -> renderer.draw()
}
}
}
override fun dispose() {
renderer.destroy()
super.dispose()
}
private val jniBrigde = JniBridge(state.activity!!.pointed.vm!!)
private fun callToManagedAPI() = jniBrigde.withLocalFrame {
// Actually, this is a context pointer.
val context = JniObject(state.activity!!.pointed.clazz!!)
val contextClass = FindClass("android/content/Context")
val getSystemServiceMethod = GetMethodID(
contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;")!!
val vibrator = CallObjectMethod(context, getSystemServiceMethod, "vibrator")
if (vibrator != null) {
val vibratorClass = FindClass("android/os/Vibrator")
val vibrateMethod = GetMethodID(vibratorClass, "vibrate", "(J)V")!!
CallVoidMethod(vibrator, vibrateMethod, 500L)
}
}
private fun processSysEvent(fd: IntVar): Boolean {
val readBytes = read(fd.value, eventPointer.ptr, pointerSize.convert()).toLong()
if (readBytes != pointerSize.toLong()) {
logError("Failure reading event, $readBytes read: ${getUnixError()}")
return true
}
try {
val event = eventPointer.value.dereferenceAs<NativeActivityEvent>()
println("got ${event.eventKind}")
when (event.eventKind) {
NativeActivityEventKind.START -> {
logInfo("Activity started")
renderer.start()
}
NativeActivityEventKind.STOP -> {
renderer.stop()
}
NativeActivityEventKind.DESTROY -> {
rendererState?.let {
free(it)
rendererState = null
}
return false
}
NativeActivityEventKind.NATIVE_WINDOW_CREATED -> {
val windowEvent = eventPointer.value.dereferenceAs<NativeActivityWindowEvent>()
if (!renderer.initialize(windowEvent.window!!))
return false
logInfo("Renderer initialized")
renderer.draw()
}
NativeActivityEventKind.INPUT_QUEUE_CREATED -> {
val queueEvent = eventPointer.value.dereferenceAs<NativeActivityQueueEvent>()
if (queue != null)
AInputQueue_detachLooper(queue)
queue = queueEvent.queue
AInputQueue_attachLooper(queue, state.looper, LOOPER_ID_INPUT, null, null)
}
NativeActivityEventKind.INPUT_QUEUE_DESTROYED -> {
val queueEvent = eventPointer.value.dereferenceAs<NativeActivityQueueEvent>()
AInputQueue_detachLooper(queueEvent.queue)
}
NativeActivityEventKind.NATIVE_WINDOW_DESTROYED -> {
renderer.destroy()
}
NativeActivityEventKind.SAVE_INSTANCE_STATE -> {
val saveStateEvent = eventPointer.value.dereferenceAs<NativeActivitySaveStateEvent>()
val state = renderer.getState()
val dataSize = state.second
rendererState = realloc(rendererState, dataSize.convert())
memcpy(rendererState, state.first, dataSize.convert())
logInfo("Saving instance state to $rendererState: $dataSize bytes")
saveStateEvent.savedState = rendererState
saveStateEvent.savedStateSize = dataSize.convert()
}
}
} finally {
notifySysEventProcessed()
}
return true
}
private fun getTime(): Float {
clock_gettime(CLOCK_MONOTONIC, now.ptr)
return now.tv_sec + now.tv_nsec / 1_000_000_000.0f
}
private fun getEventPoint(event: CPointer<AInputEvent>?, i: Int) =
Vector2(AMotionEvent_getRawX(event, i.convert()), AMotionEvent_getRawY(event, i.convert()))
private fun getEventTime(event: CPointer<AInputEvent>?) =
AMotionEvent_getEventTime(event) / 1_000_000_000.0f
private fun processUserInput(): Unit {
if (AInputQueue_getEvent(queue, inputEvent.ptr) < 0) {
logError("Failure reading input event")
return
}
val event = inputEvent.value
val eventType = AInputEvent_getType(event)
if (eventType.toUInt() == AINPUT_EVENT_TYPE_MOTION) {
val action = AKeyEvent_getAction(event).toUInt() and AMOTION_EVENT_ACTION_MASK
when (action) {
AMOTION_EVENT_ACTION_DOWN -> {
animating = false
currentPoint = getEventPoint(event, 0)
startTime = getEventTime(event)
startPoint = currentPoint
}
AMOTION_EVENT_ACTION_UP -> {
val endPoint = getEventPoint(event, 0)
val endTime = getEventTime(event)
animating = true
velocity = (endPoint - startPoint) / (endTime - startTime + 1e-9f)
if (velocity.length > renderer.screen.length)
velocity = velocity * (renderer.screen.length / velocity.length)
acceleration = velocity.normalized() * (-renderer.screen.length * 0.5f)
animationEndTime = velocity.length / acceleration.length
startPoint = endPoint
startTime = endTime
move(endPoint)
}
AMOTION_EVENT_ACTION_MOVE -> {
val numberOfPointers = AMotionEvent_getPointerCount(event).toInt()
for (i in 0 until numberOfPointers)
move(getEventPoint(event, i))
}
}
}
AInputQueue_finishEvent(queue, event, 1)
}
private fun move(newPoint: Vector2) {
renderer.rotateBy(newPoint - currentPoint)
currentPoint = newPoint
}
}
@@ -0,0 +1,110 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
import platform.android.*
data class JniClass(val jclass: jclass)
data class JniObject(val jobject: jobject)
data class JniMethod(val jmethod: jmethodID)
fun asJniClass(jclass: jclass?) =
if (jclass != null) JniClass(jclass) else null
fun asJniObject(jobject: jobject?) =
if (jobject != null) JniObject(jobject) else null
fun asJniMethod(jmethodID: jmethodID?) =
if (jmethodID != null) JniMethod(jmethodID) else null
class JniBridge(val vm: CPointer<JavaVMVar>) {
private val vmFunctions: JNIInvokeInterface = vm.pointed.pointed!!
val jniEnv = memScoped {
val envStorage = alloc<CPointerVar<JNIEnvVar>>()
if (vmFunctions.AttachCurrentThreadAsDaemon!!(vm, envStorage.ptr, null) != 0)
throw Error("Cannot attach thread to the VM")
envStorage.value!!
}
private val envFunctions: JNINativeInterface = jniEnv.pointed.pointed!!
// JNI operations.
private val fNewStringUTF = envFunctions.NewStringUTF!!
private val fFindClass = envFunctions.FindClass!!
private val fGetMethodID = envFunctions.GetMethodID!!
private val fCallVoidMethodA = envFunctions.CallVoidMethodA!!
private val fCallObjectMethodA = envFunctions.CallObjectMethodA!!
private val fExceptionCheck = envFunctions.ExceptionCheck!!
private val fExceptionDescribe = envFunctions.ExceptionDescribe!!
private val fExceptionClear = envFunctions.ExceptionClear!!
val fPushLocalFrame = envFunctions.PushLocalFrame!!
val fPopLocalFrame = envFunctions.PopLocalFrame!!
private fun check() {
if (fExceptionCheck(jniEnv) != 0.toUByte()) {
fExceptionDescribe(jniEnv)
fExceptionClear(jniEnv)
throw Error("JVM exception thrown")
}
}
fun toJString(string: String) = memScoped {
val result = asJniObject(fNewStringUTF(jniEnv, string.cstr.ptr))
check()
result
}
fun toJValues(arguments: Array<out Any?>, scope: MemScope): CPointer<jvalue>? {
val result = scope.allocArray<jvalue>(arguments.size)
arguments.mapIndexed { index, it ->
when (it) {
null -> result[index].l = null
is JniObject -> result[index].l = it.jobject
is String -> result[index].l = toJString(it)?.jobject
is Int -> result[index].i = it
is Long -> result[index].j = it
else -> throw Error("Unsupported conversion for ${it::class.simpleName}")
}
}
return result
}
fun FindClass(name: String) = memScoped {
val result = asJniClass(fFindClass(jniEnv, name.cstr.ptr))
check()
result
}
fun GetMethodID(clazz: JniClass?, name: String, signature: String) = memScoped {
val result = asJniMethod(fGetMethodID(jniEnv, clazz?.jclass, name.cstr.ptr, signature.cstr.ptr))
check()
result
}
fun CallVoidMethod(receiver: JniObject?, method: JniMethod, vararg arguments: Any?) = memScoped {
fCallVoidMethodA(jniEnv, receiver?.jobject, method.jmethod,
toJValues(arguments, this@memScoped))
check()
}
fun CallObjectMethod(receiver: JniObject?, method: JniMethod, vararg arguments: Any?) = memScoped {
val result = asJniObject(fCallObjectMethodA(jniEnv, receiver?.jobject, method.jmethod,
toJValues(arguments, this@memScoped)))
check()
result
}
// Usually, use this
inline fun <T> withLocalFrame(block: JniBridge.() -> T): T {
if (fPushLocalFrame(jniEnv, 0) < 0)
throw Error("Cannot push new local frame")
try {
return block()
} finally {
fPopLocalFrame(jniEnv, null)
}
}
}
@@ -0,0 +1,49 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
const val Zero = 0.0f
const val DodeA = 0.93417235896f // (Sqrt(5) + 1) / (2 * Sqrt(3))
const val DodeB = 0.35682208977f // (Sqrt(5) - 1) / (2 * Sqrt(3))
const val DodeC = 0.57735026919f // 1 / Sqrt(3)
const val IcosA = 0.52573111212f // Sqrt(5 - Sqrt(5)) / Sqrt(10)
const val IcosB = 0.85065080835f // Sqrt(5 + Sqrt(5)) / Sqrt(10)
enum class RegularPolyhedra(val vertices: Array<Vector3>, val faces: Array<ByteArray>) {
Dodecahedron(
arrayOf(
Vector3(-DodeA, Zero, DodeB), Vector3(-DodeA, Zero, -DodeB), Vector3(DodeA, Zero, -DodeB),
Vector3(DodeA, Zero, DodeB), Vector3(DodeB, -DodeA, Zero), Vector3(-DodeB, -DodeA, Zero),
Vector3(-DodeB, DodeA, Zero), Vector3(DodeB, DodeA, Zero), Vector3(Zero, DodeB, -DodeA),
Vector3(Zero, -DodeB, -DodeA), Vector3(Zero, -DodeB, DodeA), Vector3(Zero, DodeB, DodeA),
Vector3(-DodeC, -DodeC, DodeC), Vector3(-DodeC, -DodeC, -DodeC), Vector3(DodeC, -DodeC, -DodeC),
Vector3(DodeC, -DodeC, DodeC), Vector3(-DodeC, DodeC, DodeC), Vector3(-DodeC, DodeC, -DodeC),
Vector3(DodeC, DodeC, -DodeC), Vector3(DodeC, DodeC, DodeC)
),
arrayOf(
byteArrayOf(0, 12, 10, 11, 16), byteArrayOf(1, 17, 8, 9, 13), byteArrayOf(2, 14, 9, 8, 18),
byteArrayOf(3, 19, 11, 10, 15), byteArrayOf(4, 14, 2, 3, 15), byteArrayOf(5, 12, 0, 1, 13),
byteArrayOf(6, 17, 1, 0, 16), byteArrayOf(7, 19, 3, 2, 18), byteArrayOf(8, 17, 6, 7, 18),
byteArrayOf(9, 14, 4, 5, 13), byteArrayOf(10, 12, 5, 4, 15), byteArrayOf(11, 19, 7, 6, 16)
)),
Icosahedron(
arrayOf(
Vector3(-IcosA, Zero, IcosB), Vector3(IcosA, Zero, IcosB), Vector3(-IcosA, Zero, -IcosB),
Vector3(IcosA, Zero, -IcosB), Vector3(Zero, IcosB, IcosA), Vector3(Zero, IcosB, -IcosA),
Vector3(Zero, -IcosB, IcosA), Vector3(Zero, -IcosB, -IcosA), Vector3(IcosB, IcosA, Zero),
Vector3(-IcosB, IcosA, Zero), Vector3(IcosB, -IcosA, Zero), Vector3(-IcosB, -IcosA, Zero)
),
arrayOf(
byteArrayOf(1, 4, 0), byteArrayOf(4, 9, 0), byteArrayOf(4, 5, 9), byteArrayOf(8, 5, 4),
byteArrayOf(1, 8, 4), byteArrayOf(1, 10, 8), byteArrayOf(10, 3, 8), byteArrayOf(8, 3, 5),
byteArrayOf(3, 2, 5), byteArrayOf(3, 7, 2), byteArrayOf(3, 10, 7), byteArrayOf(10, 6, 7),
byteArrayOf(6, 11, 7), byteArrayOf(6, 0, 11), byteArrayOf(6, 1, 0), byteArrayOf(10, 1, 6),
byteArrayOf(11, 0, 9), byteArrayOf(2, 11, 9), byteArrayOf(5, 2, 9), byteArrayOf(11, 2, 7)
)
);
val verticesPerFace get() = faces[0].size
}
@@ -0,0 +1,302 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
import platform.android.*
import platform.egl.*
import platform.posix.*
import platform.gles.*
import sample.androidnative.bmpformat.BMPHeader
class Renderer(val container: DisposableContainer,
val nativeActivity: ANativeActivity,
val savedMatrix: COpaquePointer?) {
private var display: EGLDisplay? = null
private var surface: EGLSurface? = null
private var context: EGLContext? = null
private var initialized = false
var screen = Vector2.Zero
private val matrix = container.arena.allocArray<FloatVar>(16)
init {
if (savedMatrix != null) {
memcpy(matrix, savedMatrix, 16 * 4)
} else {
for (i in 0..3)
for (j in 0..3)
matrix[i * 4 + j] = if (i == j) 1.0f else 0.0f
}
}
fun initialize(window: CPointer<ANativeWindow>): Boolean {
with(container.arena) {
logInfo("Initializing context..")
display = eglGetDisplay(null)
if (display == null) {
logError("eglGetDisplay() returned error ${eglGetError()}")
return false
}
if (eglInitialize(display, null, null) == 0u) {
logError("eglInitialize() returned error ${eglGetError()}")
return false
}
val attribs = cValuesOf(
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
)
val numConfigs = alloc<EGLintVar>()
if (eglChooseConfig(display, attribs, null, 0, numConfigs.ptr) == 0u) {
throw Error("eglChooseConfig()#1 returned error ${eglGetError()}")
}
val supportedConfigs = allocArray<EGLConfigVar>(numConfigs.value)
if (eglChooseConfig(display, attribs, supportedConfigs, numConfigs.value, numConfigs.ptr) == 0u) {
throw Error("eglChooseConfig()#2 returned error ${eglGetError()}")
}
var configIndex = 0
while (configIndex < numConfigs.value) {
val r = alloc<EGLintVar>()
val g = alloc<EGLintVar>()
val b = alloc<EGLintVar>()
val d = alloc<EGLintVar>()
if (eglGetConfigAttrib(display, supportedConfigs[configIndex], EGL_RED_SIZE, r.ptr) != 0u &&
eglGetConfigAttrib (display, supportedConfigs[configIndex], EGL_GREEN_SIZE, g.ptr) != 0u &&
eglGetConfigAttrib(display, supportedConfigs[configIndex], EGL_BLUE_SIZE, b.ptr) != 0u &&
eglGetConfigAttrib(display, supportedConfigs[configIndex], EGL_DEPTH_SIZE, d.ptr) != 0u &&
r.value == 8 && g.value == 8 && b.value == 8 && d.value == 0) break
++configIndex
}
if (configIndex >= numConfigs.value)
configIndex = 0
surface = eglCreateWindowSurface(display, supportedConfigs[configIndex], window, null)
if (surface == null) {
throw Error("eglCreateWindowSurface() returned error ${eglGetError()}")
}
context = eglCreateContext(display, supportedConfigs[configIndex], null, null)
if (context == null) {
throw Error("eglCreateContext() returned error ${eglGetError()}")
}
if (eglMakeCurrent(display, surface, surface, context) == 0u) {
throw Error("eglMakeCurrent() returned error ${eglGetError()}")
}
val width = alloc<EGLintVar>()
val height = alloc<EGLintVar>()
if (eglQuerySurface(display, surface, EGL_WIDTH, width.ptr) == 0u
|| eglQuerySurface (display, surface, EGL_HEIGHT, height.ptr) == 0u) {
throw Error("eglQuerySurface() returned error ${eglGetError()}")
}
this@Renderer.screen = Vector2(width.value.toFloat(), height.value.toFloat())
glDisable(GL_DITHER)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST)
glClearColor(0.0f, 0.0f, 0.0f, 0.0f)
glEnable(GL_CULL_FACE)
glShadeModel(GL_SMOOTH)
glEnable(GL_DEPTH_TEST)
glViewport(0, 0, width.value, height.value)
val ratio = width.value.toFloat() / height.value
glMatrixMode(GL_PROJECTION)
checkErrors()
glLoadIdentity()
glFrustumf(-ratio, ratio, -1.0f, 1.0f, 1.0f, 10.0f)
glMatrixMode(GL_MODELVIEW)
checkErrors()
glTranslatef(0.0f, 0.0f, -2.0f)
glLightfv(GL_LIGHT0, GL_POSITION, cValuesOf(1.25f, 1.25f, -2.0f, 0.0f))
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_TEXTURE_2D)
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, cValuesOf(0.0f, 1.0f, 1.0f, 1.0f))
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, cValuesOf(0.3f, 0.3f, 0.3f, 1.0f))
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 30.0f)
loadTexture("kotlin_logo.bmp")
initialized = true
return true
}
}
fun checkErrors() {
val error = glGetError()
if (error.toInt() != GL_NO_ERROR)
throw Error("OpenGL error 0x${error.toInt().toString(16)}")
}
fun getState() = matrix to 16 * 4
fun rotateBy(vector: Vector2) {
if (!initialized) return
val length = vector.length
if (length < 1e-9f) return
val angle = 180 * length / screen.length
val x = -vector.y / length
val y = -vector.x / length
glPushMatrix()
glMatrixMode(GL_MODELVIEW)
checkErrors()
glLoadIdentity()
glRotatef(angle, x, y, 0.0f)
glMultMatrixf(matrix)
glGetFloatv(GL_MODELVIEW_MATRIX, matrix)
glPopMatrix()
}
private fun loadTexture(assetName: String): Unit = memScoped {
val asset = AAssetManager_open(nativeActivity.assetManager, assetName, AASSET_MODE_BUFFER.convert())
?: throw Error("Error opening asset $assetName")
println("loading texture $assetName")
try {
val length = AAsset_getLength(asset)
val buffer = allocArray<ByteVar>(length)
if (AAsset_read(asset, buffer, length.convert()) != length.toInt()) {
throw Error("Error reading asset")
}
with(buffer.reinterpret<BMPHeader>().pointed) {
if (magic != 0x4d42.toUShort() || zero != 0u || size != length.toUInt() || bits != 24.toUShort()) {
throw Error("Error parsing texture file")
}
val numberOfBytes = width * height * 3
// Swap BGR in bitmap to RGB.
for (i in 0 until numberOfBytes step 3) {
val t = data[i]
data[i] = data[i + 2]
data[i + 2] = t
}
println("loaded texture ${width}x${height}")
glBindTexture(GL_TEXTURE_2D, 1)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND.toFloat())
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, cValuesOf(1.0f, 1.0f, 1.0f, 1.0f))
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data)
}
} finally {
AAsset_close(asset)
}
}
private val texturePoints = arrayOf(
Vector2(0.0f, 0.2f), Vector2(0.0f, 0.8f), Vector2(0.6f, 1.0f), Vector2(1.0f, 0.5f), Vector2(0.8f, 0.0f)
)
private val scale = 1.25f
fun draw(): Unit {
if (!initialized) return
glPushMatrix()
glMatrixMode(GL_MODELVIEW)
checkErrors()
glMultMatrixf(matrix)
glClear((GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT).toUInt())
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY)
val polygon = RegularPolyhedra.Dodecahedron
val vertices = mutableListOf<Float>()
val texCoords = mutableListOf<Float>()
val triangles = mutableListOf<Byte>()
val normals = mutableListOf<Float>()
for (face in polygon.faces) {
val u = polygon.vertices[face[2].toInt()] - polygon.vertices[face[1].toInt()]
val v = polygon.vertices[face[0].toInt()] - polygon.vertices[face[1].toInt()]
val normal = u.crossProduct(v).normalized()
val copiedFace = ByteArray(face.size)
for (j in face.indices) {
copiedFace[j] = (vertices.size / 4).toByte()
polygon.vertices[face[j].toInt()].copyCoordinatesTo(vertices)
vertices.add(scale)
normal.copyCoordinatesTo(normals)
texturePoints[j].copyCoordinatesTo(texCoords)
}
for (j in 1..face.size - 2) {
triangles.add(copiedFace[0])
triangles.add(copiedFace[j])
triangles.add(copiedFace[j + 1])
}
}
memScoped {
glFrontFace(GL_CW)
glVertexPointer(4, GL_FLOAT, 0, vertices.toFloatArray().toCValues().ptr)
glTexCoordPointer(2, GL_FLOAT, 0, texCoords.toFloatArray().toCValues().ptr)
glNormalPointer(GL_FLOAT, 0, normals.toFloatArray().toCValues().ptr)
glDrawElements(GL_TRIANGLES, triangles.size, GL_UNSIGNED_BYTE, triangles.toByteArray().toCValues().ptr)
}
glPopMatrix()
if (eglSwapBuffers(display, surface) == 0u) {
val error = eglGetError()
if (error != EGL_BAD_SURFACE)
throw Error("eglSwapBuffers() returned error $error")
else {
if (eglMakeCurrent(display, surface, surface, context) == 0u) {
throw Error("Reinit eglMakeCurrent() returned error ${eglGetError()}")
}
if (eglSwapBuffers(display, surface) == 0u)
throw Error("Bad eglSwapBuffers() after surface reinit: ${eglGetError()}")
}
}
}
fun start() {
logInfo("Starting renderer.")
if (initialized) {
if (eglMakeCurrent(display, surface, surface, context) == 0u) {
throw Error("eglMakeCurrent() returned error ${eglGetError()}")
}
}
}
fun stop() {
logInfo("Stopping renderer..")
eglMakeCurrent(display, null, null, null)
}
fun destroy() {
if (!initialized) return
logInfo("Destroying renderer..")
eglMakeCurrent(display, null, null, null)
context?.let { eglDestroyContext(display, it) }
surface?.let { eglDestroySurface(display, it) }
display?.let { eglTerminate(display) }
display = null
surface = null
context = null
initialized = false
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
import platform.android.*
import platform.posix.*
class Vector2(val x: Float, val y: Float) {
val length by lazy { sqrtf(x * x + y * y) }
fun normalized(): Vector2 {
val len = length
return Vector2(x / len, y / len)
}
fun copyCoordinatesTo(arr: MutableList<Float>) {
arr.add(x)
arr.add(y)
}
operator fun minus(other: Vector2) = Vector2(x - other.x, y - other.y)
operator fun plus(other: Vector2) = Vector2(x + other.x, y + other.y)
operator fun times(other: Float) = Vector2(x * other, y * other)
operator fun div(other: Float) = Vector2(x / other, y / other)
companion object {
val Zero = Vector2(0.0f, 0.0f)
}
}
class Vector3(val x: Float, val y: Float, val z: Float) {
val length by lazy { sqrtf(x * x + y * y + z * z) }
fun crossProduct(other: Vector3): Vector3 =
Vector3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x)
fun normalized(): Vector3 {
val len = length
return Vector3(x / len, y / len, z / len)
}
fun copyCoordinatesTo(arr: MutableList<Float>) {
arr.add(x)
arr.add(y)
arr.add(z)
}
operator fun minus(other: Vector3) = Vector3(x - other.x, y - other.y, z - other.z)
operator fun plus(other: Vector3) = Vector3(x + other.x, y + other.y, z + other.z)
}
@@ -0,0 +1,24 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.androidnative
import kotlinx.cinterop.*
import platform.android.*
fun main() {
logInfo("Entering main().")
memScoped {
val state = alloc<NativeActivityState>()
getNativeActivityState(state.ptr)
val engine = Engine(state)
try {
engine.mainLoop()
} finally {
engine.dispose()
}
}
kotlin.system.exitProcess(0)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">KonanActivity</string>
</resources>
+74
View File
@@ -0,0 +1,74 @@
buildscript {
repositories {
mavenCentral()
maven("https://dl.bintray.com/kotlin/kotlin-dev")
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
val kotlin_version: String by rootProject
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
}
}
allprojects {
repositories {
mavenCentral()
maven("https://dl.bintray.com/kotlin/kotlin-dev")
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
}
val hostOs = System.getProperty("os.name")
val isMacos = hostOs == "Mac OS X"
val isLinux = hostOs == "Linux"
val isWindows = hostOs.startsWith("Windows")
val localRepo = rootProject.file("build/.m2-local")
val clean by tasks.creating(Delete::class) {
delete(localRepo)
}
val buildSh by tasks.creating(Exec::class) {
errorOutput = System.out
isIgnoreExitValue = true
workingDir = projectDir
enabled = !isWindows
if (isLinux || isMacos) {
commandLine = listOf(projectDir.resolve("build.sh").toString())
}
}
val buildSamplesWithPlatformLibs by tasks.creating {
dependsOn(":csvparser:assemble")
dependsOn(":curl:assemble")
dependsOn(":echoServer:assemble")
dependsOn(":globalState:assemble")
dependsOn(":html5Canvas:assemble")
dependsOn(":workers:assemble")
if (isMacos || isLinux) {
dependsOn(":nonBlockingEchoServer:assemble")
dependsOn(":tensorflow:assemble")
}
if (isMacos) {
dependsOn(":objc:assemble")
dependsOn(":opengl:assemble")
dependsOn(":uikit:assemble")
dependsOn(":coverage:assemble")
dependsOn(":watchos:assemble")
}
if (isWindows) {
dependsOn(":win32:assemble")
}
}
val buildAllSamples by tasks.creating {
subprojects.forEach {
dependsOn("${it.path}:assemble")
}
finalizedBy(buildSh)
}
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
EXCLUDE=()
BUILD_SCRIPT="build.sh"
function isExcluded() {
CHECKED="${1}"
for VALUE in $EXCLUDE; do
if [ "x$CHECKED" == "x$VALUE" ]; then
return 0
fi
done
return -1
}
for SAMPLE_DIR in *; do
if [ -d "$SAMPLE_DIR" ] && [ -e "$SAMPLE_DIR/$BUILD_SCRIPT" ]; then
echo
echo "======================================================"
date
echo "Building a sample: $SAMPLE_DIR."
if ! isExcluded "$SAMPLE_DIR"; then
bash "$SAMPLE_DIR/$BUILD_SCRIPT" || (echo "Cannot build a sample: $SAMPLE_DIR. See log for details." && exit 1)
else
echo "The sample excluded."
fi
fi
done
@@ -0,0 +1 @@
xcuserdata
@@ -0,0 +1,55 @@
# Calculator sample
This example shows how to use Kotlin common module (located in [arithmeticParser](arithmeticParser/)) in different environments.
Currently for
* Android (see [androidApp](androidApp/))
* iOS (see [iosApp](iosApp/))
* plain JVM (cli) (see [cliApp](cliApp/))
## Common
Common Kotlin module contains arithmetic expressions parser.
## Android App
The common module may be used in an Android application.
Please make sure that Android SDK version 28 is installed, using Android SDK manager in Android Studio.
See https://developer.android.com/studio/index.html for more details on Android Studio or
`$ANDROID_HOME/tools/bin/sdkmanager "platforms;android-28" "build-tools;28.0.3"` from command line.
To build use `ANDROID_HOME=<your path to android sdk> ../gradlew assemble`.
Run `$ANDROID_HOME/platform-tools/adb install -r androidApp/build/outputs/apk/debug/androidApp-debug.apk`
to deploy the apk on the Android device or emulator.
Note: If you are importing project to IDEA for the first time, you might need to put `local.properties` file
with the following content:
sdk.dir=<your path to Android SDK>
## iOS
The iOS project compiles Kotlin module to a framework (see [iosApp](iosApp/)). The framework can be easily included in an existing iOS project (e.g. written in Swift or Objective-C)
To build and run the iOS sample do the following:
1. Open `iosApp/calculator.xcodeproj` with Xcode.
2. Open the project's target through project navigator, go to tab 'General'.
In 'Identity' section change the bundle ID to the unique string in
reverse-DNS format. Then select the team in 'Signing' section.
See the
[Xcode documentation](https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringYourApp/ConfiguringYourApp.html#//apple_ref/doc/uid/TP40012582-CH28-SW2)
for more info.
3. Now build and run the application with Xcode.
The iOS application is written in Swift. It uses Kotlin module as a library.
Kotlin module is built into Objective-C framework by invoking Gradle
from custom "Run Script" build phase, and this framework is imported into
the Xcode project.
## Plain JVM
The common module can also be used in JVM application built by Kotlin/JVM compiler with Gradle.
To build and run it, go to [cliApp](cliApp/) directory and use
```
../gradlew runProgram
```
@@ -0,0 +1,24 @@
apply plugin: 'org.jetbrains.kotlin.multiplatform'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId 'org.konan.calculator'
minSdkVersion 21
targetSdkVersion 28
}
}
dependencies {
api 'com.android.support:appcompat-v7:28.0.0'
api 'com.android.support.constraint:constraint-layout:1.1.3'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':arithmeticParser')
}
kotlin {
android()
}
@@ -0,0 +1,2 @@
kotlin.code.style=official
kotlin.import.noCommonSourceSets=true
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sample.calculator.android"
android:versionCode="1"
android:versionName="1.0">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="sample.calculator.android.MainActivity"
android:theme="@style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,33 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.calculator.android
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import android.widget.TextView
import sample.calculator.arithmeticparser.parseAndCompute
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val resultView = findViewById<TextView>(R.id.computed_result)
val input = findViewById<EditText>(R.id.input)
input.setOnEditorActionListener { input, _, _ ->
val inputText = input.text.toString()
val result = parseAndCompute(inputText).expression
with(resultView) {
text = if (result != null) inputText + " = " + result.toString() else "Unable to parse $inputText"
}
true
}
}
}
@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
style="@style/TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/enter_mathematical_expression" />
<EditText
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<TextView
android:id="@+id/computed_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="1+1=2" />
</LinearLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
@@ -0,0 +1,4 @@
<resources>
<string name="app_name">Konan Calculator</string>
<string name="enter_mathematical_expression">Enter mathematical expression:</string>
</resources>
@@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
</dict>
</plist>
@@ -0,0 +1,81 @@
apply plugin: 'org.jetbrains.kotlin.multiplatform'
kotlin {
targets {
fromPreset(determineIosPreset(), 'ios') {
binaries {
framework()
}
}
fromPreset(presets.jvm, 'jvm')
}
sourceSets {
commonMain {
dependencies {
api 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
}
jvmMain {
dependencies {
api 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
}
}
}
}
// Workaround for https://youtrack.jetbrains.com/issue/KT-27170
configurations {
compileClasspath
}
// If custom preset specified in 'calculator.preset.name' property, then use it for building.
// Otherwise build for iPhone simulator (by default).
def determineIosPreset() {
String presetName = project.hasProperty('calculator.preset.name') ? project.properties['calculator.preset.name'] : 'iosX64'
def preset = project.kotlin.presets[presetName]
println("$project has been configured for $presetName platform.")
preset
}
// Special Gradle task that is called from Xcode.
// Two Gradle properties must be specified for this task:
// - calculator.configuration.name=[Release|Debug]
// - calculator.framework.location
task buildFrameworkForXcode {
if (isCalledFromXcode()) {
dependsOn kotlin.targets.ios.binaries.getFramework(getBuildTypeForXcode()).linkTask
}
doLast {
if (!isCalledFromXcode()) {
throw new Exception("Please run 'buildFrameworkForXcode' task with all necessary properties!")
}
def frameworkDir = kotlin.targets.ios.binaries.getFramework(getBuildTypeForXcode()).outputFile
println("from: ${frameworkDir.parentFile}")
println("into: ${getXcodeConfigurationBuildDir()}")
copy {
from frameworkDir.parentFile
into getXcodeConfigurationBuildDir()
include "${frameworkDir.name}/**"
include "${frameworkDir.name}.dSYM/**"
}
}
}
private boolean isCalledFromXcode() {
project.hasProperty('calculator.configuration.name') && project.hasProperty('calculator.framework.location')
}
private String getBuildTypeForXcode() {
project.properties['calculator.configuration.name'] as String
}
private String getXcodeConfigurationBuildDir() {
project.properties['calculator.framework.location'] as String
}
@@ -0,0 +1 @@
kotlin.code.style=official
@@ -0,0 +1,284 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.calculator.arithmeticparser
fun parseAndCompute(expression: String): PartialParser.Result<Double, String> =
PartialParser(Calculator(), PartialRenderer()).parseWithPartial(expression)
class Calculator : ExpressionComposer<Double> {
override fun number(value: Double) = value
override fun plus(left: Double, right: Double) = left + right
override fun minus(left: Double, right: Double) = left - right
override fun mult(left: Double, right: Double) = left * right
override fun div(left: Double, right: Double) = left / right
}
class PartialRenderer : PartialExpressionComposer<Double, String> {
override fun missing() = "..."
override fun ending(expression: Double) = "$expression ..."
override fun plus(left: Double, partialRight: String) = "$left + $partialRight"
override fun minus(left: Double, partialRight: String) = "$left - $partialRight"
override fun mult(left: Double, partialRight: String) = "$left * $partialRight"
override fun div(left: Double, partialRight: String) = "$left / $partialRight"
override fun leftParenthesized(partialExpression: String) = "($partialExpression"
}
interface ExpressionComposer<E : Any> {
fun number(value: Double): E
fun plus(left: E, right: E): E
fun minus(left: E, right: E): E
fun mult(left: E, right: E): E
fun div(left: E, right: E): E
}
open class Parser<E : Any>(private val composer: ExpressionComposer<E>) {
fun parse(expression: String): E? {
val tokenizer = Tokenizer(expression)
val prefix = parseAsPrefix(tokenizer)
if (prefix is EndedWithExpression && !tokenizer.hasNext()) {
val reduced = prefix.reduced()
if (reduced.prefix is Empty) {
return reduced.expression
}
}
return null
}
internal fun parseAsPrefix(tokenizer: Tokenizer): ExpressionPrefix<E> =
generateSequence<ExpressionPrefix<E>>(Empty) {
it.tryExtend(tokenizer)
}.last()
private fun ExpressionPrefix<E>.tryExtend(tokenizer: Tokenizer): ExpressionPrefix<E>? = when (this) {
is ContinuableWithExpression -> {
val number = tokenizer.tryReadNumber()
when {
number != null -> this.with(composer.number(number))
tokenizer.tryReadLeftParenthesis() -> this.withLeftParenthesis()
else -> null
}
}
is EndedWithExpression -> {
val operator = tokenizer.tryReadBinaryOperator()
if (operator != null) {
this.extendedWithOperator(operator)
} else {
val reduced = this.reduced()
if (reduced.prefix is EndedWithLeftParenthesis && tokenizer.tryReadRightParenthesis()) {
// Drop parens:
reduced.prefix.prefix.with(reduced.expression)
} else {
null
}
}
}
}
private tailrec fun EndedWithExpression<E>.extendedWithOperator(operator: BinaryOperator): EndedWithOperator<E> =
if (this.prefix is EndedWithOperator && this.prefix.operator.precedence >= operator.precedence) {
// Apply the operator
this.prefix
.withOperatorApplied(this.expression)
.extendedWithOperator(operator)
} else {
EndedWithOperator(this.prefix, this.expression, operator)
}
internal tailrec fun EndedWithExpression<E>.reduced(): EndedWithExpression<E> = when (this.prefix) {
Empty, is EndedWithLeftParenthesis -> this
is EndedWithOperator ->
this.prefix
.withOperatorApplied(this.expression)
.reduced()
}
private fun EndedWithOperator<E>.withOperatorApplied(rightOperand: E) =
this.prefix.with(composer.compose(this.operator, this.leftOperand, rightOperand))
private fun ExpressionComposer<E>.compose(
binaryOperator: BinaryOperator, left: E, right: E
): E = when (binaryOperator) {
BinaryOperator.PLUS -> plus(left, right)
BinaryOperator.MINUS -> minus(left, right)
BinaryOperator.MULT -> mult(left, right)
BinaryOperator.DIV -> div(left, right)
}
}
interface PartialExpressionComposer<E : Any, PE : Any> {
fun missing(): PE
fun ending(expression: E): PE
fun plus(left: E, partialRight: PE): PE
fun minus(left: E, partialRight: PE): PE
fun mult(left: E, partialRight: PE): PE
fun div(left: E, partialRight: PE): PE
fun leftParenthesized(partialExpression: PE): PE
}
class PartialParser<E : Any, PE : Any>(
composer: ExpressionComposer<E>,
private val partialComposer: PartialExpressionComposer<E, PE>
) : Parser<E>(composer) {
data class Result<E : Any, PE : Any>(val expression: E?, val partialExpression: PE, val remainder: String?)
fun parseWithPartial(expression: String): Result<E, PE> {
val tokenizer = Tokenizer(expression)
val prefix = parseAsPrefix(tokenizer)
val remainder = tokenizer.getRemainder()
return Result(
if (remainder != null) null else tryReduce(prefix),
prefix.toPartialExpression(),
remainder
)
}
private fun tryReduce(prefix: ExpressionPrefix<E>): E? {
if (prefix is EndedWithExpression) {
val reduced = prefix.reduced()
if (reduced.prefix is Empty) {
return reduced.expression
}
}
return null
}
private fun ExpressionPrefix<E>.toPartialExpression(): PE = when (this) {
is EndedWithExpression -> this.prefix.toPartialExpressionWith(
ending = partialComposer.ending(this.expression)
)
is ContinuableWithExpression -> this.toPartialExpressionWith(ending = partialComposer.missing())
}
private tailrec fun ContinuableWithExpression<E>.toPartialExpressionWith(
ending: PE
): PE = when (this) {
Empty -> ending
is EndedWithLeftParenthesis -> this.prefix.toPartialExpressionWith(
ending = partialComposer.leftParenthesized(ending)
)
is EndedWithOperator -> this.prefix.toPartialExpressionWith(
ending = partialComposer.compose(this.operator, this.leftOperand, ending)
)
}
private fun PartialExpressionComposer<E, PE>.compose(
binaryOperator: BinaryOperator,
left: E,
right: PE
): PE = when (binaryOperator) {
BinaryOperator.PLUS -> plus(left, right)
BinaryOperator.MINUS -> minus(left, right)
BinaryOperator.MULT -> mult(left, right)
BinaryOperator.DIV -> div(left, right)
}
}
/**
* Immutable prefix of expression partially parsed to combination of abstractly represented expressions.
* The prefix representation can be thought as "almost AST", i.e. AST with unfinished rightmost leaf
* (referenced by this object), and its nodes contain links to parent and (if needed) left child.
*
* @param E abstract representation of expression, e.g. its value, AST etc.
*/
internal sealed class ExpressionPrefix<out E>
internal data class EndedWithExpression<E>(
val prefix: ContinuableWithExpression<E>,
val expression: E
) : ExpressionPrefix<E>()
internal sealed class ContinuableWithExpression<out E> : ExpressionPrefix<E>()
private fun <E> ContinuableWithExpression<E>.with(expression: E) =
EndedWithExpression(this, expression)
private object Empty : ContinuableWithExpression<Nothing>()
private data class EndedWithLeftParenthesis<out E>(
val prefix: ContinuableWithExpression<E>
) : ContinuableWithExpression<E>()
private fun <E> ContinuableWithExpression<E>.withLeftParenthesis() =
EndedWithLeftParenthesis(this)
private data class EndedWithOperator<out E>(
val prefix: ContinuableWithExpression<E>,
val leftOperand: E,
val operator: BinaryOperator
) : ContinuableWithExpression<E>()
internal enum class BinaryOperator(val sign: Char, val precedence: Int) {
PLUS('+', 2),
MINUS('-', 2),
MULT('*', 3),
DIV('/', 3)
}
internal class Tokenizer(private val expression: String) {
private var index = 0
init {
skipSpaces()
}
fun hasNext(): Boolean = (index < expression.length)
fun getRemainder(): String? = if (this.hasNext()) {
expression.substring(index)
} else {
null
}
fun tryReadNumber(): Double? {
var endIndex = index
while (expression.getOrNull(endIndex)?.isNumberChar() == true) {
++endIndex
}
return expression.substring(index, endIndex).toDoubleOrNull()?.also {
index = endIndex
skipSpaces()
}
}
private fun Char.isNumberChar(): Boolean = this in '0'..'9' || this == '.'
fun tryReadBinaryOperator(): BinaryOperator? = BinaryOperator.values().firstOrNull { tryRead(it.sign) }
fun tryReadLeftParenthesis(): Boolean = tryRead('(')
fun tryReadRightParenthesis(): Boolean = tryRead(')')
private fun tryRead(char: Char): Boolean = if (hasNext() && expression[index] == char) {
++index
skipSpaces()
true
} else {
false
}
private fun skipSpaces() {
while (expression.getOrNull(index)?.isWhitespace() == true) {
++index
}
}
}
@@ -0,0 +1,24 @@
buildscript {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )
$DIR/../gradlew -p $DIR assemble
@@ -0,0 +1,22 @@
apply plugin: 'org.jetbrains.kotlin.multiplatform'
kotlin {
targets {
jvm()
}
sourceSets {
jvmMain {
dependencies {
implementation project(':arithmeticParser')
}
}
}
}
task runProgram(type: JavaExec) {
dependsOn assemble
main = 'sample.calculator.jvm.JvmCli'
classpath = files(kotlin.targets.jvm.compilations.main.output) + kotlin.targets.jvm.compilations.main.runtimeDependencyFiles
args '2 + 3'
}
@@ -0,0 +1,2 @@
kotlin.code.style=official
kotlin.import.noCommonSourceSets=true
@@ -0,0 +1,31 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:JvmName("JvmCli")
package sample.calculator.jvm
import sample.calculator.arithmeticparser.parseAndCompute
fun main(args: Array<String>) {
val expression = if (args.isNotEmpty()) {
args.first().also {
print(it)
}
} else {
println("Enter an expression:")
readLine()!!
}
val result = parseAndCompute(expression)
val computed = result.expression
if (computed != null) {
println(" = $computed")
} else {
println(" = ${result.partialExpression}")
result.remainder?.let {
println("Unable to parse suffix: $it")
}
}
}
@@ -0,0 +1,15 @@
kotlin.code.style=official
# Run parallel builds in Gradle:
org.gradle.parallel=true
org.gradle.workers.max=4
# Pin Kotlin version:
# CHANGE_VERSION_WITH_RELEASE
kotlin_version=1.4.10
# Use custom Kotlin/Native home:
kotlin.native.home=../../../dist
# Increase memory for in-process compiler execution.
org.gradle.jvmargs=-Xmx3g
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
+89
View File
@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,519 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 48;
objects = {
/* Begin PBXBuildFile section */
2C3F38451FD1738300151601 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C3F38441FD1738300151601 /* AppDelegate.swift */; };
2C3F38471FD1738300151601 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C3F38461FD1738300151601 /* ViewController.swift */; };
2C3F384A1FD1738300151601 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F38481FD1738300151601 /* Main.storyboard */; };
2C3F384C1FD1738300151601 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F384B1FD1738300151601 /* Assets.xcassets */; };
2C3F384F1FD1738300151601 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */; };
7FE128BF205854BA0064CE74 /* arithmeticParser.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 7FF94AD92058464C00590D0D /* arithmeticParser.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
7FF94AE32058483900590D0D /* arithmeticParser.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FF94AD92058464C00590D0D /* arithmeticParser.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
2C10D2172521E5AA001EB717 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 2C3F38391FD1738300151601 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 7FF94AD82058464C00590D0D;
remoteInfo = arithmeticParser;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
7FE128BE2058549E0064CE74 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
7FE128BF205854BA0064CE74 /* arithmeticParser.framework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
2C3F38411FD1738300151601 /* KotlinCalculator.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KotlinCalculator.app; sourceTree = BUILT_PRODUCTS_DIR; };
2C3F38441FD1738300151601 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
2C3F38461FD1738300151601 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
2C3F38491FD1738300151601 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
2C3F384B1FD1738300151601 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
2C3F384E1FD1738300151601 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
2C3F38501FD1738300151601 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
7FF94AD92058464C00590D0D /* arithmeticParser.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = arithmeticParser.framework; sourceTree = BUILT_PRODUCTS_DIR; };
7FF94AEA2058485300590D0D /* Parser.kt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Parser.kt; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
2C3F383E1FD1738300151601 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7FF94AE32058483900590D0D /* arithmeticParser.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2C3F38381FD1738300151601 = {
isa = PBXGroup;
children = (
2C3F38431FD1738300151601 /* calculator */,
7FF94ADA2058464C00590D0D /* arithmeticParser */,
2C3F38421FD1738300151601 /* Products */,
7FF94AE22058483900590D0D /* Frameworks */,
);
sourceTree = "<group>";
};
2C3F38421FD1738300151601 /* Products */ = {
isa = PBXGroup;
children = (
2C3F38411FD1738300151601 /* KotlinCalculator.app */,
7FF94AD92058464C00590D0D /* arithmeticParser.framework */,
);
name = Products;
sourceTree = "<group>";
};
2C3F38431FD1738300151601 /* calculator */ = {
isa = PBXGroup;
children = (
2C3F38441FD1738300151601 /* AppDelegate.swift */,
2C3F38461FD1738300151601 /* ViewController.swift */,
2C3F38481FD1738300151601 /* Main.storyboard */,
2C3F384B1FD1738300151601 /* Assets.xcassets */,
2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */,
2C3F38501FD1738300151601 /* Info.plist */,
);
path = calculator;
sourceTree = "<group>";
};
7FF94ADA2058464C00590D0D /* arithmeticParser */ = {
isa = PBXGroup;
children = (
7FF94AE42058485300590D0D /* src */,
);
name = arithmeticParser;
sourceTree = "<group>";
};
7FF94AE22058483900590D0D /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
7FF94AE42058485300590D0D /* src */ = {
isa = PBXGroup;
children = (
7FF94AE52058485300590D0D /* commonMain */,
);
name = src;
path = ../arithmeticParser/src;
sourceTree = SOURCE_ROOT;
};
7FF94AE52058485300590D0D /* commonMain */ = {
isa = PBXGroup;
children = (
7FF94AE62058485300590D0D /* kotlin */,
);
path = commonMain;
sourceTree = "<group>";
};
7FF94AE62058485300590D0D /* kotlin */ = {
isa = PBXGroup;
children = (
7FF94AEA2058485300590D0D /* Parser.kt */,
);
path = kotlin;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
2C3F38401FD1738300151601 /* KotlinCalculator */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2C3F38531FD1738300151601 /* Build configuration list for PBXNativeTarget "KotlinCalculator" */;
buildPhases = (
2C3F383D1FD1738300151601 /* Sources */,
2C3F383E1FD1738300151601 /* Frameworks */,
2C3F383F1FD1738300151601 /* Resources */,
7FE128BE2058549E0064CE74 /* Embed Frameworks */,
);
buildRules = (
);
dependencies = (
2C10D2182521E5AA001EB717 /* PBXTargetDependency */,
);
name = KotlinCalculator;
productName = calculator;
productReference = 2C3F38411FD1738300151601 /* KotlinCalculator.app */;
productType = "com.apple.product-type.application";
};
7FF94AD82058464C00590D0D /* arithmeticParser */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7FF94ADE2058464C00590D0D /* Build configuration list for PBXNativeTarget "arithmeticParser" */;
buildPhases = (
7FF94AE12058466D00590D0D /* Compile Kotlin/Native */,
);
buildRules = (
);
dependencies = (
);
name = arithmeticParser;
productName = arithmeticParser;
productReference = 7FF94AD92058464C00590D0D /* arithmeticParser.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
2C3F38391FD1738300151601 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0900;
LastUpgradeCheck = 0900;
ORGANIZATIONNAME = JetBrains;
TargetAttributes = {
2C3F38401FD1738300151601 = {
CreatedOnToolsVersion = 9.0;
ProvisioningStyle = Automatic;
};
7FF94AD82058464C00590D0D = {
CreatedOnToolsVersion = 9.2;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 2C3F383C1FD1738300151601 /* Build configuration list for PBXProject "calculator" */;
compatibilityVersion = "Xcode 8.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 2C3F38381FD1738300151601;
productRefGroup = 2C3F38421FD1738300151601 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
2C3F38401FD1738300151601 /* KotlinCalculator */,
7FF94AD82058464C00590D0D /* arithmeticParser */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
2C3F383F1FD1738300151601 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2C3F384F1FD1738300151601 /* LaunchScreen.storyboard in Resources */,
2C3F384C1FD1738300151601 /* Assets.xcassets in Resources */,
2C3F384A1FD1738300151601 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
7FF94AE12058466D00590D0D /* Compile Kotlin/Native */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Compile Kotlin/Native";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"$SRCROOT/../gradlew\" -p \"$SRCROOT/..\" buildFrameworkForXcode \\\n-Pcalculator.preset.name=\"$KOTLIN_NATIVE_PRESET\" \\\n-Pcalculator.configuration.name=\"$CONFIGURATION\" \\\n-Pcalculator.framework.location=\"$CONFIGURATION_BUILD_DIR\"\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
2C3F383D1FD1738300151601 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2C3F38471FD1738300151601 /* ViewController.swift in Sources */,
2C3F38451FD1738300151601 /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
2C10D2182521E5AA001EB717 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 7FF94AD82058464C00590D0D /* arithmeticParser */;
targetProxy = 2C10D2172521E5AA001EB717 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
2C3F38481FD1738300151601 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
2C3F38491FD1738300151601 /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
2C3F384E1FD1738300151601 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
2C3F38511FD1738300151601 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
2C3F38521FD1738300151601 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
2C3F38541FD1738300151601 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = $BUILT_PRODUCTS_DIR;
INFOPLIST_FILE = calculator/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = org.jetbrains.konan.calculator;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
2C3F38551FD1738300151601 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = $BUILT_PRODUCTS_DIR;
INFOPLIST_FILE = calculator/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = org.jetbrains.konan.calculator;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
7FF94ADF2058464C00590D0D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_IDENTITY = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/../arithmeticParser/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 11.2;
"KOTLIN_NATIVE_PRESET[sdk=iphoneos*]" = iosArm64;
"KOTLIN_NATIVE_PRESET[sdk=iphonesimulator*]" = iosX64;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = JetBrains.arithmeticParser;
PRODUCT_MODULE_NAME = "_$(PRODUCT_NAME:c99extidentifier)";
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = arm64;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
7FF94AE02058464C00590D0D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_IDENTITY = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = "$(SRCROOT)/../arithmeticParser/Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 11.2;
"KOTLIN_NATIVE_PRESET[sdk=iphoneos*]" = iosArm64;
"KOTLIN_NATIVE_PRESET[sdk=iphonesimulator*]" = iosX64;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = JetBrains.arithmeticParser;
PRODUCT_MODULE_NAME = "_$(PRODUCT_NAME:c99extidentifier)";
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = arm64;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
2C3F383C1FD1738300151601 /* Build configuration list for PBXProject "calculator" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2C3F38511FD1738300151601 /* Debug */,
2C3F38521FD1738300151601 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2C3F38531FD1738300151601 /* Build configuration list for PBXNativeTarget "KotlinCalculator" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2C3F38541FD1738300151601 /* Debug */,
2C3F38551FD1738300151601 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7FF94ADE2058464C00590D0D /* Build configuration list for PBXNativeTarget "arithmeticParser" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7FF94ADF2058464C00590D0D /* Debug */,
7FF94AE02058464C00590D0D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 2C3F38391FD1738300151601 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:calculator.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,43 @@
//
// Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
// that can be found in the license/LICENSE.txt file.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13196" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_0" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13173"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="calculator" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" fixedFrame="YES" text="2+2" textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="cQ3-DE-9pB">
<rect key="frame" x="16" y="80" width="288" height="86"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<textInputTraits key="textInputTraits" autocapitalizationType="sentences" keyboardType="numbersAndPunctuation"/>
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="number" keyPath="layer.borderWidth">
<integer key="value" value="1"/>
</userDefinedRuntimeAttribute>
</userDefinedRuntimeAttributes>
</textView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="UXD-Ml-fWa">
<rect key="frame" x="16" y="20" width="288" height="52"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dE5-rs-MxS">
<rect key="frame" x="16" y="174" width="288" height="56"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" flexibleMinY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" fixedFrame="YES" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="uUY-IG-q6c">
<rect key="frame" x="16" y="238" width="288" height="310"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxX="YES" flexibleMinY="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="0.0" minimumInteritemSpacing="0.0" id="60I-ff-UQl">
<size key="itemSize" width="60" height="60"/>
<size key="headerReferenceSize" width="0.0" height="0.0"/>
<size key="footerReferenceSize" width="0.0" height="0.0"/>
<inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
</collectionViewFlowLayout>
<cells>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="buttonCell" id="m0y-g8-H1J">
<rect key="frame" x="0.0" y="0.0" width="60" height="60"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO">
<rect key="frame" x="0.0" y="0.0" width="60" height="60"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<button opaque="NO" tag="1" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="R08-8U-cUE">
<rect key="frame" x="0.0" y="0.0" width="60" height="60"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" type="system" pointSize="19"/>
<state key="normal" title="1"/>
<connections>
<action selector="numpadButtonPressed:" destination="BYZ-38-t0r" eventType="touchUpInside" id="MBN-Ls-DBV"/>
</connections>
</button>
</subviews>
</view>
</collectionViewCell>
</cells>
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="number" keyPath="layer.borderWidth">
<integer key="value" value="1"/>
</userDefinedRuntimeAttribute>
</userDefinedRuntimeAttributes>
</collectionView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
<connections>
<outlet property="input" destination="cQ3-DE-9pB" id="U0V-GS-zHc"/>
<outlet property="numpad" destination="uUY-IG-q6c" id="kNg-wO-UyR"/>
<outlet property="partialResult" destination="UXD-Ml-fWa" id="2td-LF-uL1"/>
<outlet property="result" destination="dE5-rs-MxS" id="zaZ-Fm-AVn"/>
</connections>
</viewController>
</objects>
<point key="canvasLocation" x="116.25" y="118.30985915492958"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>KotlinCalc</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,154 @@
//
// Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
// that can be found in the license/LICENSE.txt file.
//
import UIKit
import arithmeticParser
class ViewController: UIViewController, UITextViewDelegate, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
numpad.dataSource = self
self.input.delegate = self
inputDidChange()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var partialResult: UILabel!
@IBOutlet var result: UILabel!
@IBOutlet var input: UITextView!
@IBOutlet var numpad: UICollectionView!
private let parser = PartialParser<KotlinDouble, NSAttributedString>(
composer: Calculator(),
partialComposer: PartialRenderer()
)
@IBAction func numpadButtonPressed(_ sender: UIButton) {
let title = sender.currentTitle!
if title == "" {
return
}
if title == "" {
if !input.text.isEmpty {
input.text.removeLast()
}
} else {
input.text.append(title)
}
inputDidChange()
}
func textViewDidChange(_ textView: UITextView) {
if textView === input {
inputDidChange()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.input.endEditing(true)
}
private func inputDidChange() {
let parsed = parser.parseWithPartial(expression: input.text)
if let resultValue = parsed.expression {
result.text = "= \(resultValue)"
} else {
result.text = ""
}
let attributedText = parsed.partialExpression
if let remainder = parsed.remainder {
partialResult.attributedText = attributedText +
NSAttributedString(string: " ") +
NSAttributedString(string: remainder, attributes:
[.foregroundColor: UIColor.red,
.font: UIFont.boldSystemFont(ofSize: partialResult.font.pointSize)])
} else {
partialResult.attributedText = attributedText
}
}
private let buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
".", "0", "", "+",
"(", ")", "", ""
]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return buttons.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "buttonCell", for: indexPath)
(cell.viewWithTag(1) as! UIButton).setTitle(buttons[indexPath.item],for: .normal)
return cell
}
}
private func +(left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
let result = NSMutableAttributedString(attributedString: left)
result.append(right)
return result
}
private extension String {
func toAttributed() -> NSAttributedString {
return NSAttributedString(string: self)
}
}
private class PartialRenderer: NSObject, PartialExpressionComposer {
func missing() -> Any {
return "... ".toAttributed()
}
func ending(expression: Any) -> Any {
return "\(formatDouble(expression))... ".toAttributed()
}
func plus(left: Any, partialRight: Any) -> Any {
return compose("+", left, partialRight)
}
func minus(left: Any, partialRight: Any) -> Any {
return compose("-", left, partialRight)
}
func mult(left: Any, partialRight: Any) -> Any {
return compose("*", left, partialRight)
}
func div(left: Any, partialRight: Any) -> Any {
return compose("/", left, partialRight)
}
func leftParenthesized(partialExpression: Any) -> Any {
let suffix = NSAttributedString(string: ")", attributes: [.foregroundColor: UIColor.lightGray])
return "(".toAttributed() + (partialExpression as! NSAttributedString) + suffix
}
private func formatDouble(_ value: Any) -> String {
let rounded = round(1000 * (value as! Double)) / 1000
return "\(rounded as NSNumber)"
}
private func compose(_ op: String, _ left: Any, _ partialRight: Any) -> Any {
return "\(formatDouble(left)) \(op) ".toAttributed() + (partialRight as! NSAttributedString)
}
}
@@ -0,0 +1,16 @@
include ':arithmeticParser'
include ':cliApp'
boolean sdkDirPropertySpecified = false
File localPropertiesFile = file("${rootProject.projectDir}/local.properties")
if (localPropertiesFile.isFile()) {
Properties properties = new Properties()
localPropertiesFile.withInputStream { inputStream -> properties.load(inputStream) }
sdkDirPropertySpecified = properties.containsKey('sdk.dir')
}
// Don't create Android tasks if a user has no Android SDK.
if (sdkDirPropertySpecified || System.getenv('ANDROID_HOME') != null) {
include ':androidApp'
}
@@ -0,0 +1,8 @@
ios-app/Pods
Podfile.lock
kotlin-library/kotlin_library.podspec
ios-app/ios-app.xcodeproj/xcuserdata
ios-app/ios-app.xcworkspace/xcuserdata
ios-app/ios-app.xcodeproj/project.xcworkspace/xcuserdata
ios-app/ios-app.xcworkspace/contents.xcworkspacedata
ios-app/ios-app.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
+24
View File
@@ -0,0 +1,24 @@
# Using CocoaPods
This sample demonstrates how to use a CocoaPods library from Kotlin/Native. It uses the the
[AFNetworking](https://cocoapods.org/pods/AFNetworking) library to retrieve a web-page by a
given URL.
## Configuring the project
1. [Install](https://guides.cocoapods.org/using/getting-started.html#installation) CocoaPods.
It's recommended to use CocoaPods 1.6.1 or higher.
2. Navigate to the [kotlin-library](kotlin-library) directory and run
```
./gradlew podspec
```
A [podspec](https://guides.cocoapods.org/syntax/podspec.html#specification) file for the
Kotlin/Native library will be generated.
3. Navigate to the [ios-app](ios-app) directory and install the dependencies. The generated
podspec is already added to the Podfile, so just run
```
pod install
```
4. Open [ios-app.xcworkspace](ios-app/ios-app.xcworkspace) in Xcode and run the build.
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )
KOTLIN_DIR="$DIR/kotlin-library"
IOS_DIR="$DIR/ios-app"
#Check CocoaPods version.
REQUIRED_POD_VERSION="1.6.1"
POD_VERSION=`pod --version`
EARLIER_VERSION=`echo "$POD_VERSION $REQUIRED_POD_VERSION" | tr " " "\n" | sort -V | head -1`
if [ "$EARLIER_VERSION" != "$REQUIRED_POD_VERSION" ]; then
echo "ERROR: This version of CocoaPods is unsupported. Current version is $POD_VERSION. Minimal required version is $REQUIRED_POD_VERSION."
echo "See update instructions at https://guides.cocoapods.org/using/getting-started.html#updating-cocoapods"
exit 1
fi
# Prepare Kotlin/Native project to be consumed by CocoaPods.
"$KOTLIN_DIR/gradlew" -p "$KOTLIN_DIR" podspec
# Run CocoaPods to configure the Xcode project.
pod --project-directory="$IOS_DIR" install
# Run Xcode to build the app.
xcodebuild -sdk iphonesimulator -arch arm64 -configuration Release -workspace "$IOS_DIR/ios-app.xcworkspace" -scheme ios-app
@@ -0,0 +1,8 @@
# Either use_frameworks! or use_modular_headers! must be specified.
use_frameworks!
platform :ios, '9.0'
target 'ios-app' do
pod 'kotlin_library', :path => '../kotlin-library'
end
@@ -0,0 +1,419 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
2C11BACF224B4DCB00D1CC3C /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C11BACE224B4DCB00D1CC3C /* AppDelegate.swift */; };
2C11BAD1224B4DCB00D1CC3C /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C11BAD0224B4DCB00D1CC3C /* ViewController.swift */; };
2C11BAD4224B4DCB00D1CC3C /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C11BAD2224B4DCB00D1CC3C /* Main.storyboard */; };
2C11BAD6224B4DCD00D1CC3C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2C11BAD5224B4DCD00D1CC3C /* Assets.xcassets */; };
2C11BAD9224B4DCD00D1CC3C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C11BAD7224B4DCD00D1CC3C /* LaunchScreen.storyboard */; };
7AEB35573DF5ECC0B96C877C /* Pods_ios_app.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 06FDB564DA981DADB5693C07 /* Pods_ios_app.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
06FDB564DA981DADB5693C07 /* Pods_ios_app.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ios_app.framework; sourceTree = BUILT_PRODUCTS_DIR; };
2C11BACB224B4DCB00D1CC3C /* ios-app.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ios-app.app"; sourceTree = BUILT_PRODUCTS_DIR; };
2C11BACE224B4DCB00D1CC3C /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
2C11BAD0224B4DCB00D1CC3C /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };
2C11BAD3224B4DCB00D1CC3C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
2C11BAD5224B4DCD00D1CC3C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
2C11BAD8224B4DCD00D1CC3C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
2C11BADA224B4DCD00D1CC3C /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
2C11BAE0224B65DE00D1CC3C /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };
44888DA7148EA4EB17DF765D /* Pods-ios-app.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ios-app.debug.xcconfig"; path = "Target Support Files/Pods-ios-app/Pods-ios-app.debug.xcconfig"; sourceTree = "<group>"; };
A063F818143EBBCD07EA19D4 /* Pods-ios-app.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ios-app.release.xcconfig"; path = "Target Support Files/Pods-ios-app/Pods-ios-app.release.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
2C11BAC8224B4DCB00D1CC3C /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7AEB35573DF5ECC0B96C877C /* Pods_ios_app.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2C11BAC2224B4DCB00D1CC3C = {
isa = PBXGroup;
children = (
2C11BACD224B4DCB00D1CC3C /* ios-app */,
2C11BACC224B4DCB00D1CC3C /* Products */,
9C1A5E5C1B80F794B7154EE0 /* Pods */,
B404E0DEAC80D8DB556F0E49 /* Frameworks */,
);
sourceTree = "<group>";
};
2C11BACC224B4DCB00D1CC3C /* Products */ = {
isa = PBXGroup;
children = (
2C11BACB224B4DCB00D1CC3C /* ios-app.app */,
);
name = Products;
sourceTree = "<group>";
};
2C11BACD224B4DCB00D1CC3C /* ios-app */ = {
isa = PBXGroup;
children = (
2C11BACE224B4DCB00D1CC3C /* AppDelegate.swift */,
2C11BAD0224B4DCB00D1CC3C /* ViewController.swift */,
2C11BAD2224B4DCB00D1CC3C /* Main.storyboard */,
2C11BAD5224B4DCD00D1CC3C /* Assets.xcassets */,
2C11BAD7224B4DCD00D1CC3C /* LaunchScreen.storyboard */,
2C11BADA224B4DCD00D1CC3C /* Info.plist */,
);
path = "ios-app";
sourceTree = "<group>";
};
9C1A5E5C1B80F794B7154EE0 /* Pods */ = {
isa = PBXGroup;
children = (
44888DA7148EA4EB17DF765D /* Pods-ios-app.debug.xcconfig */,
A063F818143EBBCD07EA19D4 /* Pods-ios-app.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
B404E0DEAC80D8DB556F0E49 /* Frameworks */ = {
isa = PBXGroup;
children = (
2C11BAE0224B65DE00D1CC3C /* WebKit.framework */,
06FDB564DA981DADB5693C07 /* Pods_ios_app.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
2C11BACA224B4DCB00D1CC3C /* ios-app */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2C11BADD224B4DCD00D1CC3C /* Build configuration list for PBXNativeTarget "ios-app" */;
buildPhases = (
F305A4DC70C8B21755898707 /* [CP] Check Pods Manifest.lock */,
2C11BAC7224B4DCB00D1CC3C /* Sources */,
2C11BAC8224B4DCB00D1CC3C /* Frameworks */,
2C11BAC9224B4DCB00D1CC3C /* Resources */,
042B85E17AFECF20FF11D591 /* [CP] Embed Pods Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "ios-app";
productName = "ios-app";
productReference = 2C11BACB224B4DCB00D1CC3C /* ios-app.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
2C11BAC3224B4DCB00D1CC3C /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1010;
LastUpgradeCheck = 1010;
TargetAttributes = {
2C11BACA224B4DCB00D1CC3C = {
CreatedOnToolsVersion = 10.1;
};
};
};
buildConfigurationList = 2C11BAC6224B4DCB00D1CC3C /* Build configuration list for PBXProject "ios-app" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 2C11BAC2224B4DCB00D1CC3C;
productRefGroup = 2C11BACC224B4DCB00D1CC3C /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
2C11BACA224B4DCB00D1CC3C /* ios-app */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
2C11BAC9224B4DCB00D1CC3C /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2C11BAD9224B4DCD00D1CC3C /* LaunchScreen.storyboard in Resources */,
2C11BAD6224B4DCD00D1CC3C /* Assets.xcassets in Resources */,
2C11BAD4224B4DCB00D1CC3C /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
042B85E17AFECF20FF11D591 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-ios-app/Pods-ios-app-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
);
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-ios-app/Pods-ios-app-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
F305A4DC70C8B21755898707 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-ios-app-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
2C11BAC7224B4DCB00D1CC3C /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2C11BAD1224B4DCB00D1CC3C /* ViewController.swift in Sources */,
2C11BACF224B4DCB00D1CC3C /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
2C11BAD2224B4DCB00D1CC3C /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
2C11BAD3224B4DCB00D1CC3C /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
2C11BAD7224B4DCD00D1CC3C /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
2C11BAD8224B4DCD00D1CC3C /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
2C11BADB224B4DCD00D1CC3C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
2C11BADC224B4DCD00D1CC3C /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
2C11BADE224B4DCD00D1CC3C /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 44888DA7148EA4EB17DF765D /* Pods-ios-app.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "ios-app/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.jetbrains.konan.ios-app";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
2C11BADF224B4DCD00D1CC3C /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = A063F818143EBBCD07EA19D4 /* Pods-ios-app.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = "ios-app/Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.jetbrains.konan.ios-app";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
2C11BAC6224B4DCB00D1CC3C /* Build configuration list for PBXProject "ios-app" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2C11BADB224B4DCD00D1CC3C /* Debug */,
2C11BADC224B4DCD00D1CC3C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2C11BADD224B4DCD00D1CC3C /* Build configuration list for PBXNativeTarget "ios-app" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2C11BADE224B4DCD00D1CC3C /* Debug */,
2C11BADF224B4DCD00D1CC3C /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 2C11BAC3224B4DCB00D1CC3C /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:ios-app.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,38 @@
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina5_5" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="ios_app" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="736"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="fill" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="URL" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="yxG-KN-iVS">
<rect key="frame" x="20" y="20" width="343" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" textContentType="url"/>
</textField>
<textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" editable="NO" translatesAutoresizingMaskIntoConstraints="NO" id="6po-pO-57H">
<rect key="frame" x="20" y="58" width="374" height="658"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<fontDescription key="fontDescription" name=".AppleSystemUIFont" family=".AppleSystemUIFont" pointSize="14"/>
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
</textView>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Tmq-lB-SJh">
<rect key="frame" x="364" y="20" width="30" height="30"/>
<constraints>
<constraint firstAttribute="width" constant="30" id="MLi-dL-yKe"/>
</constraints>
<state key="normal" title="Go!"/>
<connections>
<action selector="onGoTouch:" destination="BYZ-38-t0r" eventType="touchUpInside" id="TuI-9e-64N"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="yxG-KN-iVS" firstAttribute="top" secondItem="Tmq-lB-SJh" secondAttribute="top" id="8B4-D0-Bll"/>
<constraint firstAttribute="bottom" secondItem="6po-pO-57H" secondAttribute="bottom" constant="20" symbolic="YES" id="DQe-FX-RyI"/>
<constraint firstItem="yxG-KN-iVS" firstAttribute="leading" secondItem="6po-pO-57H" secondAttribute="leading" id="I3A-Fn-cSe"/>
<constraint firstItem="6po-pO-57H" firstAttribute="top" secondItem="yxG-KN-iVS" secondAttribute="bottom" constant="8" symbolic="YES" id="IxV-IA-Ss9"/>
<constraint firstItem="Tmq-lB-SJh" firstAttribute="leading" secondItem="yxG-KN-iVS" secondAttribute="trailing" constant="1" id="VAd-gQ-6n5"/>
<constraint firstItem="Tmq-lB-SJh" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="Yx2-Hv-HXr"/>
<constraint firstItem="yxG-KN-iVS" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="ZtB-cu-ry8"/>
<constraint firstItem="yxG-KN-iVS" firstAttribute="top" secondItem="6Tk-OE-BBY" secondAttribute="top" id="cPt-02-UL5"/>
<constraint firstItem="Tmq-lB-SJh" firstAttribute="trailing" secondItem="6po-pO-57H" secondAttribute="trailing" id="mXC-8E-3J4"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
<connections>
<outlet property="contentTextView" destination="6po-pO-57H" id="RyQ-WT-F4c"/>
<outlet property="goButton" destination="Tmq-lB-SJh" id="4Zy-vm-Zdm"/>
<outlet property="urlField" destination="yxG-KN-iVS" id="lON-5B-zW1"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="131.8840579710145" y="132.88043478260872"/>
</scene>
</scenes>
</document>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,21 @@
import UIKit
import kotlin_library
class ViewController: UIViewController {
@IBOutlet weak var goButton: UIButton!
@IBOutlet weak var urlField: UITextField!
@IBOutlet weak var contentTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func onGoTouch(_ sender: Any) {
let url = urlField.text!
KotlinLibKt.getAndShow(url: url, contentView: contentTextView)
}
}
@@ -0,0 +1,37 @@
plugins {
id("org.jetbrains.kotlin.multiplatform")
id("org.jetbrains.kotlin.native.cocoapods")
}
repositories {
jcenter()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
group = "org.jetbrains.kotlin.sample.native"
version = "1.0"
kotlin {
// Add a platform switching to have an IDE support.
val buildForDevice = project.findProperty("kotlin.native.cocoapods.target") == "ios_arm"
if (buildForDevice) {
iosArm64("iOS64")
iosArm32("iOS32")
val iOSMain by sourceSets.creating
sourceSets["iOS64Main"].dependsOn(iOSMain)
sourceSets["iOS32Main"].dependsOn(iOSMain)
} else {
iosX64("iOS")
}
cocoapods {
// Configure fields required by CocoaPods.
summary = "Working with AFNetworking from Kotlin/Native using CocoaPods"
homepage = "https://github.com/JetBrains/kotlin-native"
// Configure a dependency on AFNetworking. It will be added in all macOS and iOS targets.
pod("AFNetworking", "~> 3.2.0")
}
}
@@ -0,0 +1,15 @@
kotlin.code.style=official
# Run parallel builds in Gradle:
org.gradle.parallel=true
org.gradle.workers.max=4
# Pin Kotlin version:
# CHANGE_VERSION_WITH_RELEASE
kotlin_version=1.4.10
# Use custom Kotlin/Native home:
kotlin.native.home=../../../dist
# Increase memory for in-process compiler execution.
org.gradle.jvmargs=-Xmx3g
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,20 @@
pluginManagement {
repositories {
jcenter()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
resolutionStrategy {
val kotlin_version: String by settings
eachPlugin {
when {
requested.id.id == "org.jetbrains.kotlin.native.cocoapods" ||
requested.id.id == "kotlin-native-cocoapods" ->
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
requested.id.id.startsWith("org.jetbrains.kotlin") ->
useVersion(kotlin_version)
}
}
}
}
@@ -0,0 +1,34 @@
import cocoapods.AFNetworking.AFHTTPResponseSerializer
import cocoapods.AFNetworking.AFHTTPSessionManager
import platform.Foundation.*
import platform.UIKit.NSDocumentTypeDocumentAttribute
import platform.UIKit.NSHTMLTextDocumentType
import platform.UIKit.UITextView
import platform.UIKit.create
import kotlin.Any
import kotlin.String
import kotlin.to
import kotlin.toString
/**
* Retrieves the content by the given URL and shows it at the given WebKitView
*/
fun getAndShow(url: String, contentView: UITextView) {
val manager = AFHTTPSessionManager()
manager.responseSerializer = AFHTTPResponseSerializer()
val onSuccess = { _: NSURLSessionDataTask?, response: Any? ->
val html = NSAttributedString.create(
data = response as NSData,
options = mapOf(NSDocumentTypeDocumentAttribute as Any? to NSHTMLTextDocumentType),
documentAttributes = null,
error = null
)!!
contentView.attributedText = html
}
val onError = { _: NSURLSessionDataTask?, error: NSError? ->
NSLog("Cannot get ${url}.")
NSLog(error.toString())
}
manager.GET(url, null, onSuccess, onError)
}
+12
View File
@@ -0,0 +1,12 @@
# Code Coverage usage sample
This example shows how to collect coverage information during execution of the test suite.
Please note that this functionality will be incorporated into Gradle plugin so you won't need to do it by hand in the nearest future.
### Prerequisites
`createCoverageReport` task requires `llvm-profdata` and `llvm-cov` to be added to the `$PATH`.
They can be found in the Kotlin/Native dependencies dir. By default it should look like
`$HOME/.konan/dependencies/clang-llvm-6.0.1-darwin-macos/bin`
### Usage
Just run `createCoverageReport` task.
@@ -0,0 +1,49 @@
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
plugins {
kotlin("multiplatform")
}
kotlin {
// Determine host preset.
val hostOs = System.getProperty("os.name")
val isMingwX64 = hostOs.startsWith("Windows")
// Create a target for the host platform.
val hostTarget = when {
hostOs == "Mac OS X" -> macosX64("coverage")
hostOs == "Linux" -> linuxX64("coverage")
isMingwX64 -> mingwX64("coverage")
else -> throw GradleException("Host OS '$hostOs' is not supported in Kotlin/Native $project.")
}
hostTarget.apply {
binaries {
executable(listOf(DEBUG))
}
binaries.getTest("DEBUG").apply {
freeCompilerArgs += listOf("-Xlibrary-to-cover=${compilations["main"].output.classesDirs.singleFile.absolutePath}")
}
}
sourceSets {
val coverageMain by getting
val coverageTest by getting
}
}
tasks.create("createCoverageReport") {
dependsOn("coverageTest")
description = "Create coverage report"
doLast {
val testDebugBinary = kotlin.targets["coverage"].let { it as KotlinNativeTarget }.binaries.getTest("DEBUG").outputFile
exec {
commandLine("llvm-profdata", "merge", "$testDebugBinary.profraw", "-o", "$testDebugBinary.profdata")
}
exec {
commandLine("llvm-cov", "show", "$testDebugBinary", "-instr-profile", "$testDebugBinary.profdata")
}
}
}

Some files were not shown because too many files have changed in this diff Show More