1 // Copyright 2015-present 650 Industries. All rights reserved. 2 package host.exp.exponent.utils 3 4 import android.os.Handler 5 import android.util.Log 6 import androidx.test.uiautomator.Configurator 7 import androidx.test.uiautomator.UiDevice 8 import host.exp.exponent.test.TestActionEvent 9 import androidx.test.uiautomator.UiSelector 10 import androidx.test.uiautomator.UiObject 11 import de.greenrobot.event.EventBus 12 import host.exp.exponent.test.TestResolvePromiseEvent 13 import java.lang.Exception 14 import java.lang.RuntimeException 15 16 class TestNativeModuleServer private constructor() { 17 var uiDevice: UiDevice? = null 18 onEventnull19 fun onEvent(event: TestActionEvent) { 20 if (event.delay <= 0) { 21 performAction(event) 22 } else { 23 Handler().postDelayed({ performAction(event) }, event.delay.toLong()) 24 } 25 } 26 performActionnull27 private fun performAction(event: TestActionEvent) { 28 synchronized(this) { 29 try { 30 Configurator.getInstance().waitForSelectorTimeout = event.timeout.toLong() 31 val selector = getSelectorForObject(event) 32 val obj = uiDevice!!.findObject(selector) 33 runActionOnObject(event, obj) 34 } catch (e: Throwable) { 35 Log.d(TAG, "Error in performAction: $e") 36 } finally { 37 EventBus.getDefault().post(TestResolvePromiseEvent(event.id)) 38 } 39 } 40 } 41 getSelectorForObjectnull42 private fun getSelectorForObject(event: TestActionEvent): UiSelector { 43 return when (event.selectorType) { 44 "text" -> UiSelector().text(event.selectorValue) 45 else -> throw RuntimeException("No selector found for type " + event.selectorType) 46 } 47 } 48 runActionOnObjectnull49 private fun runActionOnObject(event: TestActionEvent, `object`: UiObject) { 50 try { 51 when (event.actionType) { 52 "click" -> `object`.click() 53 else -> throw RuntimeException("No action found for type " + event.actionType) 54 } 55 } catch (e: Exception) { 56 throw RuntimeException(e.toString()) 57 } 58 } 59 60 companion object { 61 private val TAG = TestNativeModuleServer::class.java.simpleName 62 <lambda>null63 @JvmStatic val instance: TestNativeModuleServer by lazy { 64 TestNativeModuleServer() 65 } 66 } 67 68 init { 69 EventBus.getDefault().register(this) 70 } 71 } 72