-
Notifications
You must be signed in to change notification settings - Fork 25
/
ReplViewController.swift
498 lines (410 loc) · 22 KB
/
ReplViewController.swift
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
import UIKit
let messageFontSize: CGFloat = 14
let toolBarMinHeight: CGFloat = 44
let textViewMaxHeight: (portrait: CGFloat, landscape: CGFloat) = (portrait: 272, landscape: 90)
class ReplViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
let history: History
var tableView: UITableView!
var toolBar: UIToolbar!
var textView: UITextView!
var evalButton: UIButton!
var rotating = false
var textFieldHeightLayoutConstraint: NSLayoutConstraint!
var currentKeyboardHeight: CGFloat!
var initialized = false;
var enterPressed = false;
var scrollToBottom = false;
override var inputAccessoryView: UIView! {
get {
if toolBar == nil {
toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: toolBarMinHeight-0.5))
textView = InputTextView(frame: CGRect.zero)
textView.backgroundColor = UIColor(white: 250/255, alpha: 1)
textView.font = UIFont(name: "Menlo", size: messageFontSize)
textView.layer.borderColor = UIColor(red: 200/255, green: 200/255, blue: 205/255, alpha:1).cgColor
textView.layer.borderWidth = 0.5
textView.layer.cornerRadius = 5
textView.scrollsToTop = false
textView.textContainerInset = UIEdgeInsetsMake(6, 3, 6, 3)
textView.autocorrectionType = UITextAutocorrectionType.no;
textView.autocapitalizationType = UITextAutocapitalizationType.none;
textView.delegate = self
toolBar.addSubview(textView)
evalButton = UIButton(type: .system)
evalButton.isEnabled = false
evalButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
evalButton.setTitle("Eval", for: UIControlState())
evalButton.setTitleColor(UIColor(red: 142/255, green: 142/255, blue: 147/255, alpha: 1), for: .disabled)
evalButton.setTitleColor(UIColor(red: 1/255, green: 122/255, blue: 255/255, alpha: 1), for: UIControlState())
evalButton.contentEdgeInsets = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 8)
evalButton.addTarget(self, action: #selector(sendAction), for: UIControlEvents.touchUpInside)
toolBar.addSubview(evalButton)
toolBar.translatesAutoresizingMaskIntoConstraints = false
textView.translatesAutoresizingMaskIntoConstraints = false
evalButton.translatesAutoresizingMaskIntoConstraints = false
textFieldHeightLayoutConstraint = NSLayoutConstraint(item: textView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)
toolBar.addConstraint(textFieldHeightLayoutConstraint)
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .left, relatedBy: .equal, toItem: toolBar, attribute: .left, multiplier: 1, constant: 8))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: toolBar, attribute: .top, multiplier: 1, constant: 7.5))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .right, relatedBy: .equal, toItem: evalButton, attribute: .left, multiplier: 1, constant: -2))
toolBar.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: toolBar, attribute: .bottom, multiplier: 1, constant: -8))
toolBar.addConstraint(NSLayoutConstraint(item: evalButton, attribute: .right, relatedBy: .equal, toItem: toolBar, attribute: .right, multiplier: 1, constant: 0))
toolBar.addConstraint(NSLayoutConstraint(item: evalButton, attribute: .bottom, relatedBy: .equal, toItem: toolBar, attribute: .bottom, multiplier: 1, constant: -4.5))
}
return toolBar
}
}
required init?(coder aDecoder: NSCoder) {
self.history = History()
super.init(nibName: nil, bundle: nil)
//hidesBottomBarWhenPushed = true
self.currentKeyboardHeight = 0.0;
}
override var canBecomeFirstResponder : Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
history.loadedMessages = [
]
let whiteColor = UIColor.white
view.backgroundColor = whiteColor
tableView = UITableView(frame: CGRect(x: 0, y: 20, width: view.bounds.width, height: view.bounds.height-20), style: .plain)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = whiteColor
let edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: toolBarMinHeight, right: 0)
tableView.contentInset = edgeInsets
tableView.dataSource = self
tableView.delegate = self
tableView.keyboardDismissMode = .interactive
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
view.addSubview(tableView)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(menuControllerWillHide(_:)), name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil) // #CopyMessage
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setPrintCallback { (incoming: Bool, message: String?) -> Void in
DispatchQueue.main.async {
self.loadMessage(incoming, text: message!)
}
}
DispatchQueue.main.async {
self.loadMessage(false, text:"\nClojureScript " + appDelegate.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");
};
NSLog("Initializing...");
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.initializeJavaScriptEnvironment()
DispatchQueue.main.async {
// mark ready
NSLog("Ready");
self.initialized = true;
let hasText = self.textView.hasText
self.evalButton.isEnabled = hasText
if (hasText) {
self.runParinfer()
}
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//tableView.flashScrollIndicators()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//chat.draft = textView.text
}
// This gets called a lot. Perhaps there's a better way to know when `view.window` has been set?
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if true {
//textView.text = chat.draft
//chat.draft = ""
textViewDidChange(textView)
textView.becomeFirstResponder()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return history.loadedMessages.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.loadedMessages[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = NSStringFromClass(HistoryTableViewCell.self)
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! HistoryTableViewCell!
if cell == nil {
cell = HistoryTableViewCell(style: .default, reuseIdentifier: cellIdentifier)
// Add gesture recognizers #CopyMessage
let action: Selector = #selector(messageShowMenuAction(_:))
let doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: action)
doubleTapGestureRecognizer.numberOfTapsRequired = 2
cell?.messageLabel.addGestureRecognizer(doubleTapGestureRecognizer)
cell?.messageLabel.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: action))
}
let message = history.loadedMessages[indexPath.section][indexPath.row]
cell?.configureWithMessage(message)
return cell!
}
// Reserve row selection #CopyMessage
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Disable default keyboard shortcut where two spaces inserts a '.'
let currentText = textView.text
if (range.location > 0 &&
text == " " &&
currentText!.substring(with: currentText!.index(currentText!.startIndex, offsetBy: range.location-1)..<currentText!.index(currentText!.startIndex, offsetBy: range.location-1)) == " ") {
textView.text = (textView.text as NSString).replacingCharacters(in: range, with: " ")
textView.selectedRange = NSMakeRange(range.location+1, 0);
return false;
}
if (text == "\n") {
enterPressed = true;
}
return true;
}
func runParinfer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let currentText = textView.text
let currentSelectedRange = textView.selectedRange
if (currentText != "") {
let result: Array = appDelegate.parinferFormat(currentText, pos:Int32(currentSelectedRange.location), enterPressed:enterPressed)
textView.text = result[0] as! String
textView.selectedRange = NSMakeRange(result[1] as! Int, 0)
}
enterPressed = false;
}
// This is a native profile of Parinfer, meant for use when
// ClojureScript hasn't yet initialized, but yet the user
// is already typing. It covers extremely simple cases that
// could be typed immediately.
func runPoorMansParinfer() {
let currentText = textView.text
let currentSelectedRange = textView.selectedRange
if (currentText != "") {
if (currentSelectedRange.location == 1) {
if (currentText == "(") {
textView.text = "()";
} else if (currentText == "[") {
textView.text = "[]";
} else if (currentText == "{") {
textView.text = "{}";
}
textView.selectedRange = currentSelectedRange;
}
}
}
func textViewDidChange(_ textView: UITextView) {
if (initialized) {
runParinfer()
} else {
runPoorMansParinfer()
}
updateTextViewHeight()
evalButton.isEnabled = self.initialized && textView.hasText
}
func keyboardWillShow(_ notification: Notification) {
let userInfo = notification.userInfo as NSDictionary!
let frameNew = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let insetNewBottom = tableView.convert(frameNew, from: nil).height
let insetOld = tableView.contentInset
let insetChange = insetNewBottom - insetOld.bottom
let overflow = tableView.contentSize.height - (tableView.frame.height-insetOld.top-insetOld.bottom)
let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations: (() -> Void) = {
if !(self.tableView.isTracking || self.tableView.isDecelerating) {
// Move content with keyboard
if overflow > 0 { // scrollable before
self.tableView.contentOffset.y += insetChange
if self.tableView.contentOffset.y < -insetOld.top {
self.tableView.contentOffset.y = -insetOld.top
}
} else if insetChange > -overflow { // scrollable after
self.tableView.contentOffset.y += insetChange + overflow
}
}
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16)) // http://stackoverflow.com/a/18873820/242933
UIView.animate(withDuration: duration, delay: 0, options: options, animations: animations, completion: nil)
} else {
animations()
}
}
func keyboardDidShow(_ notification: Notification) {
let userInfo = notification.userInfo as NSDictionary!
let frameNew = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let insetNewBottom = tableView.convert(frameNew, from: nil).height
self.currentKeyboardHeight = frameNew.height
// Inset `tableView` with keyboard
let contentOffsetY = tableView.contentOffset.y
tableView.contentInset.bottom = insetNewBottom
tableView.scrollIndicatorInsets.bottom = insetNewBottom
// Prevents jump after keyboard dismissal
if self.tableView.isTracking || self.tableView.isDecelerating {
tableView.contentOffset.y = contentOffsetY
}
}
func updateTextViewHeight() {
let oldHeight = textView.frame.height
let newText = textView.text
let newSize = (newText as String!).boundingRect(with: CGSize(width: textView.frame.width - textView.textContainerInset.right - textView.textContainerInset.left - 10, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font!], context: nil)
let heightChange = newSize.height + textView.textContainerInset.top + textView.textContainerInset.bottom - oldHeight
let maxHeight = self.view.frame.height
- self.topLayoutGuide.length
- currentKeyboardHeight
+ toolBar.frame.height
- textView.textContainerInset.top
- textView.textContainerInset.bottom
- 20
if !(textFieldHeightLayoutConstraint.constant + heightChange > maxHeight){
//ceil because of small irregularities in heightChange
self.textFieldHeightLayoutConstraint.constant = ceil(heightChange + oldHeight)
//In order to ensure correct placement of text inside the textfield:
self.textView.setContentOffset(CGPoint.zero, animated: false)
//To ensure update of placement happens immediately
self.textView.layoutIfNeeded()
}
else{
self.textFieldHeightLayoutConstraint.constant = maxHeight
}
}
func markString(_ s: NSMutableAttributedString) -> Bool {
if (s.string.contains("\u{001b}[")) {
let text = s.string;
let range : Range<String.Index> = text.range(of: "\u{001b}[")!;
let index: Int = text.characters.distance(from: text.startIndex, to: range.lowerBound);
let index2 = text.characters.index(text.startIndex, offsetBy: index + 2);
var color : UIColor = UIColor.black;
if (text.substring(from: index2).hasPrefix("34m")){
color = UIColor.blue;
} else if (text.substring(from: index2).hasPrefix("32m")){
color = UIColor.init(colorLiteralRed: 0.0, green: 0.75, blue: 0.0, alpha: 1.0);
} else if (text.substring(from: index2).hasPrefix("35m")){
color = UIColor.init(colorLiteralRed: 0.75, green: 0.0, blue: 0.75, alpha: 1.0);
} else if (text.substring(from: index2).hasPrefix("31m")){
color = UIColor.init(colorLiteralRed: 1, green: 0.33, blue: 0.33, alpha: 1.0);
}
s.replaceCharacters(in: NSMakeRange(index, 5), with: "");
s.addAttribute(NSForegroundColorAttributeName,
value: color,
range: NSMakeRange(index, s.length-index));
return true;
}
return false;
}
func loadMessage(_ incoming: Bool, text: String) {
if (text != "\n") {
// NSLog("load: %@", text);
let s = NSMutableAttributedString(string:text)
while (markString(s)) {};
history.loadedMessages.append([Message(incoming: incoming, text: s)])
if (history.loadedMessages.count > 64) {
history.loadedMessages.remove(at: 0);
tableView.reloadData();
} else {
let lastSection = tableView.numberOfSections
tableView.beginUpdates()
tableView.insertSections(IndexSet(integer: lastSection), with: .automatic)
tableView.insertRows(at: [
IndexPath(row: 0, section: lastSection)
], with: .automatic)
tableView.endUpdates()
}
scrollToBottom = true;
let delayTime = DispatchTime.now() + Double(Int64(50 * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
if (self.scrollToBottom) {
self.scrollToBottom = false;
self.tableViewScrollToBottomAnimated(false)
}
}
}
}
func sendAction() {
// Autocomplete text before sending #hack
//textView.resignFirstResponder()
//textView.becomeFirstResponder()
let textToEvaluate = textView.text
loadMessage(false, text: textToEvaluate!)
textView.text = nil
updateTextViewHeight()
evalButton.isEnabled = false
// Dispatch to be evaluated
let delayTime = DispatchTime.now() + Double(Int64(50 * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.evaluate(textToEvaluate)
}
}
func tableViewScrollToBottomAnimated(_ animated: Bool) {
let numberOfSections = tableView.numberOfSections;
let numberOfRows = tableView.numberOfRows(inSection: numberOfSections-1)
if numberOfRows > 0 {
tableView.scrollToRow(at: IndexPath(row: numberOfRows-1, section: numberOfSections-1), at: .bottom, animated: animated)
}
}
// Handle actions #CopyMessage
// 1. Select row and show "Copy" menu
func messageShowMenuAction(_ gestureRecognizer: UITapGestureRecognizer) {
let twoTaps = (gestureRecognizer.numberOfTapsRequired == 2)
let doubleTap = (twoTaps && gestureRecognizer.state == .ended)
let longPress = (!twoTaps && gestureRecognizer.state == .began)
if doubleTap || longPress {
let pressedIndexPath = tableView.indexPathForRow(at: gestureRecognizer.location(in: tableView))!
tableView.selectRow(at: pressedIndexPath, animated: false, scrollPosition: .none)
let menuController = UIMenuController.shared
let bubbleImageView = gestureRecognizer.view!
menuController.setTargetRect(bubbleImageView.frame, in: bubbleImageView.superview!)
menuController.menuItems = [UIMenuItem(title: "Copy", action: #selector(messageCopyTextAction(_:)))]
menuController.setMenuVisible(true, animated: true)
}
}
// 2. Copy text to pasteboard
func messageCopyTextAction(_ menuController: UIMenuController) {
let selectedIndexPath = tableView.indexPathForSelectedRow
let selectedMessage = history.loadedMessages[selectedIndexPath!.section][selectedIndexPath!.row]
UIPasteboard.general.string = selectedMessage.text.string
}
// 3. Deselect row
func menuControllerWillHide(_ notification: Notification) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndexPath, animated: false)
}
(notification.object as! UIMenuController).menuItems = nil
}
override var keyCommands: [UIKeyCommand]? {
get {
let commandEnter = UIKeyCommand(input: "\r", modifierFlags: .command, action: #selector(sendAction))
return [commandEnter]
}
}
}
// Only show "Copy" when editing `textView` #CopyMessage
class InputTextView: UITextView {
override func canPerformAction(_ action: Selector, withSender sender: Any!) -> Bool {
if (delegate as! ReplViewController).tableView.indexPathForSelectedRow != nil {
return action == #selector(messageCopyTextAction(_:))
} else {
return super.canPerformAction(action, withSender: sender)
}
}
// More specific than implementing `nextResponder` to return `delegate`, which might cause side effects?
func messageCopyTextAction(_ menuController: UIMenuController) {
(delegate as! ReplViewController).messageCopyTextAction(menuController)
}
}