1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "Terminal"
18 
19 #include <utils/Log.h>
20 #include <utils/Mutex.h>
21 #include "android_runtime/AndroidRuntime.h"
22 
23 #include "jni.h"
24 #include <nativehelper/JNIHelp.h>
25 #include <nativehelper/ScopedLocalRef.h>
26 #include <nativehelper/ScopedPrimitiveArray.h>
27 
28 #include <fcntl.h>
29 #include <pty.h>
30 #include <cstdio>
31 #include <termios.h>
32 #include <unistd.h>
33 
34 #include <vterm.h>
35 
36 #include <cstring>
37 
38 #define USE_TEST_SHELL 0
39 #define DEBUG_CALLBACKS 0
40 #define DEBUG_IO 0
41 #define DEBUG_SCROLLBACK 0
42 
43 namespace android {
44 
45 /*
46  * Callback class reference
47  */
48 static jclass terminalCallbacksClass;
49 
50 /*
51  * Callback methods
52  */
53 static jmethodID damageMethod;
54 static jmethodID moveRectMethod;
55 static jmethodID moveCursorMethod;
56 static jmethodID setTermPropBooleanMethod;
57 static jmethodID setTermPropIntMethod;
58 static jmethodID setTermPropStringMethod;
59 static jmethodID setTermPropColorMethod;
60 static jmethodID bellMethod;
61 
62 /*
63  * CellRun class
64  */
65 static jclass cellRunClass;
66 static jfieldID cellRunDataField;
67 static jfieldID cellRunDataSizeField;
68 static jfieldID cellRunColSizeField;
69 static jfieldID cellRunFgField;
70 static jfieldID cellRunBgField;
71 
72 typedef short unsigned int dimen_t;
73 
74 class ScrollbackLine {
75 public:
ScrollbackLine(dimen_t _cols)76     inline ScrollbackLine(dimen_t _cols) : cols(_cols) {
77         mCells = new VTermScreenCell[cols];
78     };
~ScrollbackLine()79     inline ~ScrollbackLine() {
80         delete mCells;
81     }
82 
copyFrom(dimen_t cols,const VTermScreenCell * cells)83     inline dimen_t copyFrom(dimen_t cols, const VTermScreenCell* cells) {
84         dimen_t n = this->cols > cols ? cols : this->cols;
85         memcpy(mCells, cells, sizeof(VTermScreenCell) * n);
86         return n;
87     }
88 
copyTo(dimen_t cols,VTermScreenCell * cells)89     inline dimen_t copyTo(dimen_t cols, VTermScreenCell* cells) {
90         dimen_t n = cols > this->cols ? this->cols : cols;
91         memcpy(cells, mCells, sizeof(VTermScreenCell) * n);
92         return n;
93     }
94 
getCell(dimen_t col,VTermScreenCell * cell)95     inline void getCell(dimen_t col, VTermScreenCell* cell) {
96         *cell = mCells[col];
97     }
98 
99     const dimen_t cols;
100 
101 private:
102     VTermScreenCell* mCells;
103 };
104 
105 /*
106  * Terminal session
107  */
108 class Terminal {
109 public:
110     Terminal(jobject callbacks);
111     ~Terminal();
112 
113     status_t run();
114 
115     size_t write(const char *bytes, size_t len);
116 
117     bool dispatchCharacter(int mod, int character);
118     bool dispatchKey(int mod, int key);
119     bool flushInput();
120 
121     status_t resize(dimen_t rows, dimen_t cols, dimen_t scrollRows);
122 
123     status_t onPushline(dimen_t cols, const VTermScreenCell* cells);
124     status_t onPopline(dimen_t cols, VTermScreenCell* cells);
125 
126     void getCellLocked(VTermPos pos, VTermScreenCell* cell);
127 
128     dimen_t getRows() const;
129     dimen_t getCols() const;
130     dimen_t getScrollRows() const;
131 
132     jobject getCallbacks() const;
133 
134     // Lock protecting mutations of internal libvterm state
135     Mutex mLock;
136 
137 private:
138     int mMasterFd;
139     pid_t mChildPid;
140     VTerm *mVt;
141     VTermScreen *mVts;
142 
143     jobject mCallbacks;
144 
145     dimen_t mRows;
146     dimen_t mCols;
147     bool mKilled;
148 
149     ScrollbackLine **mScroll;
150     dimen_t mScrollCur;
151     dimen_t mScrollSize;
152 
153 };
154 
155 /*
156  * VTerm event handlers
157  */
158 
term_damage(VTermRect rect,void * user)159 static int term_damage(VTermRect rect, void *user) {
160     Terminal* term = reinterpret_cast<Terminal*>(user);
161 #if DEBUG_CALLBACKS
162     ALOGW("term_damage");
163 #endif
164 
165     JNIEnv* env = AndroidRuntime::getJNIEnv();
166     return env->CallIntMethod(term->getCallbacks(), damageMethod, rect.start_row, rect.end_row,
167             rect.start_col, rect.end_col);
168 }
169 
term_moverect(VTermRect dest,VTermRect src,void * user)170 static int term_moverect(VTermRect dest, VTermRect src, void *user) {
171     Terminal* term = reinterpret_cast<Terminal*>(user);
172 #if DEBUG_CALLBACKS
173     ALOGW("term_moverect");
174 #endif
175 
176     JNIEnv* env = AndroidRuntime::getJNIEnv();
177     return env->CallIntMethod(term->getCallbacks(), moveRectMethod,
178             dest.start_row, dest.end_row, dest.start_col, dest.end_col,
179             src.start_row, src.end_row, src.start_col, src.end_col);
180 }
181 
term_movecursor(VTermPos pos,VTermPos oldpos,int visible,void * user)182 static int term_movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user) {
183     Terminal* term = reinterpret_cast<Terminal*>(user);
184 #if DEBUG_CALLBACKS
185     ALOGW("term_movecursor");
186 #endif
187 
188     JNIEnv* env = AndroidRuntime::getJNIEnv();
189     return env->CallIntMethod(term->getCallbacks(), moveCursorMethod, pos.row,
190             pos.col, oldpos.row, oldpos.col, visible);
191 }
192 
term_settermprop(VTermProp prop,VTermValue * val,void * user)193 static int term_settermprop(VTermProp prop, VTermValue *val, void *user) {
194     Terminal* term = reinterpret_cast<Terminal*>(user);
195 #if DEBUG_CALLBACKS
196     ALOGW("term_settermprop");
197 #endif
198 
199     JNIEnv* env = AndroidRuntime::getJNIEnv();
200     switch (vterm_get_prop_type(prop)) {
201     case VTERM_VALUETYPE_BOOL:
202         return env->CallIntMethod(term->getCallbacks(), setTermPropBooleanMethod, prop,
203                 val->boolean ? JNI_TRUE : JNI_FALSE);
204     case VTERM_VALUETYPE_INT:
205         return env->CallIntMethod(term->getCallbacks(), setTermPropIntMethod, prop, val->number);
206     case VTERM_VALUETYPE_STRING:
207         return env->CallIntMethod(term->getCallbacks(), setTermPropStringMethod, prop,
208                 env->NewStringUTF(val->string));
209     case VTERM_VALUETYPE_COLOR:
210         return env->CallIntMethod(term->getCallbacks(), setTermPropIntMethod, prop,
211                 val->color.rgb.red, val->color.rgb.green, val->color.rgb.blue);
212     default:
213         ALOGE("unknown callback type");
214         return 0;
215     }
216 }
217 
term_bell(void * user)218 static int term_bell(void *user) {
219     Terminal* term = reinterpret_cast<Terminal*>(user);
220 #if DEBUG_CALLBACKS
221     ALOGW("term_bell");
222 #endif
223 
224     JNIEnv* env = AndroidRuntime::getJNIEnv();
225     return env->CallIntMethod(term->getCallbacks(), bellMethod);
226 }
227 
term_sb_pushline(int cols,const VTermScreenCell * cells,void * user)228 static int term_sb_pushline(int cols, const VTermScreenCell *cells, void *user) {
229     Terminal* term = reinterpret_cast<Terminal*>(user);
230 #if DEBUG_CALLBACKS
231     ALOGW("term_sb_pushline");
232 #endif
233 
234     return term->onPushline(cols, cells);
235 }
236 
term_sb_popline(int cols,VTermScreenCell * cells,void * user)237 static int term_sb_popline(int cols, VTermScreenCell *cells, void *user) {
238     Terminal* term = reinterpret_cast<Terminal*>(user);
239 #if DEBUG_CALLBACKS
240     ALOGW("term_sb_popline");
241 #endif
242 
243     return term->onPopline(cols, cells);
244 }
245 
246 static VTermScreenCallbacks cb = {
247     .damage = term_damage,
248     .moverect = term_moverect,
249     .movecursor = term_movecursor,
250     .settermprop = term_settermprop,
251     .bell = term_bell,
252     // Resize requests are applied immediately, so callback is ignored
253     .resize = NULL,
254     .sb_pushline = term_sb_pushline,
255     .sb_popline = term_sb_popline,
256 };
257 
Terminal(jobject callbacks)258 Terminal::Terminal(jobject callbacks) :
259         mCallbacks(callbacks), mRows(25), mCols(80), mKilled(false),
260         mScrollCur(0), mScrollSize(100) {
261     JNIEnv* env = AndroidRuntime::getJNIEnv();
262     mCallbacks = env->NewGlobalRef(callbacks);
263 
264     mScroll = new ScrollbackLine*[mScrollSize];
265     memset(mScroll, 0, sizeof(ScrollbackLine*) * mScrollSize);
266 
267     /* Create VTerm */
268     mVt = vterm_new(mRows, mCols);
269     vterm_set_utf8(mVt, 1);
270 
271     /* Set up screen */
272     mVts = vterm_obtain_screen(mVt);
273     vterm_screen_enable_altscreen(mVts, 1);
274     vterm_screen_set_callbacks(mVts, &cb, this);
275     vterm_screen_set_damage_merge(mVts, VTERM_DAMAGE_SCROLL);
276     vterm_screen_reset(mVts, 1);
277 }
278 
~Terminal()279 Terminal::~Terminal() {
280     close(mMasterFd);
281     ::kill(mChildPid, SIGHUP);
282 
283     vterm_free(mVt);
284 
285     delete mScroll;
286 
287     JNIEnv *env = AndroidRuntime::getJNIEnv();
288     env->DeleteGlobalRef(mCallbacks);
289 }
290 
run()291 status_t Terminal::run() {
292     struct termios termios;
293     memset(&termios, 0, sizeof(termios));
294     termios.c_iflag = ICRNL|IXON|IUTF8;
295     termios.c_oflag = OPOST|ONLCR|NL0|CR0|TAB0|BS0|VT0|FF0;
296     termios.c_cflag = CS8|CREAD;
297     termios.c_lflag = ISIG|ICANON|IEXTEN|ECHO|ECHOE|ECHOK;
298 
299     cfsetispeed(&termios, B38400);
300     cfsetospeed(&termios, B38400);
301 
302     termios.c_cc[VINTR]    = 0x1f & 'C';
303     termios.c_cc[VQUIT]    = 0x1f & '\\';
304     termios.c_cc[VERASE]   = 0x7f;
305     termios.c_cc[VKILL]    = 0x1f & 'U';
306     termios.c_cc[VEOF]     = 0x1f & 'D';
307     termios.c_cc[VSTART]   = 0x1f & 'Q';
308     termios.c_cc[VSTOP]    = 0x1f & 'S';
309     termios.c_cc[VSUSP]    = 0x1f & 'Z';
310     termios.c_cc[VREPRINT] = 0x1f & 'R';
311     termios.c_cc[VWERASE]  = 0x1f & 'W';
312     termios.c_cc[VLNEXT]   = 0x1f & 'V';
313     termios.c_cc[VMIN]     = 1;
314     termios.c_cc[VTIME]    = 0;
315 
316     struct winsize size = { mRows, mCols, 0, 0 };
317 
318     int stderr_save_fd = dup(2);
319     if (stderr_save_fd < 0) {
320         ALOGE("failed to dup stderr - %s", strerror(errno));
321     }
322 
323     mChildPid = forkpty(&mMasterFd, NULL, &termios, &size);
324     if (mChildPid == 0) {
325         /* Restore the ISIG signals back to defaults */
326         signal(SIGINT, SIG_DFL);
327         signal(SIGQUIT, SIG_DFL);
328         signal(SIGSTOP, SIG_DFL);
329         signal(SIGCONT, SIG_DFL);
330 
331         FILE *stderr_save = fdopen(stderr_save_fd, "a");
332 
333         if (!stderr_save) {
334             ALOGE("failed to open stderr - %s", strerror(errno));
335         }
336 
337         // We know execvp(2) won't actually try to modify this.
338         char *shell = const_cast<char*>("/system/bin/sh");
339 #if USE_TEST_SHELL
340         char *arg1 = const_cast<char*>("-c");
341         char *arg2 = const_cast<char*>("x=1; c=0; while true; do echo -e \"stop \e[00;3${c}mechoing\e[00m yourself! ($x)\"; x=$(( $x + 1 )); c=$((($c+1)%7)); if [ $x -gt 110 ]; then sleep 0.5; fi; done");
342         char *args[4] = {shell, arg1, arg2, NULL};
343 #else
344         char *args[2] = {shell, NULL};
345 #endif
346 
347         execvp(shell, args);
348         fprintf(stderr_save, "Cannot exec(%s) - %s\n", shell, strerror(errno));
349         _exit(1);
350     }
351 
352     ALOGD("entering read() loop");
353     while (1) {
354         char buffer[4096];
355         ssize_t bytes = ::read(mMasterFd, buffer, sizeof buffer);
356 #if DEBUG_IO
357         ALOGD("read() returned %d bytes", bytes);
358 #endif
359 
360         if (mKilled) {
361             ALOGD("kill() requested");
362             break;
363         }
364         if (bytes == 0) {
365             ALOGD("read() found EOF");
366             break;
367         }
368         if (bytes == -1) {
369             ALOGE("read() failed: %s", strerror(errno));
370             return 1;
371         }
372 
373         {
374             Mutex::Autolock lock(mLock);
375             vterm_input_write(mVt, buffer, bytes);
376             vterm_screen_flush_damage(mVts);
377         }
378     }
379 
380     return 0;
381 }
382 
write(const char * bytes,size_t len)383 size_t Terminal::write(const char *bytes, size_t len) {
384     return ::write(mMasterFd, bytes, len);
385 }
386 
dispatchCharacter(int mod,int character)387 bool Terminal::dispatchCharacter(int mod, int character) {
388     Mutex::Autolock lock(mLock);
389     vterm_keyboard_unichar(mVt, character, static_cast<VTermModifier>(mod));
390     return flushInput();
391 }
392 
dispatchKey(int mod,int key)393 bool Terminal::dispatchKey(int mod, int key) {
394     Mutex::Autolock lock(mLock);
395     vterm_keyboard_key(mVt, static_cast<VTermKey>(key), static_cast<VTermModifier>(mod));
396     return flushInput();
397 }
398 
flushInput()399 bool Terminal::flushInput() {
400     size_t len = vterm_output_get_buffer_current(mVt);
401     if (len) {
402         char buf[len];
403         len = vterm_output_read(mVt, buf, len);
404         return len == write(buf, len);
405     }
406     return true;
407 }
408 
resize(dimen_t rows,dimen_t cols,dimen_t scrollRows)409 status_t Terminal::resize(dimen_t rows, dimen_t cols, dimen_t scrollRows) {
410     Mutex::Autolock lock(mLock);
411 
412     ALOGD("resize(%d, %d, %d)", rows, cols, scrollRows);
413 
414     mRows = rows;
415     mCols = cols;
416     // TODO: resize scrollback
417 
418     struct winsize size = { rows, cols, 0, 0 };
419     ioctl(mMasterFd, TIOCSWINSZ, &size);
420 
421     vterm_set_size(mVt, rows, cols);
422     vterm_screen_flush_damage(mVts);
423 
424     return 0;
425 }
426 
onPushline(dimen_t cols,const VTermScreenCell * cells)427 status_t Terminal::onPushline(dimen_t cols, const VTermScreenCell* cells) {
428     ScrollbackLine* line = NULL;
429     if (mScrollCur == mScrollSize) {
430         /* Recycle old row if it's the right size */
431         if (mScroll[mScrollCur - 1]->cols == cols) {
432             line = mScroll[mScrollCur - 1];
433         } else {
434             delete mScroll[mScrollCur - 1];
435         }
436 
437         memmove(mScroll + 1, mScroll, sizeof(ScrollbackLine*) * (mScrollCur - 1));
438     } else if (mScrollCur > 0) {
439         memmove(mScroll + 1, mScroll, sizeof(ScrollbackLine*) * mScrollCur);
440     }
441 
442     if (line == NULL) {
443         line = new ScrollbackLine(cols);
444     }
445 
446     mScroll[0] = line;
447 
448     if (mScrollCur < mScrollSize) {
449         mScrollCur++;
450     }
451 
452     line->copyFrom(cols, cells);
453     return 1;
454 }
455 
onPopline(dimen_t cols,VTermScreenCell * cells)456 status_t Terminal::onPopline(dimen_t cols, VTermScreenCell* cells) {
457     if (mScrollCur == 0) {
458         return 0;
459     }
460 
461     ScrollbackLine* line = mScroll[0];
462     mScrollCur--;
463     memmove(mScroll, mScroll + 1, sizeof(ScrollbackLine*) * mScrollCur);
464 
465     dimen_t n = line->copyTo(cols, cells);
466     for (dimen_t col = n; col < cols; col++) {
467         cells[col].chars[0] = 0;
468         cells[col].width = 1;
469     }
470 
471     delete line;
472     return 1;
473 }
474 
getCellLocked(VTermPos pos,VTermScreenCell * cell)475 void Terminal::getCellLocked(VTermPos pos, VTermScreenCell* cell) {
476     // The UI may be asking for cell data while the model is changing
477     // underneath it, so we always fill with meaningful data.
478 
479     if (pos.row < 0) {
480         size_t scrollRow = -pos.row;
481         if (scrollRow > mScrollCur) {
482             // Invalid region above current scrollback
483             cell->width = 1;
484 #if DEBUG_SCROLLBACK
485             cell->bg.red = 255;
486 #endif
487             return;
488         }
489 
490         ScrollbackLine* line = mScroll[scrollRow - 1];
491         if ((size_t) pos.col < line->cols) {
492             // Valid scrollback cell
493             line->getCell(pos.col, cell);
494             cell->width = 1;
495 #if DEBUG_SCROLLBACK
496             cell->bg.blue = 255;
497 #endif
498             return;
499         } else {
500             // Extend last scrollback cell into invalid region
501             line->getCell(line->cols - 1, cell);
502             cell->width = 1;
503             cell->chars[0] = ' ';
504 #if DEBUG_SCROLLBACK
505             cell->bg.green = 255;
506 #endif
507             return;
508         }
509     }
510 
511     if ((size_t) pos.row >= mRows) {
512         // Invalid region below screen
513         cell->width = 1;
514 #if DEBUG_SCROLLBACK
515         cell->bg.red = 128;
516 #endif
517         return;
518     }
519 
520     // Valid screen cell
521     vterm_screen_get_cell(mVts, pos, cell);
522 }
523 
getRows() const524 dimen_t Terminal::getRows() const {
525     return mRows;
526 }
527 
getCols() const528 dimen_t Terminal::getCols() const {
529     return mCols;
530 }
531 
getScrollRows() const532 dimen_t Terminal::getScrollRows() const {
533     return mScrollSize;
534 }
535 
getCallbacks() const536 jobject Terminal::getCallbacks() const {
537     return mCallbacks;
538 }
539 
540 /*
541  * JNI glue
542  */
543 
com_android_terminal_Terminal_nativeInit(JNIEnv * env,jclass clazz,jobject callbacks)544 static jlong com_android_terminal_Terminal_nativeInit(JNIEnv* env, jclass clazz, jobject callbacks) {
545     return reinterpret_cast<jlong>(new Terminal(callbacks));
546 }
547 
com_android_terminal_Terminal_nativeDestroy(JNIEnv * env,jclass clazz,jlong ptr)548 static jint com_android_terminal_Terminal_nativeDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
549     Terminal* term = reinterpret_cast<Terminal*>(ptr);
550     delete term;
551     return 0;
552 }
553 
com_android_terminal_Terminal_nativeRun(JNIEnv * env,jclass clazz,jlong ptr)554 static jint com_android_terminal_Terminal_nativeRun(JNIEnv* env, jclass clazz, jlong ptr) {
555     Terminal* term = reinterpret_cast<Terminal*>(ptr);
556     return term->run();
557 }
558 
com_android_terminal_Terminal_nativeResize(JNIEnv * env,jclass clazz,jlong ptr,jint rows,jint cols,jint scrollRows)559 static jint com_android_terminal_Terminal_nativeResize(JNIEnv* env,
560         jclass clazz, jlong ptr, jint rows, jint cols, jint scrollRows) {
561     Terminal* term = reinterpret_cast<Terminal*>(ptr);
562     return term->resize(rows, cols, scrollRows);
563 }
564 
toArgb(const VTermColor & color)565 static inline int toArgb(const VTermColor& color) {
566     return (0xff << 24 | color.rgb.red << 16 | color.rgb.green << 8 | color.rgb.blue);
567 }
568 
isCellStyleEqual(const VTermScreenCell & a,const VTermScreenCell & b)569 static inline bool isCellStyleEqual(const VTermScreenCell& a, const VTermScreenCell& b) {
570     if (toArgb(a.fg) != toArgb(b.fg)) return false;
571     if (toArgb(a.bg) != toArgb(b.bg)) return false;
572 
573     if (a.attrs.bold != b.attrs.bold) return false;
574     if (a.attrs.underline != b.attrs.underline) return false;
575     if (a.attrs.italic != b.attrs.italic) return false;
576     if (a.attrs.blink != b.attrs.blink) return false;
577     if (a.attrs.reverse != b.attrs.reverse) return false;
578     if (a.attrs.strike != b.attrs.strike) return false;
579     if (a.attrs.font != b.attrs.font) return false;
580 
581     return true;
582 }
583 
com_android_terminal_Terminal_nativeGetCellRun(JNIEnv * env,jclass clazz,jlong ptr,jint row,jint col,jobject run)584 static jint com_android_terminal_Terminal_nativeGetCellRun(JNIEnv* env,
585         jclass clazz, jlong ptr, jint row, jint col, jobject run) {
586     Terminal* term = reinterpret_cast<Terminal*>(ptr);
587     Mutex::Autolock lock(term->mLock);
588 
589     jcharArray dataArray = (jcharArray) env->GetObjectField(run, cellRunDataField);
590     ScopedCharArrayRW data(env, dataArray);
591     if (data.get() == NULL) {
592         return -1;
593     }
594 
595     VTermScreenCell firstCell, cell;
596 
597     VTermPos pos = {
598         .row = row,
599         .col = col,
600     };
601 
602     size_t dataSize = 0;
603     size_t colSize = 0;
604     while ((size_t) pos.col < term->getCols()) {
605         memset(&cell, 0, sizeof(VTermScreenCell));
606         term->getCellLocked(pos, &cell);
607 
608         if (colSize == 0) {
609             env->SetIntField(run, cellRunFgField, toArgb(cell.fg));
610             env->SetIntField(run, cellRunBgField, toArgb(cell.bg));
611             memcpy(&firstCell, &cell, sizeof(VTermScreenCell));
612         } else {
613             if (!isCellStyleEqual(cell, firstCell)) {
614                 break;
615             }
616         }
617 
618         // Only include cell chars if they fit into run
619         uint32_t rawCell = cell.chars[0];
620         size_t size = (rawCell < 0x10000) ? 1 : 2;
621         if (dataSize + size <= data.size()) {
622             if (rawCell < 0x10000) {
623                 data[dataSize++] = rawCell;
624             } else {
625                 data[dataSize++] = (((rawCell - 0x10000) >> 10) & 0x3ff) + 0xd800;
626                 data[dataSize++] = ((rawCell - 0x10000) & 0x3ff) + 0xdc00;
627             }
628 
629             for (int i = 1; i < cell.width; i++) {
630                 data[dataSize++] = ' ';
631             }
632 
633             colSize += cell.width;
634             pos.col += cell.width;
635         } else {
636             break;
637         }
638     }
639 
640     env->SetIntField(run, cellRunDataSizeField, dataSize);
641     env->SetIntField(run, cellRunColSizeField, colSize);
642 
643     return 0;
644 }
645 
com_android_terminal_Terminal_nativeGetRows(JNIEnv * env,jclass clazz,jlong ptr)646 static jint com_android_terminal_Terminal_nativeGetRows(JNIEnv* env, jclass clazz, jlong ptr) {
647     Terminal* term = reinterpret_cast<Terminal*>(ptr);
648     return term->getRows();
649 }
650 
com_android_terminal_Terminal_nativeGetCols(JNIEnv * env,jclass clazz,jlong ptr)651 static jint com_android_terminal_Terminal_nativeGetCols(JNIEnv* env, jclass clazz, jlong ptr) {
652     Terminal* term = reinterpret_cast<Terminal*>(ptr);
653     return term->getCols();
654 }
655 
com_android_terminal_Terminal_nativeGetScrollRows(JNIEnv * env,jclass clazz,jlong ptr)656 static jint com_android_terminal_Terminal_nativeGetScrollRows(JNIEnv* env, jclass clazz, jlong ptr) {
657     Terminal* term = reinterpret_cast<Terminal*>(ptr);
658     return term->getScrollRows();
659 }
660 
com_android_terminal_Terminal_nativeDispatchCharacter(JNIEnv * env,jclass clazz,jlong ptr,jint mod,jint c)661 static jboolean com_android_terminal_Terminal_nativeDispatchCharacter(JNIEnv *env, jclass clazz,
662         jlong ptr, jint mod, jint c) {
663     Terminal* term = reinterpret_cast<Terminal*>(ptr);
664     return term->dispatchCharacter(mod, c);
665 }
666 
com_android_terminal_Terminal_nativeDispatchKey(JNIEnv * env,jclass clazz,jlong ptr,jint mod,jint c)667 static jboolean com_android_terminal_Terminal_nativeDispatchKey(JNIEnv *env, jclass clazz,
668         jlong ptr, jint mod, jint c) {
669     Terminal* term = reinterpret_cast<Terminal*>(ptr);
670     return term->dispatchKey(mod, c);
671 }
672 
673 static JNINativeMethod gMethods[] = {
674     { "nativeInit", "(Lcom/android/terminal/TerminalCallbacks;)J", (void*)com_android_terminal_Terminal_nativeInit },
675     { "nativeDestroy", "(J)I", (void*)com_android_terminal_Terminal_nativeDestroy },
676     { "nativeRun", "(J)I", (void*)com_android_terminal_Terminal_nativeRun },
677     { "nativeResize", "(JIII)I", (void*)com_android_terminal_Terminal_nativeResize },
678     { "nativeGetCellRun", "(JIILcom/android/terminal/Terminal$CellRun;)I", (void*)com_android_terminal_Terminal_nativeGetCellRun },
679     { "nativeGetRows", "(J)I", (void*)com_android_terminal_Terminal_nativeGetRows },
680     { "nativeGetCols", "(J)I", (void*)com_android_terminal_Terminal_nativeGetCols },
681     { "nativeGetScrollRows", "(J)I", (void*)com_android_terminal_Terminal_nativeGetScrollRows },
682     { "nativeDispatchCharacter", "(JII)Z", (void*)com_android_terminal_Terminal_nativeDispatchCharacter},
683     { "nativeDispatchKey", "(JII)Z", (void*)com_android_terminal_Terminal_nativeDispatchKey },
684 };
685 
register_com_android_terminal_Terminal(JNIEnv * env)686 int register_com_android_terminal_Terminal(JNIEnv* env) {
687     ScopedLocalRef<jclass> localClass(env,
688             env->FindClass("com/android/terminal/TerminalCallbacks"));
689 
690     android::terminalCallbacksClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
691 
692     android::damageMethod = env->GetMethodID(terminalCallbacksClass, "damage", "(IIII)I");
693     android::moveRectMethod = env->GetMethodID(terminalCallbacksClass, "moveRect", "(IIIIIIII)I");
694     android::moveCursorMethod = env->GetMethodID(terminalCallbacksClass, "moveCursor",
695             "(IIIII)I");
696     android::setTermPropBooleanMethod = env->GetMethodID(terminalCallbacksClass,
697             "setTermPropBoolean", "(IZ)I");
698     android::setTermPropIntMethod = env->GetMethodID(terminalCallbacksClass, "setTermPropInt",
699             "(II)I");
700     android::setTermPropStringMethod = env->GetMethodID(terminalCallbacksClass, "setTermPropString",
701             "(ILjava/lang/String;)I");
702     android::setTermPropColorMethod = env->GetMethodID(terminalCallbacksClass, "setTermPropColor",
703             "(IIII)I");
704     android::bellMethod = env->GetMethodID(terminalCallbacksClass, "bell", "()I");
705 
706     ScopedLocalRef<jclass> cellRunLocal(env,
707             env->FindClass("com/android/terminal/Terminal$CellRun"));
708     cellRunClass = reinterpret_cast<jclass>(env->NewGlobalRef(cellRunLocal.get()));
709     cellRunDataField = env->GetFieldID(cellRunClass, "data", "[C");
710     cellRunDataSizeField = env->GetFieldID(cellRunClass, "dataSize", "I");
711     cellRunColSizeField = env->GetFieldID(cellRunClass, "colSize", "I");
712     cellRunFgField = env->GetFieldID(cellRunClass, "fg", "I");
713     cellRunBgField = env->GetFieldID(cellRunClass, "bg", "I");
714 
715     return jniRegisterNativeMethods(env, "com/android/terminal/Terminal",
716             gMethods, NELEM(gMethods));
717 }
718 
719 } /* namespace android */
720