Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions examples/nitro-ui/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
node_modules/
.nitro/
.DS_Store
*.tsbuildinfo
**/xcuserdata/
android/.gradle/
android/.kotlin/
android/local.properties
android/**/build/
android/**/.cxx/

# Generated from the pinned public starter by scripts/setup-native.mjs.
/ios/
/android/
/AGENTS.md
/.agents/
/generated/
5 changes: 5 additions & 0 deletions examples/nitro-ui/Modules/ExampleTools/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
nitrogen/generated/
.build/
.swiftpm/

/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.margelo.nitro.app.exampletools

import android.content.Context
import com.margelo.nitroui.runtime.NitroActivity
import com.margelo.nitroui.runtime.NitroActivityInitializer
import java.lang.ref.WeakReference

/** Application services and the current presentation activity for this example only. */
object ExampleToolsModule : NitroActivityInitializer {
@Volatile private var context: Context? = null
@Volatile private var activity = WeakReference<NitroActivity>(null)

override fun onCreate(activity: NitroActivity) {
context = activity.applicationContext
this.activity = WeakReference(activity)
}

fun requireContext(): Context = context ?: error("ExampleTools needs an initialized application context")
fun requireActivity(): NitroActivity = activity.get() ?: error("ExampleTools needs an active screen")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.margelo.nitro.app.exampletools

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Build
import com.margelo.nitro.core.Callback
import com.margelo.nitro.core.Promise
import com.margelo.nitro.core.callAndForget
import java.io.File

/** App-only platform operations used by the SQLite example screens. */
class HybridExampleTools : HybridExampleToolsSpec() {
private val memory = ProcessMemorySampler()

override fun observeKeyboardInset(listener: Callback<(Double) -> Unit>) {
listener.callAndForget(0.0)
}
override fun stopObservingKeyboardInset() {}

override val osVersion: String get() = Build.VERSION.RELEASE
override val deviceModel: String get() = Build.MODEL

override fun copyText(text: String): Promise<Unit> {
val promise = Promise<Unit>()
val clipboard = ExampleToolsModule.requireContext().getSystemService(ClipboardManager::class.java)
?: error("The system clipboard is unavailable")
ExampleToolsModule.requireActivity().runOnUiThread {
try {
clipboard.setPrimaryClip(ClipData.newPlainText("Nitro SQLite", text))
promise.resolve(Unit)
} catch (error: Exception) {
promise.reject(error)
}
}
return promise
}

override fun shareText(text: String): Promise<Unit> {
val promise = Promise<Unit>()
val activity = ExampleToolsModule.requireActivity()
activity.runOnUiThread {
try {
val content = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, text)
}
activity.startActivity(Intent.createChooser(content, "Share benchmark report"))
promise.resolve(Unit)
} catch (error: Exception) {
promise.reject(error)
}
}
return promise
}

override fun getBundledSQLPath(): String {
val context = ExampleToolsModule.requireContext()
val file = File(context.cacheDir, "load-file-with-error.sql")
context.assets.open("load-file-with-error.sql").use { source ->
file.outputStream().use { source.copyTo(it) }
}
return file.absolutePath
}

override fun startMemorySampling(): Promise<Unit> {
val promise = Promise<Unit>()
memory.start { result ->
result.fold({ promise.resolve(Unit) }, { promise.reject(it) })
}
return promise
}

override fun stopMemorySampling(): Promise<ProcessMemorySample> {
val promise = Promise<ProcessMemorySample>()
memory.stop { result ->
result.fold({ sample ->
promise.resolve(ProcessMemorySample(
ProcessMemoryMetric.TOTALPSS,
sample.baselineBytes,
sample.peakBytes,
sample.intervalMs,
))
}, { promise.reject(it) })
}
return promise
}

override fun dispose() {
memory.close()
super.dispose()
}

protected fun finalize() {
memory.close()
}

