package android.os class Looper { companion object { val owner=Thread.currentThread();private val main=Looper();private val other=Looper() fun getMainLooper()=main fun myLooper()=if(Thread.currentThread()===owner) main else other } } class HandlerThread(val name: String) { val looper=Looper();var quit=false fun start() { threads+=this } fun quitSafely(): Boolean {quit=true;return true} companion object {val threads=mutableListOf()} } object SystemClock { fun elapsedRealtime()=CameraClock.now } class Handler(val looper: Looper=Looper.getMainLooper()) { fun post(r: Runnable): Boolean=postDelayed(r,0) fun postDelayed(r: Runnable,ms: Long): Boolean {CameraClock.add(this,r,ms);return true} fun removeCallbacks(r: Runnable) {CameraClock.remove(this,r)} } object CameraClock { @Volatile var now=0L private data class Task(val h: Handler,val r: Runnable,val due: Long,val order: Long) private val tasks=java.util.PriorityQueue(compareBy {it.due}.thenBy {it.order}) var paused=mutableSetOf() var pausedLoopers=mutableSetOf() private var serial=0L @Synchronized fun add(h: Handler,r: Runnable,ms: Long) {tasks.add(Task(h,r,now+ms,serial++))} @Synchronized fun remove(h: Handler,r: Runnable) {tasks.removeIf {it.h===h && it.r===r}} @Synchronized fun reset() {tasks.clear();paused.clear();pausedLoopers.clear();now=0;serial=0} fun advance(ms: Long=0) { val end=now+ms while(true) { val task=synchronized(this) {tasks.filter {it.due<=end && it.h !in paused && it.h.looper !in pausedLoopers}.minWithOrNull(compareBy {it.due}.thenBy {it.order})?.also {tasks.remove(it)}} ?: break now=maxOf(now,task.due);task.r.run() };now=maxOf(now,end) } fun await(condition: ()->Boolean) { val deadline=System.nanoTime()+3_000_000_000 while(!condition()) {advance();check(System.nanoTime()