forked from replete-repl/replete-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.kt
More file actions
526 lines (436 loc) · 17.2 KB
/
Copy pathMain.kt
File metadata and controls
526 lines (436 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
package replete
import android.annotation.TargetApi
import android.app.AlertDialog
import android.content.Context
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.*
import android.content.ClipData
import android.content.ClipboardManager
import android.content.res.Configuration
import android.os.*
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.DisplayMetrics
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import java.io.*
fun setTextSpanColor(s: SpannableString, color: Int, start: Int, end: Int) {
return s.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
}
fun markString(s: String): SpannableString {
var idx = 0
var rs = s as CharSequence
var ps = mutableListOf<Int>()
while (idx != -1) {
idx = rs.indexOfFirst { c -> c == "\u001B"[0] }
if (idx != -1) {
val color = when (rs.substring(idx + 2, idx + 4).toInt()) {
34 -> Color.BLUE
32 -> Color.rgb(0, 191, 0)
35 -> Color.rgb(191, 0, 191)
31 -> Color.rgb(255, 84, 84)
else -> null
}
rs = rs.substring(0, idx).plus(rs.substring(idx + 5, rs.length))
if (color != null) {
ps.add(color)
}
ps.add(idx)
}
}
val srs = SpannableString(rs)
while (srs.isNotEmpty() && ps.size >= 3) {
setTextSpanColor(srs, ps[0], ps[1], ps[2])
ps = ps.subList(3, ps.size)
}
return srs
}
enum class Messages(val value: Int) {
INIT_VM(0),
INIT_ENV(1),
BOOTSTRAP_ENV(2),
EVAL(3),
ADD_ERROR_ITEM(4),
ADD_OUTPUT_ITEM(5),
ADD_INPUT_ITEM(6),
ENABLE_EVAL(7),
ENABLE_PRINTING(8),
UPDATE_WIDTH(9),
SET_WIDTH(10),
VM_LOADED(11),
CALL_FN(12),
RELEASE_OBJ(13),
RUN_PARINFER(14),
APPLY_PARINFER(15),
NS_LOADED(16),
}
@TargetApi(Build.VERSION_CODES.O)
class MainActivity : AppCompatActivity() {
private var isVMLoaded = false
private var adapter: HistoryAdapter? = null
private fun bundleGetContents(path: String): String? {
return try {
val reader = assets.open("out/$path").bufferedReader()
val ret = reader.readText()
reader.close()
ret
} catch (e: IOException) {
null
}
}
private fun getClojureScriptVersion(): String {
val s = bundleGetContents("replete/bundle.js")
return s?.substring(29, s.length)?.takeWhile { c -> c != " ".toCharArray()[0] } ?: ""
}
private fun runPoorMansParinfer(inputField: EditText, s: Editable) {
val cursorPos = inputField.selectionStart
if (cursorPos == 1) {
when (s.toString()) {
"(" -> s.append(")")
"[" -> s.append("]")
"{" -> s.append("}")
}
inputField.setSelection(cursorPos)
}
}
private fun applyParinfer(args: Array<*>) {
val s = inputField!!.text
val origText = args[0] as String
val text = args[1] as String
val cursor = args[2] as Int
if (s.toString() == origText) {
s.replace(0, s.length, text)
inputField!!.setSelection(cursor)
}
}
private fun displayError(error: String) {
adapter!!.update(Item(SpannableString(error), ItemType.ERROR))
}
private fun displayInput(input: String) {
adapter!!.update(Item(SpannableString(input), ItemType.INPUT))
}
private fun displayOutput(output: SpannableString) {
if (!suppressPrinting) {
adapter!!.update(Item(output, ItemType.OUTPUT))
}
}
private fun toAbsolutePath(path: String): File {
return filesDir.resolve(if (path.startsWith("/")) path.drop(1) else path)
}
private var selectedPosition = -1
private var selectedView: View? = null
private fun isRequire(s: String): Boolean {
return s.trimStart().startsWith("(require")
}
private fun isMacro(s: String): Boolean {
val _s = s.trimStart()
return _s.startsWith("(defmacro") || _s.startsWith("(defmacfn")
}
private var consentedToChivorcam = false
private var suppressPrinting = false
private fun defmacroCalled(s: String) {
if (consentedToChivorcam) {
suppressPrinting = true
eval("(require '[chivorcam.core :refer [defmacro defmacfn]])")
eval(s)
} else {
val builder = AlertDialog.Builder(this)
builder.setTitle("Enable REPL\nMacro Definitions?")
builder.setMessage(
"ClojureScript macros must be defined in a separate namespace and required appropriately." +
"\n\nFor didactic purposes, we can support defining macros directly in the Replete REPL. " +
"\n\nAny helper functions called during macroexpansion must be defined using defmacfn in lieu of defn."
)
builder.setPositiveButton(
"OK"
) { dialog, id ->
consentedToChivorcam = true
suppressPrinting = true
eval("(require '[chivorcam.core :refer [defmacro defmacfn]])")
eval(s)
}
builder.setNegativeButton(
"Cancel"
) { dialog, id ->
dialog.cancel()
}
builder.show()
}
}
var isExecutingTask = false
private fun disableEvalButton() {
isExecutingTask = true
evalButton!!.isEnabled = false
evalButton!!.setTextColor(Color.GRAY)
}
private fun enableEvalButton(withCheck: Boolean = false) {
val shouldEnable = if (withCheck) inputField!!.text.isNotEmpty() else true
if (shouldEnable) {
evalButton!!.isEnabled = true
evalButton!!.setTextColor(Color.rgb(0, 153, 204))
isExecutingTask = false
}
}
private fun eval(input: String) {
disableEvalButton()
sendThMessage(Messages.EVAL, input)
}
private fun updateWidth() {
if (isVMLoaded) {
val replHistory: ListView = findViewById(R.id.repl_history)
val width: Double = (replHistory.width / 29).toDouble()
sendThMessage(Messages.SET_WIDTH, width)
}
}
private var deviceType: String? = null
private fun setDeviceType() {
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
val yInches = metrics.heightPixels / metrics.ydpi;
val xInches = metrics.widthPixels / metrics.xdpi;
val diagonalInches = Math.sqrt((xInches * xInches + yInches * yInches).toDouble());
deviceType = if (diagonalInches >= 6.5) {
"iPad"
} else {
"iPhone"
}
}
val fadeIn = AlphaAnimation(0.3f, 1.0f)
val fadeOut = AlphaAnimation(1.0f, 0.3f)
private fun stopLoadingItem() {
fadeIn.cancel()
fadeIn.reset()
fadeOut.reset()
}
private fun startLoadingItem(view: View) {
val duration: Long = 500
fadeIn.duration = duration
fadeIn.fillAfter = true
fadeOut.duration = duration
fadeOut.fillAfter = true
fadeOut.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) {
view.startAnimation(fadeIn)
}
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
})
fadeIn.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) {
view.startAnimation(fadeOut)
}
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
})
view.startAnimation(fadeOut)
}
override fun onConfigurationChanged(cfg: Configuration) {
if (resources.configuration.orientation != cfg.orientation) {
updateWidth()
}
}
var evalButton: Button? = null
var openBracketButton: Button? = null
var historyUpButton: Button? = null
var historyDownButton: Button? = null
var inputField: EditText? = null
var uiHandler: Handler? = null
var thHandler: Handler? = null
var ht: HandlerThread? = null
private fun sendThMessage(what: Messages, obj: Any? = null) {
if (obj != null) {
thHandler!!.sendMessage(thHandler!!.obtainMessage(what.value, obj))
} else {
thHandler!!.sendMessage(thHandler!!.obtainMessage(what.value))
}
}
private fun sendUIMessage(what: Messages, obj: Any? = null) {
if (obj != null) {
uiHandler!!.sendMessage(uiHandler!!.obtainMessage(what.value, obj))
} else {
uiHandler!!.sendMessage(uiHandler!!.obtainMessage(what.value))
}
}
private fun initializeVMThread() {
ht = HandlerThread("VMThread")
ht!!.start()
thHandler = VMHandler(
ht!!,
{ what, obj -> sendUIMessage(what, obj) },
{ s -> bundleGetContents(s) },
{ s -> toAbsolutePath(s) }
)
sendThMessage(Messages.INIT_VM)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var historyPosition = 0
var sessionList = ArrayList<String>()
uiHandler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
when (msg.what) {
Messages.ADD_INPUT_ITEM.value -> displayInput(msg.obj as String)
Messages.ADD_OUTPUT_ITEM.value -> displayOutput(msg.obj as SpannableString)
Messages.ADD_ERROR_ITEM.value -> displayError(msg.obj as String)
Messages.ENABLE_EVAL.value -> enableEvalButton()
Messages.ENABLE_PRINTING.value -> suppressPrinting = false
Messages.UPDATE_WIDTH.value -> updateWidth()
Messages.VM_LOADED.value -> isVMLoaded = true
Messages.APPLY_PARINFER.value -> applyParinfer(msg.obj as Array<*>)
}
}
}
initializeVMThread()
setDeviceType()
setContentView(R.layout.activity_main)
val replHistory: ListView = findViewById(R.id.repl_history)
inputField = findViewById(R.id.input)
evalButton = findViewById(R.id.eval_button)
historyUpButton = findViewById(R.id.history_up)
historyDownButton = findViewById(R.id.history_down)
inputField!!.hint = "Type in here"
inputField!!.setHintTextColor(Color.GRAY)
evalButton!!.isEnabled = false
evalButton!!.setTextColor(Color.GRAY)
openBracketButton = findViewById(R.id.insert_open_bracket)
adapter = HistoryAdapter(this, R.layout.list_item, replHistory)
replHistory.adapter = adapter
replHistory.divider = null
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
replHistory.setOnItemClickListener { parent, view, position, id ->
val item = parent.getItemAtPosition(position) as Item
if (item.type == ItemType.INPUT) {
if (position == selectedPosition) {
selectedPosition = -1
view.setBackgroundColor(Color.rgb(255, 255, 255))
} else {
if (selectedPosition != -1 && selectedView != null) {
(selectedView as View).setBackgroundColor(Color.rgb(255, 255, 255))
}
selectedPosition = position
view.setBackgroundColor(Color.rgb(219, 220, 255))
selectedView = view
(selectedView as View).startActionMode(object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val inflater = mode.menuInflater
inflater.inflate(R.menu.menu_actions, menu)
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return when (item.itemId) {
R.id.copy_action -> {
val sitem = parent.getItemAtPosition(selectedPosition) as Item
clipboard.primaryClip = ClipData.newPlainText("input", sitem.text)
selectedPosition = -1
(selectedView as View).setBackgroundColor(Color.rgb(255, 255, 255))
mode.finish()
true
}
else -> false
}
}
override fun onDestroyActionMode(mode: ActionMode?) {
}
}, ActionMode.TYPE_FLOATING)
}
}
}
var isParinferChange = false
var enterPressed = false
inputField!!.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (s != null) {
evalButton!!.isEnabled = !s.isNullOrEmpty() and isVMLoaded and !isExecutingTask
if (evalButton!!.isEnabled) {
evalButton!!.setTextColor(Color.rgb(0, 153, 204))
} else {
evalButton!!.setTextColor(Color.GRAY)
}
if (!s.isNullOrEmpty() && !isParinferChange) {
isParinferChange = true
if (isVMLoaded) {
val cursorPos = inputField!!.selectionStart
thHandler!!.sendMessageAtFrontOfQueue(
thHandler!!.obtainMessage(
Messages.RUN_PARINFER.value,
arrayOf(s.toString(), enterPressed, cursorPos)
)
)
enterPressed = false
} else {
runPoorMansParinfer(inputField!!, s)
}
} else {
isParinferChange = false
}
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (p0 != null && p0.length > p1 && p0[p1] == "\n"[0]) {
enterPressed = true
}
}
})
evalButton!!.setOnClickListener { v ->
val input = inputField!!.text.toString()
inputField!!.text.clear()
sendUIMessage(Messages.ADD_INPUT_ITEM, input)
sessionList.add(input)
historyPosition = sessionList.size
try {
if (isMacro(input)) {
defmacroCalled(input)
} else {
eval(input)
}
} catch (e: Exception) {
sendUIMessage(Messages.ADD_ERROR_ITEM, e.toString())
}
}
openBracketButton!!.setOnClickListener { v ->
val cursorPos = inputField!!.getSelectionStart()
inputField!!.text.insert(cursorPos ,"(")
}
historyUpButton!!.setOnClickListener { v ->
if (historyPosition > 0) {
historyPosition--
val histItem = sessionList.get(historyPosition)
inputField!!.setText(histItem)
}
}
historyDownButton!!.setOnClickListener { v ->
if (historyPosition < sessionList.size -1) {
historyPosition++
val histItem = sessionList.get(historyPosition)
inputField!!.setText(histItem)
} else {
inputField!!.text.clear()
historyPosition = sessionList.size
}
}
sendUIMessage(
Messages.ADD_INPUT_ITEM, "\nClojureScript ${getClojureScriptVersion()}\n" +
" Docs: (doc function-name)\n" +
" (find-doc \"part-of-name\")\n" +
" Source: (source function-name)\n" +
" Results: Stored in *1, *2, *3,\n" +
" an exception in *e\n"
)
sendThMessage(Messages.INIT_ENV)
sendThMessage(Messages.BOOTSTRAP_ENV, deviceType)
}
}