companion object : HybridExampleToolsSpec.Companion {
override fun constructor() = HybridExampleTools()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.margelo.nitro.app.exampletools

import android.os.Debug
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

data class ProcessMemorySnapshot(
val baselineBytes: Double,
val peakBytes: Double,
val intervalMs: Double,
)

class ProcessMemorySampler : AutoCloseable {
private val scheduler = Executors.newSingleThreadScheduledExecutor { task ->
Thread(task, "nitro-sqlite-process-memory").apply { isDaemon = true }
}
private var sampling: ActiveSampling? = null

fun start(completion: (Result<Unit>) -> Unit) {
scheduler.execute {
completion(runCatching {
check(sampling == null) { "Memory sampling is already running" }
val baseline = currentPssBytes()
val timer = scheduler.scheduleAtFixedRate({ updatePeak() }, 0, 20, TimeUnit.MILLISECONDS)
sampling = ActiveSampling(baseline, baseline, timer)
})
}
}

fun stop(completion: (Result<ProcessMemorySnapshot>) -> Unit) {
scheduler.execute {
completion(runCatching {
val active = checkNotNull(sampling) { "Memory sampling has not started" }
active.timer.cancel(false)
updatePeak()
sampling = null
ProcessMemorySnapshot(active.baselineBytes.toDouble(), active.peakBytes.toDouble(), 20.0)
})
}
}

override fun close() {
if (scheduler.isShutdown) return
try {
scheduler.execute {
sampling?.timer?.cancel(false)
sampling = null
scheduler.shutdown()
}
} catch (error: RejectedExecutionException) {
if (!scheduler.isShutdown) throw error
}
}

private fun updatePeak() {
val active = sampling ?: return
active.peakBytes = maxOf(active.peakBytes, currentPssBytes())
}

private fun currentPssBytes(): Long {
val information = Debug.MemoryInfo()
Debug.getMemoryInfo(information)
return information.totalPss.toLong() * 1024
}

private class ActiveSampling(
val baselineBytes: Long,
var peakBytes: Long,
val timer: ScheduledFuture<*>,
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import Darwin
import Foundation
internal import NitroModules
import UIKit

final class HybridExampleTools: HybridExampleToolsSpec {
private let memory = ProcessMemorySampler()
private let keyboard = KeyboardInsetObserver()

func observeKeyboardInset(listener: any Callback<Double, Void>) throws {
DispatchQueue.main.async { [keyboard] in
keyboard.start { inset in
listener.callAndForget(inset)
}
}
}

func stopObservingKeyboardInset() throws {
DispatchQueue.main.async { [keyboard] in keyboard.stop() }
}

var osVersion: String { ProcessInfo.processInfo.operatingSystemVersionString }
var deviceModel: String {
if let simulator = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
return simulator
}
var system = utsname()
uname(&system)
let capacity = MemoryLayout.size(ofValue: system.machine)
return withUnsafePointer(to: &system.machine) { pointer in
pointer.withMemoryRebound(to: CChar.self, capacity: capacity) { String(cString: $0) }
}
}

func copyText(text: String) throws -> any Promise<Void> {
let promise = Promise_void.pending()
DispatchQueue.main.async {
UIPasteboard.general.string = text
promise.resolve()
}
return promise
}

func shareText(text: String) throws -> any Promise<Void> {
let promise = Promise_void.pending()
DispatchQueue.main.async {
guard
let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first,
let window = scene.windows.first(where: \.isKeyWindow),
var presenter = window.rootViewController
else {
promise.reject(
error: NSError(
domain: "ExampleTools", code: 1,
userInfo: [NSLocalizedDescriptionKey: "No active screen can present the share sheet"]))
return
}
while let presented = presenter.presentedViewController { presenter = presented }
let sheet = UIActivityViewController(activityItems: [text], applicationActivities: nil)
if let popover = sheet.popoverPresentationController {
popover.sourceView = presenter.view
popover.sourceRect = CGRect(
x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1)
}
presenter.present(sheet, animated: true) { promise.resolve() }
}
return promise
}

func getBundledSQLPath() throws -> String? {
Bundle.main.url(forResource: "load-file-with-error", withExtension: "sql")?.path
}

func startMemorySampling() throws -> any Promise<Void> {
let promise = Promise_void.pending()
memory.start { result in
switch result {
case .success: promise.resolve()
case .failure(let error): promise.reject(error: error)
}
}
return promise
}

func stopMemorySampling() throws -> any Promise<ProcessMemorySample> {
let promise = Promise___ExampleTools__ProcessMemorySample.pending()
memory.stop { result in
switch result {
case .success(let sample):
promise.resolve(
result: ProcessMemorySample(
metric: .physicalfootprint, baselineBytes: sample.baselineBytes,
peakBytes: sample.peakBytes, intervalMs: sample.intervalMs))
case .failure(let error): promise.reject(error: error)
}
}
return promise
}
}
Loading
Loading