code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
package cx.hell.android.pdfview;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cx.hell.android.lib.pagesview.FindResult;
import cx.hell.android.lib.pagesview.PagesView;
/**
* Document display activity.
*/
public class OpenFileActivity extends Activity {
private final static String TAG = "cx.hell.android.pdfview";
private PDF pdf = null;
private PagesView pagesView = null;
private PDFPagesProvider pdfPagesProvider = null;
private MenuItem aboutMenuItem = null;
private MenuItem gotoPageMenuItem = null;
private MenuItem rotateLeftMenuItem = null;
private MenuItem rotateRightMenuItem = null;
private MenuItem findTextMenuItem = null;
private MenuItem clearFindTextMenuItem = null;
private EditText pageNumberInputField = null;
private EditText findTextInputField = null;
private LinearLayout findButtonsLayout = null;
private Button findPrevButton = null;
private Button findNextButton = null;
private Button findHideButton = null;
// currently opened file path
private String filePath = "/";
private String findText = null;
private Integer currentFindResultPage = null;
private Integer currentFindResultNumber = null;
// zoom buttons, layout and fade animation
private ImageButton zoomDownButton;
private ImageButton zoomUpButton;
private Animation zoomAnim;
private LinearLayout zoomLayout;
/**
* Called when the activity is first created.
* TODO: initialize dialog fast, then move file loading to other thread
* TODO: add progress bar for file load
* TODO: add progress icon for file rendering
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// use a relative layout to stack the views
RelativeLayout layout = new RelativeLayout(this);
// the PDF view
this.pagesView = new PagesView(this);
this.pdf = this.getPDF();
this.pdfPagesProvider = new PDFPagesProvider(pdf);
pagesView.setPagesProvider(pdfPagesProvider);
layout.addView(pagesView);
// the find buttons
this.findButtonsLayout = new LinearLayout(this);
this.findButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
this.findButtonsLayout.setVisibility(View.GONE);
this.findButtonsLayout.setGravity(Gravity.CENTER);
this.findPrevButton = new Button(this);
this.findPrevButton.setText("Prev");
this.findButtonsLayout.addView(this.findPrevButton);
this.findNextButton = new Button(this);
this.findNextButton.setText("Next");
this.findButtonsLayout.addView(this.findNextButton);
this.findHideButton = new Button(this);
this.findHideButton.setText("Hide");
this.findButtonsLayout.addView(this.findHideButton);
this.setFindButtonHandlers();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(this.findButtonsLayout, lp);
// the zoom buttons
zoomLayout = new LinearLayout(this);
zoomLayout.setOrientation(LinearLayout.HORIZONTAL);
zoomDownButton = new ImageButton(this);
zoomDownButton.setImageDrawable(getResources().getDrawable(R.drawable.btn_zoom_down));
zoomDownButton.setBackgroundColor(Color.TRANSPARENT);
zoomLayout.addView(zoomDownButton, 80, 50); // TODO: remove hardcoded values
zoomUpButton = new ImageButton(this);
zoomUpButton.setImageDrawable(getResources().getDrawable(R.drawable.btn_zoom_up));
zoomUpButton.setBackgroundColor(Color.TRANSPARENT);
zoomLayout.addView(zoomUpButton, 80, 50);
zoomAnim = AnimationUtils.loadAnimation(this, R.anim.zoom);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
setZoomButtonHandlers();
layout.addView(zoomLayout,lp);
// display this
this.setContentView(layout);
// go to last viewed page
gotoLastPage();
// send keyboard events to this view
pagesView.setFocusable(true);
pagesView.setFocusableInTouchMode(true);
}
/**
* Save the current page before exiting
*/
@Override
protected void onPause() {
saveLastPage();
super.onPause();
}
/**
* Set handlers on findNextButton and findHideButton.
*/
private void setFindButtonHandlers() {
this.findPrevButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findPrev();
}
});
this.findNextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findNext();
}
});
this.findHideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OpenFileActivity.this.findHide();
}
});
}
/**
* Set handlers on zoom level buttons
*/
private void setZoomButtonHandlers() {
this.zoomDownButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pagesView.zoomDown();
}
});
this.zoomUpButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pagesView.zoomUp();
}
});
}
/**
* Return PDF instance wrapping file referenced by Intent.
* Currently reads all bytes to memory, in future local files
* should be passed to native code and remote ones should
* be downloaded to local tmp dir.
* @return PDF instance
*/
private PDF getPDF() {
final Intent intent = getIntent();
Uri uri = intent.getData();
filePath = uri.getPath();
if (uri.getScheme().equals("file")) {
return new PDF(new File(filePath));
} else if (uri.getScheme().equals("content")) {
ContentResolver cr = this.getContentResolver();
FileDescriptor fileDescriptor;
try {
fileDescriptor = cr.openFileDescriptor(uri, "r").getFileDescriptor();
} catch (FileNotFoundException e) {
throw new RuntimeException(e); // TODO: handle errors
}
return new PDF(fileDescriptor);
} else {
throw new RuntimeException("don't know how to get filename from " + uri);
}
}
/**
* Handle menu.
* @param menuItem selected menu item
* @return true if menu item was handled
*/
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem == this.aboutMenuItem) {
Intent intent = new Intent();
intent.setClass(this, AboutPDFViewActivity.class);
this.startActivity(intent);
return true;
} else if (menuItem == this.gotoPageMenuItem) {
this.showGotoPageDialog();
} else if (menuItem == this.rotateLeftMenuItem) {
this.pagesView.rotate(-1);
} else if (menuItem == this.rotateRightMenuItem) {
this.pagesView.rotate(1);
} else if (menuItem == this.findTextMenuItem) {
this.showFindDialog();
} else if (menuItem == this.clearFindTextMenuItem) {
this.clearFind();
}
return false;
}
/**
* Intercept touch events to handle the zoom buttons animation
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
zoomAnim.setFillAfter(true);
zoomLayout.startAnimation(zoomAnim);
}
return super.dispatchTouchEvent(event);
};
/**
* Hide the find buttons
*/
private void clearFind() {
this.currentFindResultPage = null;
this.currentFindResultNumber = null;
this.pagesView.setFindMode(false);
this.findButtonsLayout.setVisibility(View.GONE);
}
/**
* Show error message to user.
* @param message message to show
*/
private void errorMessage(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.setMessage(message).setTitle("Error").create();
dialog.show();
}
/**
* Called from menu when user want to go to specific page.
*/
private void showGotoPageDialog() {
final Dialog d = new Dialog(this);
d.setTitle(R.string.goto_page_dialog_title);
LinearLayout contents = new LinearLayout(this);
contents.setOrientation(LinearLayout.VERTICAL);
TextView label = new TextView(this);
final int pagecount = this.pdfPagesProvider.getPageCount();
label.setText("Page number from " + 1 + " to " + pagecount);
this.pageNumberInputField = new EditText(this);
this.pageNumberInputField.setInputType(InputType.TYPE_CLASS_NUMBER);
this.pageNumberInputField.setText("" + (this.pagesView.getCurrentPage() + 1));
Button goButton = new Button(this);
goButton.setText(R.string.goto_page_go_button);
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int pageNumber = -1;
try {
pageNumber = Integer.parseInt(OpenFileActivity.this.pageNumberInputField.getText().toString())-1;
} catch (NumberFormatException e) {
/* ignore */
}
d.dismiss();
if (pageNumber >= 0 && pageNumber < pagecount) {
OpenFileActivity.this.gotoPage(pageNumber);
} else {
OpenFileActivity.this.errorMessage("Invalid page number");
}
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = 5;
params.rightMargin = 5;
params.bottomMargin = 2;
params.topMargin = 2;
contents.addView(label, params);
contents.addView(pageNumberInputField, params);
contents.addView(goButton, params);
d.setContentView(contents);
d.show();
}
/**
* Called after submitting go to page dialog.
* @param page page number, 0-based
*/
private void gotoPage(int page) {
Log.i(TAG, "rewind to page " + page);
if (this.pagesView != null) {
this.pagesView.scrollToPage(page);
}
}
/**
* Goto the last open page if possible
*/
private void gotoLastPage() {
Bookmark b = new Bookmark(this.getApplicationContext()).open();
int lastpage = b.getLast(filePath);
b.close();
if (lastpage > 0) {
Handler mHandler = new Handler();
Runnable mUpdateTimeTask = new GotoPageThread(lastpage);
mHandler.postDelayed(mUpdateTimeTask, 2000);
}
}
/**
* Save the last page in the bookmarks
*/
private void saveLastPage() {
Bookmark b = new Bookmark(this.getApplicationContext()).open();
b.setLast(filePath, pagesView.getCurrentPage());
b.close();
Log.i(TAG, "last page saved for "+filePath);
}
/**
* Create options menu, called by Android system.
* @param menu menu to populate
* @return true meaning that menu was populated
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.gotoPageMenuItem = menu.add(R.string.goto_page);
this.rotateRightMenuItem = menu.add(R.string.rotate_page_left);
this.rotateLeftMenuItem = menu.add(R.string.rotate_page_right);
this.findTextMenuItem = menu.add(R.string.find_text);
this.clearFindTextMenuItem = menu.add(R.string.clear_find_text);
this.aboutMenuItem = menu.add(R.string.about);
return true;
}
/**
* Thread to delay the gotoPage action when opening a PDF file
*/
private class GotoPageThread implements Runnable {
int page;
public GotoPageThread(int page) {
this.page = page;
}
public void run() {
gotoPage(page);
}
}
/**
* Prepare menu contents.
* Hide or show "Clear find results" menu item depending on whether
* we're in find mode.
* @param menu menu that should be prepared
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
this.clearFindTextMenuItem.setVisible(this.pagesView.getFindMode());
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i(TAG, "onConfigurationChanged(" + newConfig + ")");
}
/**
* Show find dialog.
* Very pretty UI code ;)
*/
private void showFindDialog() {
Log.d(TAG, "find dialog...");
final Dialog dialog = new Dialog(this);
dialog.setTitle(R.string.find_dialog_title);
LinearLayout contents = new LinearLayout(this);
contents.setOrientation(LinearLayout.VERTICAL);
this.findTextInputField = new EditText(this);
this.findTextInputField.setWidth(this.pagesView.getWidth() * 80 / 100);
Button goButton = new Button(this);
goButton.setText(R.string.find_go_button);
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String text = OpenFileActivity.this.findTextInputField.getText().toString();
OpenFileActivity.this.findText(text);
dialog.dismiss();
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin = 5;
params.rightMargin = 5;
params.bottomMargin = 2;
params.topMargin = 2;
contents.addView(findTextInputField, params);
contents.addView(goButton, params);
dialog.setContentView(contents);
dialog.show();
}
private void findText(String text) {
Log.d(TAG, "findText(" + text + ")");
this.findText = text;
this.find(true);
}
/**
* Called when user presses "next" button in find panel.
*/
private void findNext() {
this.find(true);
}
/**
* Called when user presses "prev" button in find panel.
*/
private void findPrev() {
this.find(false);
}
/**
* Called when user presses hide button in find panel.
*/
private void findHide() {
if (this.pagesView != null) this.pagesView.setFindMode(false);
this.currentFindResultNumber = null;
this.currentFindResultPage = null;
this.findButtonsLayout.setVisibility(View.GONE);
}
/**
* Helper class that handles search progress, search cancelling etc.
*/
static class Finder implements Runnable, DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
private OpenFileActivity parent = null;
private boolean forward;
private AlertDialog dialog = null;
private String text;
private int startingPage;
private int pageCount;
private boolean cancelled = false;
/**
* Constructor for finder.
* @param parent parent activity
*/
public Finder(OpenFileActivity parent, boolean forward) {
this.parent = parent;
this.forward = forward;
this.text = parent.findText;
this.pageCount = parent.pagesView.getPageCount();
if (parent.currentFindResultPage != null) {
if (forward) {
this.startingPage = (parent.currentFindResultPage + 1) % pageCount;
} else {
this.startingPage = (parent.currentFindResultPage - 1 + pageCount) % pageCount;
}
} else {
this.startingPage = parent.pagesView.getCurrentPage();
}
}
public void setDialog(AlertDialog dialog) {
this.dialog = dialog;
}
public void run() {
int page = -1;
this.createDialog();
this.showDialog();
for(int i = 0; i < this.pageCount; ++i) {
if (this.cancelled) {
this.dismissDialog();
return;
}
page = (startingPage + pageCount + (this.forward ? i : -i)) % this.pageCount;
Log.d(TAG, "searching on " + page);
this.updateDialog(page);
List<FindResult> findResults = this.findOnPage(page);
if (findResults != null && !findResults.isEmpty()) {
Log.d(TAG, "found something at page " + page + ": " + findResults.size() + " results");
this.dismissDialog();
this.showFindResults(findResults, page);
return;
}
}
/* TODO: show "nothing found" message */
this.dismissDialog();
}
/**
* Called by finder thread to get find results for given page.
* Routed to PDF instance.
* If result is not empty, then finder loop breaks, current find position
* is saved and find results are displayed.
* @param page page to search on
* @return results
*/
private List<FindResult> findOnPage(int page) {
if (this.text == null) throw new IllegalStateException("text cannot be null");
return this.parent.pdf.find(this.text, page);
}
private void createDialog() {
this.parent.runOnUiThread(new Runnable() {
public void run() {
String title = Finder.this.parent.getString(R.string.searching_for).replace("%1", Finder.this.text);
String message = Finder.this.parent.getString(R.string.page_of).replace("%1", String.valueOf(Finder.this.startingPage)).replace("%2", String.valueOf(pageCount));
AlertDialog.Builder builder = new AlertDialog.Builder(Finder.this.parent);
AlertDialog dialog = builder
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.setNegativeButton(R.string.cancel, Finder.this)
.create();
dialog.setOnCancelListener(Finder.this);
Finder.this.dialog = dialog;
}
});
}
public void updateDialog(final int page) {
this.parent.runOnUiThread(new Runnable() {
public void run() {
String message = Finder.this.parent.getString(R.string.page_of).replace("%1", String.valueOf(page)).replace("%2", String.valueOf(pageCount));
Finder.this.dialog.setMessage(message);
}
});
}
public void showDialog() {
this.parent.runOnUiThread(new Runnable() {
public void run() {
Finder.this.dialog.show();
}
});
}
public void dismissDialog() {
final AlertDialog dialog = this.dialog;
this.parent.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "onCancel(" + dialog + ")");
this.cancelled = true;
}
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "onClick(" + dialog + ")");
this.cancelled = true;
}
private void showFindResults(final List<FindResult> findResults, final int page) {
this.parent.runOnUiThread(new Runnable() {
public void run() {
int fn = Finder.this.forward ? 0 : findResults.size()-1;
Finder.this.parent.currentFindResultPage = page;
Finder.this.parent.currentFindResultNumber = fn;
Finder.this.parent.pagesView.setFindResults(findResults);
Finder.this.parent.pagesView.setFindMode(true);
Finder.this.parent.pagesView.scrollToFindResult(fn);
Finder.this.parent.findButtonsLayout.setVisibility(View.VISIBLE);
Finder.this.parent.pagesView.invalidate();
}
});
}
};
/**
* GUI for finding text.
* Used both on initial search and for "next" and "prev" searches.
* Displays dialog, handles cancel button, hides dialog as soon as
* something is found.
* @param
*/
private void find(boolean forward) {
if (this.currentFindResultPage != null) {
/* searching again */
int nextResultNum = forward ? this.currentFindResultNumber + 1 : this.currentFindResultNumber - 1;
if (nextResultNum >= 0 && nextResultNum < this.pagesView.getFindResults().size()) {
/* no need to really find - just focus on given result and exit */
this.currentFindResultNumber = nextResultNum;
this.pagesView.scrollToFindResult(nextResultNum);
this.pagesView.invalidate();
return;
}
}
/* finder handles next/prev and initial search by itself */
Finder finder = new Finder(this, forward);
Thread finderThread = new Thread(finder);
finderThread.start();
}
}
|
Java
|
package cx.hell.android.pdfview;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.graphics.Bitmap;
import android.util.Log;
import cx.hell.android.lib.pagesview.OnImageRenderedListener;
import cx.hell.android.lib.pagesview.PagesProvider;
import cx.hell.android.lib.pagesview.PagesView;
import cx.hell.android.lib.pagesview.RenderingException;
import cx.hell.android.lib.pagesview.Tile;
/**
* Provide rendered bitmaps of pages.
*/
public class PDFPagesProvider extends PagesProvider {
/**
* Const used by logging.
*/
private final static String TAG = "cx.hell.android.pdfview";
/**
* Smart page-bitmap cache.
* Stores up to approx MAX_CACHE_SIZE_BYTES of images.
* Dynamically drops oldest unused bitmaps.
* TODO: Return high resolution bitmaps if no exact res is available.
* Bitmap images are tiled - tile size is specified in PagesView.TILE_SIZE.
*/
private static class BitmapCache {
/**
* Max size of bitmap cache in bytes.
*/
private static final int MAX_CACHE_SIZE_BYTES = 4*1024*1024;
/**
* Cache value - tuple with data and properties.
*/
private static class BitmapCacheValue {
public Bitmap bitmap;
/* public long millisAdded; */
public long millisAccessed;
public BitmapCacheValue(Bitmap bitmap, long millisAdded) {
this.bitmap = bitmap;
/* this.millisAdded = millisAdded; */
this.millisAccessed = millisAdded;
}
}
/**
* Stores cached bitmaps.
*/
private Map<Tile, BitmapCacheValue> bitmaps;
/**
* Stats logging - number of cache hits.
*/
private long hits;
/**
* Stats logging - number of misses.
*/
private long misses;
BitmapCache() {
this.bitmaps = new HashMap<Tile, BitmapCacheValue>();
this.hits = 0;
this.misses = 0;
}
/**
* Get cached bitmap. Updates last access timestamp.
* @param k cache key
* @return bitmap found in cache or null if there's no matching bitmap
*/
Bitmap get(Tile k) {
BitmapCacheValue v = this.bitmaps.get(k);
Bitmap b = null;
if (v != null) {
// yeah
b = v.bitmap;
assert b != null;
v.millisAccessed = System.currentTimeMillis();
this.hits += 1;
} else {
// le fu
this.misses += 1;
}
if ((this.hits + this.misses) % 100 == 0 && (this.hits > 0 || this.misses > 0)) {
Log.d("cx.hell.android.pdfview.pagecache", "hits: " + hits + ", misses: " + misses + ", hit ratio: " + (float)(hits) / (float)(hits+misses) +
", size: " + this.bitmaps.size());
}
return b;
}
/**
* Put rendered tile in cache.
* @param tile tile definition (page, position etc), cache key
* @param bitmap rendered tile contents, cache value
*/
synchronized void put(Tile tile, Bitmap bitmap) {
while (this.willExceedCacheSize(bitmap) && !this.bitmaps.isEmpty()) {
this.removeOldest();
}
this.bitmaps.put(tile, new BitmapCacheValue(bitmap, System.currentTimeMillis()));
}
/**
* Check if cache contains specified bitmap tile. Doesn't update last-used timestamp.
* @return true if cache contains specified bitmap tile
*/
synchronized boolean contains(Tile tile) {
return this.bitmaps.containsKey(tile);
}
/**
* Estimate bitmap memory size.
* This is just a guess.
*/
private static int getBitmapSizeInCache(Bitmap bitmap) {
assert bitmap.getConfig() == Bitmap.Config.RGB_565;
return bitmap.getWidth() * bitmap.getHeight() * 2;
}
/**
* Get estimated sum of byte sizes of bitmaps stored in cache currently.
*/
private synchronized int getCurrentCacheSize() {
int size = 0;
Iterator<BitmapCacheValue> it = this.bitmaps.values().iterator();
while(it.hasNext()) {
BitmapCacheValue bcv = it.next();
Bitmap bitmap = bcv.bitmap;
size += getBitmapSizeInCache(bitmap);
}
return size;
}
/**
* Determine if adding this bitmap would grow cache size beyond max size.
*/
private synchronized boolean willExceedCacheSize(Bitmap bitmap) {
return (this.getCurrentCacheSize() + BitmapCache.getBitmapSizeInCache(bitmap) > MAX_CACHE_SIZE_BYTES);
}
/**
* Remove oldest bitmap cache value.
*/
private void removeOldest() {
Iterator<Tile> i = this.bitmaps.keySet().iterator();
long minmillis = 0;
Tile oldest = null;
while(i.hasNext()) {
Tile k = i.next();
BitmapCacheValue v = this.bitmaps.get(k);
if (oldest == null) {
oldest = k;
minmillis = v.millisAccessed;
} else {
if (minmillis > v.millisAccessed) {
minmillis = v.millisAccessed;
oldest = k;
}
}
}
if (oldest == null) throw new RuntimeException("couldnt find oldest");
BitmapCacheValue v = this.bitmaps.get(oldest);
v.bitmap.recycle();
this.bitmaps.remove(oldest);
}
}
private static class RendererWorker implements Runnable {
/**
* Worker stops rendering if error was encountered.
*/
private boolean isFailed = false;
private PDFPagesProvider pdfPagesProvider;
private Collection<Tile> tiles;
/**
* Internal worker number for debugging.
*/
private static int workerThreadId = 0;
/**
* Used as a synchronized flag.
* If null, then there's no designated thread to render tiles.
* There might be other worker threads running, but those have finished
* their work and will finish really soon.
* Only this one should pick up new jobs.
*/
private Thread workerThread = null;
/**
* Create renderer worker.
* @param pdfPagesProvider parent pages provider
*/
RendererWorker(PDFPagesProvider pdfPagesProvider) {
this.tiles = null;
this.pdfPagesProvider = pdfPagesProvider;
}
/**
* Called by outside world to provide more work for worker.
* This also starts rendering thread if one is needed.
* @param tiles a collection of tile objects, they carry information about what should be rendered next
*/
synchronized void setTiles(Collection<Tile> tiles) {
this.tiles = tiles;
if (this.workerThread == null) {
Thread t = new Thread(this);
t.setPriority(Thread.MIN_PRIORITY);
t.setName("RendererWorkerThread#" + RendererWorker.workerThreadId++);
this.workerThread = t;
t.start();
Log.d(TAG, "started new worker thread");
} else {
//Log.i(TAG, "setTiles notices tiles is not empty, that means RendererWorkerThread exists and there's no need to start new one");
}
}
/**
* Get tiles that should be rendered next. May not block.
* Also sets this.workerThread to null if there's no tiles to be rendered currently,
* so that calling thread may finish.
* If there are more tiles to be rendered, then this.workerThread is not reset.
* @return some tiles
*/
synchronized Collection<Tile> popTiles() {
if (this.tiles == null || this.tiles.isEmpty()) {
this.workerThread = null; /* returning null, so calling thread will finish it's work */
return null;
}
Tile tile = this.tiles.iterator().next();
this.tiles.remove(tile);
return Collections.singleton(tile);
}
/**
* Thread's main routine.
* There might be more than one running, but only one will get new tiles. Others
* will get null returned by this.popTiles and will finish their work.
*/
public void run() {
while(true) {
if (this.isFailed) {
Log.i(TAG, "RendererWorker is failed, exiting");
break;
}
Collection<Tile> tiles = this.popTiles(); /* this can't block */
if (tiles == null || tiles.size() == 0) break;
try {
Map<Tile,Bitmap> renderedTiles = this.pdfPagesProvider.renderTiles(tiles);
this.pdfPagesProvider.publishBitmaps(renderedTiles);
} catch (RenderingException e) {
this.isFailed = true;
this.pdfPagesProvider.publishRenderingException(e);
}
}
}
}
private PDF pdf = null;
private BitmapCache bitmapCache = null;
private RendererWorker rendererWorker = null;
private OnImageRenderedListener onImageRendererListener = null;
public PDFPagesProvider(PDF pdf) {
this.pdf = pdf;
this.bitmapCache = new BitmapCache();
this.rendererWorker = new RendererWorker(this);
}
/**
* Render tiles.
* Called by worker, calls PDF's methods that in turn call native code.
* @param tiles job description - what to render
* @return mapping of jobs and job results, with job results being Bitmap objects
*/
private Map<Tile,Bitmap> renderTiles(Collection<Tile> tiles) throws RenderingException {
Map<Tile,Bitmap> renderedTiles = new HashMap<Tile,Bitmap>();
Iterator<Tile> i = tiles.iterator();
Tile tile = null;
while(i.hasNext()) {
tile = i.next();
renderedTiles.put(tile, this.renderBitmap(tile));
}
return renderedTiles;
}
/**
* Really render bitmap. Takes time, should be done in background thread. Calls native code (through PDF object).
*/
private Bitmap renderBitmap(Tile tile) throws RenderingException {
Bitmap b;
PDF.Size size = new PDF.Size(PagesView.TILE_SIZE, PagesView.TILE_SIZE);
int[] pagebytes = null;
pagebytes = pdf.renderPage(tile.getPage(), tile.getZoom(), tile.getX(), tile.getY(), tile.getRotation(), size); /* native */
if (pagebytes == null) throw new RenderingException("Couldn't render page " + tile.getPage());
b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.ARGB_8888);
/* simple tests show that this indeed works - memory usage is smaller with this extra copy */
/* TODO: make mupdf write directly to RGB_565 bitmap */
Bitmap btmp = b.copy(Bitmap.Config.RGB_565, true);
if (btmp == null) throw new RuntimeException("bitmap copy failed");
b.recycle();
b = btmp;
this.bitmapCache.put(tile, b);
return b;
}
/**
* Called by worker.
*/
private void publishBitmaps(Map<Tile,Bitmap> renderedTiles) {
if (this.onImageRendererListener != null) {
this.onImageRendererListener.onImagesRendered(renderedTiles);
} else {
Log.w(TAG, "we've got new bitmaps, but there's no one to notify about it!");
}
}
/**
* Called by worker.
*/
private void publishRenderingException(RenderingException e) {
if (this.onImageRendererListener != null) {
this.onImageRendererListener.onRenderingException(e);
}
}
@Override
public void setOnImageRenderedListener(OnImageRenderedListener l) {
this.onImageRendererListener = l;
}
/**
* Get tile bitmap if it's already rendered.
* @param tile which bitmap
* @return rendered tile; tile represents rect of TILE_SIZE x TILE_SIZE pixels,
* but might be of different size (should be scaled when painting)
*/
@Override
public Bitmap getPageBitmap(Tile tile) {
Bitmap b = null;
b = this.bitmapCache.get(tile);
if (b != null) return b;
return null;
}
/**
* Get page count.
* @return number of pages
*/
@Override
public int getPageCount() {
int c = this.pdf.getPageCount();
if (c <= 0) throw new RuntimeException("failed to load pdf file: getPageCount returned " + c);
return c;
}
/**
* Get page sizes from pdf file.
* @return array of page sizes
*/
@Override
public int[][] getPageSizes() {
int cnt = this.getPageCount();
int[][] sizes = new int[cnt][];
PDF.Size size = new PDF.Size();
int err;
for(int i = 0; i < cnt; ++i) {
err = this.pdf.getPageSize(i, size);
if (err != 0) {
throw new RuntimeException("failed to getPageSize(" + i + ",...), error: " + err);
}
sizes[i] = new int[2];
sizes[i][0] = size.width;
sizes[i][1] = size.height;
}
return sizes;
}
/**
* View informs provider what's currently visible.
* Compute what should be rendered and pass that info to renderer worker thread, possibly waking up worker.
* @param tiles specs of whats currently visible
*/
synchronized public void setVisibleTiles(Collection<Tile> tiles) {
List<Tile> newtiles = null;
for(Tile tile: tiles) {
if (!this.bitmapCache.contains(tile)) {
if (newtiles == null) newtiles = new LinkedList<Tile>();
newtiles.add(tile);
}
}
if (newtiles != null) {
this.rendererWorker.setTiles(newtiles);
}
}
}
|
Java
|
package cx.hell.android.lib.pagesview;
/**
* Tile definition.
* Can be used as a key in maps (hashable, comparable).
*/
public class Tile {
/**
* X position of tile in pixels.
*/
private int x;
/**
* Y position of tile in pixels.
*/
private int y;
private int zoom;
private int page;
private int rotation;
int _hashCode;
public Tile(int page, int zoom, int x, int y, int rotation) {
this.page = page;
this.zoom = zoom;
this.x = x;
this.y = y;
this.rotation = rotation;
}
public String toString() {
return "Tile(" +
this.page + ", " +
this.zoom + ", " +
this.x + ", " +
this.y + ", " +
this.rotation + ")";
}
public int hashCode() {
return this._hashCode;
}
public boolean equals(Object o) {
if (! (o instanceof Tile)) return false;
Tile t = (Tile) o;
return (
this._hashCode == t._hashCode
&& this.page == t.page
&& this.zoom == t.zoom
&& this.x == t.x
&& this.y == t.y
&& this.rotation == t.rotation
);
}
public int getPage() {
return this.page;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZoom() {
return this.zoom;
}
public int getRotation() {
return this.rotation;
}
}
|
Java
|
package cx.hell.android.lib.pagesview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.graphics.Rect;
import android.util.Log;
/**
* Find result.
*/
public class FindResult {
/**
* Logging tag.
*/
public static final String TAG = "cx.hell.android.pdfview";
/**
* Page number.
*/
public int page;
/**
* List of rects that mark find result occurences.
* In page dimensions (not scalled).
*/
public List<Rect> markers;
/**
* Add marker.
*/
public void addMarker(int x0, int y0, int x1, int y1) {
if (x0 >= x1) throw new IllegalArgumentException("x0 must be smaller than x1: " + x0 + ", " + x1);
if (y0 >= y1) throw new IllegalArgumentException("y0 must be smaller than y1: " + y0 + ", " + y1);
if (this.markers == null)
this.markers = new ArrayList<Rect>();
Rect nr = new Rect(x0, y0, x1, y1);
if (this.markers.isEmpty()) {
this.markers.add(nr);
} else {
this.markers.get(0).union(nr);
}
}
public String toString() {
StringBuilder b = new StringBuilder();
b.append("FindResult(");
if (this.markers == null || this.markers.isEmpty()) {
b.append("no markers");
} else {
Iterator<Rect> i = this.markers.iterator();
Rect r = null;
while(i.hasNext()) {
r = i.next();
b.append(r);
if (i.hasNext()) b.append(", ");
}
}
b.append(")");
return b.toString();
}
public void finalize() {
Log.i(TAG, this + ".finalize()");
}
}
|
Java
|
package cx.hell.android.lib.pagesview;
public class RenderingException extends Exception {
private static final long serialVersionUID = 1010978161527539002L;
public RenderingException(String message) {
super(message);
}
}
|
Java
|
package cx.hell.android.lib.pagesview;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
/**
* View that simplifies displaying of paged documents.
* TODO: redesign zooms, pages, margins, layout
* TODO: use more floats for better align, or use more ints for performance ;) (that is, really analyse what should be used when)
*/
public class PagesView extends View implements View.OnTouchListener, OnImageRenderedListener, View.OnKeyListener {
/**
* Tile size.
*/
public static final int TILE_SIZE = 256;
/**
* Logging tag.
*/
private static final String TAG = "cx.hell.android.pdfview";
// private final static int MAX_ZOOM = 4000;
// private final static int MIN_ZOOM = 100;
/**
* Space between screen edge and page and between pages.
*/
private final static int MARGIN = 10;
private Activity activity = null;
/**
* Source of page bitmaps.
*/
private PagesProvider pagesProvider = null;
private long lastControlsUseMillis = 0;
/**
* Current width of this view.
*/
private int width = 0;
/**
* Current height of this view.
*/
private int height = 0;
/**
* Flag: are we being moved around by dragging.
*/
private boolean inDrag = false;
/**
* Drag start pos.
*/
private int dragx = 0;
/**
* Drag start pos.
*/
private int dragy = 0;
/**
* Drag pos.
*/
private int dragx1 = 0;
/**
* Drag pos.
*/
private int dragy1 = 0;
/**
* Position over book, not counting drag.
* This is position of viewports center, not top-left corner.
*/
private int left = 0;
/**
* Position over book, not counting drag.
* This is position of viewports center, not top-left corner.
*/
private int top = 0;
/**
* Current zoom level.
* 1000 is 100%.
*/
private int zoomLevel = 1000;
/**
* Current rotation of pages.
*/
private int rotation = 0;
/**
* Base scalling factor - how much shrink (or grow) page to fit it nicely to screen at zoomLevel = 1000.
* For example, if we determine that 200x400 image fits screen best, but PDF's pages are 400x800, then
* base scaling would be 0.5, since at base scalling, without any zoom, page should fit into screen nicely.
*/
private float scalling0 = 0f;
/**
* Page sized obtained from pages provider.
* These do not change.
*/
private int pageSizes[][];
/**
* Find mode.
*/
private boolean findMode = false;
/**
* Paint used to draw find results.
*/
private Paint findResultsPaint = null;
/**
* Currently displayed find results.
*/
private List<FindResult> findResults = null;
/**
* hold the currently displayed page
*/
private int currentPage = 0;
/**
* avoid too much allocations in rectsintersect()
*/
private static Rect r1 = new Rect();
/**
* Construct this view.
* @param activity parent activity
*/
public PagesView(Activity activity) {
super(activity);
this.activity = activity;
this.lastControlsUseMillis = System.currentTimeMillis();
this.findResultsPaint = new Paint();
this.findResultsPaint.setARGB(0xd0, 0xc0, 0, 0);
this.findResultsPaint.setStyle(Paint.Style.FILL);
this.findResultsPaint.setAntiAlias(true);
this.findResultsPaint.setStrokeWidth(3);
this.setOnTouchListener(this);
this.setOnKeyListener(this);
}
/**
* Handle size change event.
* Update base scaling, move zoom controls to correct place etc.
* @param w new width
* @param h new height
* @param oldw old width
* @param oldh old height
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.width = w;
this.height = h;
if (this.scalling0 == 0f) {
this.scalling0 = Math.min(
((float)this.height - 2*MARGIN) / (float)this.pageSizes[0][1],
((float)this.width - 2*MARGIN) / (float)this.pageSizes[0][0]);
}
if (oldw == 0 && oldh == 0) {
this.left = this.width / 2;
this.top = this.height / 2;
}
}
public void setPagesProvider(PagesProvider pagesProvider) {
this.pagesProvider = pagesProvider;
if (this.pagesProvider != null) {
this.pageSizes = this.pagesProvider.getPageSizes();
if (this.width > 0 && this.height > 0) {
this.scalling0 = Math.min(
((float)this.height - 2*MARGIN) / (float)this.pageSizes[0][1],
((float)this.width - 2*MARGIN) / (float)this.pageSizes[0][0]);
this.left = this.width / 2;
this.top = this.height / 2;
}
} else {
this.pageSizes = null;
}
this.pagesProvider.setOnImageRenderedListener(this);
}
/**
* Draw view.
* @param canvas what to draw on
*/
@Override
public void onDraw(Canvas canvas) {
this.drawPages(canvas);
if (this.findMode) this.drawFindResults(canvas);
}
/**
* Get current page width by page number taking into account zoom and rotation
* @param pageno 0-based page number
*/
private int getCurrentPageWidth(int pageno) {
float realpagewidth = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 0 : 1];
float currentpagewidth = realpagewidth * scalling0 * (this.zoomLevel*0.001f);
return (int)currentpagewidth;
}
/**
* Get current page height by page number taking into account zoom and rotation.
* @param pageno 0-based page number
*/
private float getCurrentPageHeight(int pageno) {
float realpageheight = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 1 : 0];
float currentpageheight = realpageheight * scalling0 * (this.zoomLevel*0.001f);
return currentpageheight;
}
private float getCurrentMargin() {
return (float)MARGIN * this.zoomLevel * 0.001f;
}
/**
* This takes into account zoom level.
*/
private Point getPagePositionInDocumentWithZoom(int page) {
float margin = this.getCurrentMargin();
float left = margin;
float top = 0;
for(int i = 0; i < page; ++i) {
top += this.getCurrentPageHeight(i);
}
top += (page+1) * margin;
return new Point((int)left, (int)top);
}
/**
* Calculate screens (viewports) top-left corner position over document.
*/
private Point getScreenPositionOverDocument() {
float top = this.top - this.height / 2;
float left = this.left - this.width / 2;
if (this.inDrag) {
left -= (this.dragx1 - this.dragx);
top -= (this.dragy1 - this.dragy);
}
return new Point((int)left, (int)top);
}
/**
* Calculate current page position on screen in pixels.
* @param page base-0 page number
*/
private Point getPagePositionOnScreen(int page) {
if (page < 0) throw new IllegalArgumentException("page must be >= 0: " + page);
if (page >= this.pageSizes.length) throw new IllegalArgumentException("page number too big: " + page);
Point pagePositionInDocument = this.getPagePositionInDocumentWithZoom(page);
Point screenPositionInDocument = this.getScreenPositionOverDocument();
return new Point(
pagePositionInDocument.x - screenPositionInDocument.x,
pagePositionInDocument.y - screenPositionInDocument.y
);
}
/**
* Draw pages.
* Also collect info what's visible and push this info to page renderer.
*/
private void drawPages(Canvas canvas) {
Rect src = new Rect(); /* TODO: move out of drawPages */
Rect dst = new Rect(); /* TODO: move out of drawPages */
int pageWidth = 0;
int pageHeight = 0;
float pagex0, pagey0, pagex1, pagey1; // in doc, counts zoom
float x, y; // on screen
int dragoffx, dragoffy;
int viewx0, viewy0; // view over doc
LinkedList<Tile> visibleTiles = new LinkedList<Tile>();
float currentMargin = this.getCurrentMargin();
if (this.pagesProvider != null) {
dragoffx = (inDrag) ? (dragx1 - dragx) : 0;
dragoffy = (inDrag) ? (dragy1 - dragy) : 0;
viewx0 = left - dragoffx - width/2;
viewy0 = top - dragoffy - height/2;
int pageCount = this.pageSizes.length;
float currpageoff = currentMargin;
this.currentPage = -1;
for(int i = 0; i < pageCount; ++i) {
// is page i visible?
pageWidth = this.getCurrentPageWidth(i);
pageHeight = (int) this.getCurrentPageHeight(i);
pagex0 = currentMargin;
pagex1 = (int)(currentMargin + pageWidth);
pagey0 = currpageoff;
pagey1 = (int)(currpageoff + pageHeight);
if (rectsintersect(
(int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc
viewx0, viewy0, viewx0 + this.width, viewy0 + this.height // viewport rect in doc
))
{
if (this.currentPage == -1) {
// remember the currently displayed page
this.currentPage = i;
}
x = pagex0 - viewx0;
y = pagey0 - viewy0;
for(int tileix = 0; tileix < pageWidth / TILE_SIZE + 1; ++tileix)
for(int tileiy = 0; tileiy < pageHeight / TILE_SIZE + 1; ++tileiy) {
dst.left = (int)(x + tileix*TILE_SIZE);
dst.top = (int)(y + tileiy*TILE_SIZE);
dst.right = dst.left + TILE_SIZE;
dst.bottom = dst.top + TILE_SIZE;
if (dst.intersects(0, 0, this.width, this.height)) {
/* tile is visible */
Tile tile = new Tile(i, (int)(this.zoomLevel * scalling0), tileix*TILE_SIZE, tileiy*TILE_SIZE, this.rotation);
Bitmap b = this.pagesProvider.getPageBitmap(tile);
if (b != null) {
//Log.d(TAG, " have bitmap: " + b + ", size: " + b.getWidth() + " x " + b.getHeight());
src.left = 0;
src.top = 0;
src.right = b.getWidth();
src.bottom = b.getWidth();
if (dst.right > x + pageWidth) {
src.right = (int)(b.getWidth() * (float)((x+pageWidth)-dst.left) / (float)(dst.right - dst.left));
dst.right = (int)(x + pageWidth);
}
if (dst.bottom > y + pageHeight) {
src.bottom = (int)(b.getHeight() * (float)((y+pageHeight)-dst.top) / (float)(dst.bottom - dst.top));
dst.bottom = (int)(y + pageHeight);
}
//this.fixOfscreen(dst, src);
canvas.drawBitmap(b, src, dst, null);
}
visibleTiles.add(tile);
}
}
}
/* move to next page */
currpageoff += currentMargin + this.getCurrentPageHeight(i);
}
this.pagesProvider.setVisibleTiles(visibleTiles);
}
}
/**
* Draw find results.
* TODO prettier icons
* TODO message if nothing was found
* @param canvas drawing target
*/
private void drawFindResults(Canvas canvas) {
if (!this.findMode) throw new RuntimeException("drawFindResults but not in find results mode");
if (this.findResults == null || this.findResults.isEmpty()) {
Log.w(TAG, "nothing found");
return;
}
for(FindResult findResult: this.findResults) {
if (findResult.markers == null || findResult.markers.isEmpty())
throw new RuntimeException("illegal FindResult: find result must have at least one marker");
Iterator<Rect> i = findResult.markers.iterator();
Rect r = null;
Point pagePosition = this.getPagePositionOnScreen(findResult.page);
float pagex = pagePosition.x;
float pagey = pagePosition.y;
float z = (this.scalling0 * (float)this.zoomLevel * 0.001f);
while(i.hasNext()) {
r = i.next();
canvas.drawLine(
r.left * z + pagex, r.top * z + pagey,
r.left * z + pagex, r.bottom * z + pagey,
this.findResultsPaint);
canvas.drawLine(
r.left * z + pagex, r.bottom * z + pagey,
r.right * z + pagex, r.bottom * z + pagey,
this.findResultsPaint);
canvas.drawLine(
r.right * z + pagex, r.bottom * z + pagey,
r.right * z + pagex, r.top * z + pagey,
this.findResultsPaint);
// canvas.drawRect(
// r.left * z + pagex,
// r.top * z + pagey,
// r.right * z + pagex,
// r.bottom * z + pagey,
// this.findResultsPaint);
// Log.d(TAG, "marker lands on: " +
// (r.left * z + pagex) + ", " +
// (r.top * z + pagey) + ", " +
// (r.right * z + pagex) + ", " +
// (r.bottom * z + pagey) + ", ");
}
}
}
/**
* Handle touch event coming from Android system.
*/
public boolean onTouch(View v, MotionEvent event) {
this.lastControlsUseMillis = System.currentTimeMillis();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(TAG, "onTouch(ACTION_DOWN)");
int x = (int)event.getX();
int y = (int)event.getY();
this.dragx = this.dragx1 = x;
this.dragy = this.dragy1 = y;
this.inDrag = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (this.inDrag) {
this.inDrag = false;
this.left -= (this.dragx1 - this.dragx);
this.top -= (this.dragy1 - this.dragy);
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (this.inDrag) {
this.dragx1 = (int) event.getX();
this.dragy1 = (int) event.getY();
this.invalidate();
}
}
return true;
}
/**
* Handle keyboard events
*/
public boolean onKey(View v, int keyCode, KeyEvent event) {
float step = 1.1f;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_K:
this.top -= this.getHeight() - 16;
this.invalidate();
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_SPACE:
case KeyEvent.KEYCODE_J:
this.top += this.getHeight() - 16;
this.invalidate();
return true;
case KeyEvent.KEYCODE_H:
this.left -= this.getWidth() / 4;
this.invalidate();
return true;
case KeyEvent.KEYCODE_L:
this.left += this.getWidth() / 4;
this.invalidate();
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
scrollToPage(currentPage - 1);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
scrollToPage(currentPage + 1);
return true;
case KeyEvent.KEYCODE_O:
this.zoomLevel /= step;
this.left /= step;
this.top /= step;
this.invalidate();
return true;
case KeyEvent.KEYCODE_P:
this.zoomLevel *= step;
this.left *= step;
this.top *= step;
this.invalidate();
return true;
}
}
return false;
}
/**
* Test if specified rectangles intersect with each other.
* Uses Androids standard Rect class.
*/
private static boolean rectsintersect(
int r1x0, int r1y0, int r1x1, int r1y1,
int r2x0, int r2y0, int r2x1, int r2y1) {
r1.set(r1x0, r1y0, r1x1, r1y1);
return r1.intersects(r2x0, r2y0, r2x1, r2y1);
}
/**
* Used as a callback from pdf rendering code.
* TODO: only invalidate what needs to be painted, not the whole view
*/
public void onImagesRendered(Map<Tile,Bitmap> renderedTiles) {
Log.d(TAG, "there are " + renderedTiles.size() + " new rendered tiles");
this.post(new Runnable() {
public void run() {
PagesView.this.invalidate();
}
});
}
/**
* Handle rendering exception.
* Show error message and then quit parent activity.
* TODO: find a proper way to finish an activity when something bad happens in view.
*/
public void onRenderingException(RenderingException reason) {
final Activity activity = this.activity;
final String message = reason.getMessage();
this.post(new Runnable() {
public void run() {
AlertDialog errorMessageDialog = new AlertDialog.Builder(activity)
.setTitle("Error")
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
activity.finish();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
activity.finish();
}
})
.create();
errorMessageDialog.show();
}
});
}
/**
* Move current viewport over n-th page.
* Page is 0-based.
* @param page 0-based page number
*/
synchronized public void scrollToPage(int page) {
this.left = this.width / 2;
float top = this.height / 2;
for(int i = 0; i < page; ++i) {
top += this.getCurrentPageHeight(i);
}
if (page > 0)
top += (float)MARGIN * this.zoomLevel * 0.001f * (float)(page);
this.top = (int)top;
this.currentPage = page;
this.invalidate();
}
// /**
// * Compute what's currently visible.
// * @return collection of tiles that define what's currently visible
// */
// private Collection<Tile> computeVisibleTiles() {
// LinkedList<Tile> tiles = new LinkedList<Tile>();
// float viewx = this.left + (this.dragx1 - this.dragx);
// float viewy = this.top + (this.dragy1 - this.dragy);
// float pagex = MARGIN;
// float pagey = MARGIN;
// float pageWidth;
// float pageHeight;
// int tileix;
// int tileiy;
// int thisPageTileCountX;
// int thisPageTileCountY;
// float tilex;
// float tiley;
// for(int page = 0; page < this.pageSizes.length; ++page) {
//
// pageWidth = this.getCurrentPageWidth(page);
// pageHeight = this.getCurrentPageHeight(page);
//
// thisPageTileCountX = (int)Math.ceil(pageWidth / TILE_SIZE);
// thisPageTileCountY = (int)Math.ceil(pageHeight / TILE_SIZE);
//
// if (viewy + this.height < pagey) continue; /* before first visible page */
// if (viewx > pagey + pageHeight) break; /* after last page */
//
// for(tileix = 0; tileix < thisPageTileCountX; ++tileix) {
// for(tileiy = 0; tileiy < thisPageTileCountY; ++tileiy) {
// tilex = pagex + tileix * TILE_SIZE;
// tiley = pagey + tileiy * TILE_SIZE;
// if (rectsintersect(viewx, viewy, viewx+this.width, viewy+this.height,
// tilex, tiley, tilex+TILE_SIZE, tiley+TILE_SIZE)) {
// tiles.add(new Tile(page, this.zoomLevel, (int)tilex, (int)tiley, this.rotation));
// }
// }
// }
//
// /* move to next page */
// pagey += this.getCurrentPageHeight(page) + MARGIN;
// }
// return tiles;
// }
// synchronized Collection<Tile> getVisibleTiles() {
// return this.visibleTiles;
// }
/**
* Rotate pages.
* Updates rotation variable, then invalidates view.
* @param rotation rotation
*/
synchronized public void rotate(int rotation) {
this.rotation = (this.rotation + rotation) % 4;
this.invalidate();
}
/**
* Set find mode.
* @param m true if pages view should display find results and find controls
*/
synchronized public void setFindMode(boolean m) {
if (this.findMode != m) {
this.findMode = m;
if (!m) {
this.findResults = null;
}
}
}
/**
* Return find mode.
* @return find mode - true if view is currently in find mode
*/
public boolean getFindMode() {
return this.findMode;
}
// /**
// * Ask pages provider to focus on next find result.
// * @param forward direction of search - true for forward, false for backward
// */
// public void findNext(boolean forward) {
// this.pagesProvider.findNext(forward);
// this.scrollToFindResult();
// this.invalidate();
// }
/**
* Move viewport position to find result (if any).
* Does not call invalidate().
*/
public void scrollToFindResult(int n) {
if (this.findResults == null || this.findResults.isEmpty()) return;
Rect center = new Rect();
FindResult findResult = this.findResults.get(n);
for(Rect marker: findResult.markers) {
center.union(marker);
}
int page = findResult.page;
int x = 0;
int y = 0;
for(int p = 0; p < page; ++p) {
Log.d(TAG, "adding page " + p + " to y: " + this.pageSizes[p][1]);
y += this.pageSizes[p][1];
}
x += (center.left + center.right) / 2;
y += (center.top + center.bottom) / 2;
float margin = this.getCurrentMargin();
this.left = (int)(x * scalling0 * this.zoomLevel * 0.001f + margin);
this.top = (int)(y * scalling0 * this.zoomLevel * 0.001f + (page+1)*margin);
}
/**
* Get the current page number
*
* @return the current page. 0-based
*/
public int getCurrentPage() {
return currentPage;
}
/**
* Get page count.
*/
public int getPageCount() {
return this.pageSizes.length;
}
/**
* Set find results.
*/
public void setFindResults(List<FindResult> results) {
this.findResults = results;
}
/**
* Get current find results.
*/
public List<FindResult> getFindResults() {
return this.findResults;
}
/**
* Zoom down one level
*/
public void zoomDown() {
float step = 1f/1.414f;
this.zoomLevel *= step;
this.left *= step;
this.top *= step;
Log.d(TAG, "zoom level changed to " + this.zoomLevel);
this.invalidate();
}
/**
* Zoom up one level
*/
public void zoomUp() {
float step = 1.414f;
this.zoomLevel *= step;
this.left *= step;
this.top *= step;
Log.d(TAG, "zoom level changed to " + this.zoomLevel);
this.invalidate();
}
}
|
Java
|
package cx.hell.android.lib.pagesview;
import java.util.Collection;
import android.graphics.Bitmap;
/**
* Provide content of pages rendered by PagesView.
*/
public abstract class PagesProvider {
/**
* Get page image tile for drawing.
*/
public abstract Bitmap getPageBitmap(Tile tile);
/**
* Get page count.
* This cannot change between executions - PagesView assumes (for now) that docuement doesn't change.
*/
public abstract int getPageCount();
/**
* Get page sizes.
* This cannot change between executions - PagesView assumes (for now) that docuement doesn't change.
*/
public abstract int[][] getPageSizes();
/**
* Set notify target.
* Usually page rendering takes some time. If image cannot be provided
* immediately, provider may return null.
* Then it's up to provider to notify view that requested image has arrived
* and is ready to be drawn.
* This function, if overridden, can be used to inform provider who
* should be notifed.
* Default implementation does nothing.
*/
public void setOnImageRenderedListener(OnImageRenderedListener listener) {
/* to be overridden when needed */
}
public abstract void setVisibleTiles(Collection<Tile> tiles);
}
|
Java
|
package cx.hell.android.lib.pagesview;
import java.util.Map;
import android.graphics.Bitmap;
/**
* Allow renderer to notify view that new bitmaps are ready.
* Implemented by PagesView.
*/
public interface OnImageRenderedListener {
void onImagesRendered(Map<Tile,Bitmap> renderedImages);
void onRenderingException(RenderingException reason);
}
|
Java
|
package com.jason.recognition;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
public class DrawLineActivity extends Activity {
private DrawView vw;
ArrayList<Point> mCurrentPointArray;
ArrayList<Point> mDrawPointArray;
Recognition mRecoginition;
private boolean mPressFirstBackKey = false;
private Timer mTimer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main); // 기존 뷰는 사용하지 않는다.
// 새로운 뷰를 생성하여 액티비티에 연결
vw = new DrawView(this);
setContentView(vw);
mCurrentPointArray = new ArrayList<Point>();
mDrawPointArray = new ArrayList<Point>();
}
@Override
public void onBackPressed() {
// back key 한번 누르면 이전도형 clear
// back key연속 두번 누르면 종료처리
if (mPressFirstBackKey == false) {
mCurrentPointArray.clear();
// 마지막 도형의 시작 index를 찾는다.
int sLastShapePos = 0;
for (int i = 0; i < mDrawPointArray.size(); i++) {
if (mDrawPointArray.get(i).mIsStart == true) {
sLastShapePos = i;
}
}
// 마지막 도형을 삭제한다.
if( mDrawPointArray.size() > 0 )
{
for (int i = mDrawPointArray.size()-1; i >= sLastShapePos; i--) {
mDrawPointArray.remove(mDrawPointArray.get(i));
}
vw.invalidate(); // onDraw() 호출
Toast.makeText(this, "last shape clear", 1).show();
}
else
{
Toast.makeText(this, "already all shape clear", 1).show();
}
mPressFirstBackKey = true;
// back키가 2초내에 두번 눌렸는지 감지
TimerTask second = new TimerTask() {
@Override
public void run() {
mTimer.cancel();
mTimer = null;
mPressFirstBackKey = false;
}
};
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
mTimer = new Timer();
mTimer.schedule(second, 800);
} else {
super.onBackPressed();
}
}
public class Point {
float x;
float y;
boolean mIsStart; // 시작점 여부
float mRadius; // 반지름 : 이 값이 0보다 크면 원이다.
public Point() {
this.x = 0;
this.y = 0;
this.mRadius = 0;
this.mIsStart = false;
}
public Point(float x, float y, boolean isStart) {
this.x = x;
this.y = y;
this.mRadius = 0;
this.mIsStart = isStart;
}
}
protected class Recognition {
Context mContext;
ArrayList<Point> mPointArray; // 모든 점이 저장됨
ArrayList<Point> mVertexList; // 꼭지점이 저장됨.
/*
* 각도는 mBasePoint와 현재 점의 각을 구한다. mBasePoint는 6개 이전 점으로 한다.
*/
Point mPointSum = new Point();
double mRadianAvr = 0; // 평균 각도
int mSumCount = 0; // sum된 개수
Point mBasePoint; // 각도를 잴 기준 점.
public Recognition(Context aContext) {
mContext = aContext;
mPointArray = new ArrayList<Point>();
mVertexList = new ArrayList<Point>();
mBasePoint = new Point();
}
// 점이 추가될때 호출되는 인터페이스
public void add(float x, float y, boolean isStart) {
// mPointArray에 점을 추가
mPointArray.add(new Point(x, y, isStart));
// 첫번째 점이면 mBasePoint를 기준점 및 꼭지점으로 설정하고 종료
if (isStart == true) {
mBasePoint = mPointArray.get(0);
mVertexList.add(new Point(x, y, isStart));
return;
}
// 기준점으로부터 6개 이상 넘어가면 기준점을 6개 이전 점으로 설정한다.
if (mSumCount > 6) {
mBasePoint = mPointArray.get(mPointArray.size() - 6);
}
// mBasePoint와 현재 점의 각도를 구한다.
float xChangeCur = x - mBasePoint.x;
float yChangeCur = y - mBasePoint.y;
// atan2함수를 이용하여 mBasePoint와 현재 점의 각도를 구한다.
double sRadian = Math.atan2(yChangeCur, xChangeCur);
//Log.i("test", " sRadian : " + sRadian + " sRadianAvr : " + mRadianAvr);
// 꼭지점이 생기고 처음 3개는 꼭지점으로 인식하지 않는다.
if (mSumCount >= 4) {
// 이번 각도가 평균과 비슷한지 체크한다.
// Math.PI = 3.14
// RadianAvr은 0이 0도, PI/2가 90도 PI가 180도, -PI/2가 -90도, -PI가
// -180도이다.
// 180도와 -180도는 같은데 다르게 표현됨.
// 아래에서 0.6은 30~40도 정도 될것 같음.
if (sRadian < mRadianAvr + 0.6 && sRadian > mRadianAvr - 0.6) {
// 각도가 비슷함.
// 꼭지점 아님.
} else if ((sRadian + Math.PI * 2) < mRadianAvr + 0.6
&& (sRadian + Math.PI * 2) > mRadianAvr - 0.6) {
// sRadina에 2pi를 더한것과 비슷함
// 꼭지점 아님.
} else if ((sRadian - Math.PI * 2) < mRadianAvr + 0.6
&& (sRadian - Math.PI * 2) > mRadianAvr - 0.6) {
// sRadina에 2pi를 뺀것과 비슷함
// 꼭지점 아님.
} else {
// 꼭지점이다.
// Log.i("test", "find Vertex ");
// 각도는 꼭지점 부터 다시 재야 함으로 mRadianSum, mSumCount 는 초기화 함.
mPointSum.x = 0;
mPointSum.y = 0;
mSumCount = 0;
xChangeCur = 0;
yChangeCur = 0;
// 이전 point를 base point로 설정한다.
mBasePoint = mPointArray.get(mPointArray.size() - 2);
// 이전 point를 꼭지점으로 정한다.
mVertexList
.add(new Point(mBasePoint.x, mBasePoint.y, false));
}
}
// 좌표의 합을 구한다.
mPointSum.x = mPointSum.x + xChangeCur;
mPointSum.y = mPointSum.y + yChangeCur;
mSumCount++;
// 평균 각도를 구한다.
mRadianAvr = Math.atan2(mPointSum.y, mPointSum.x);
}
public void end() {
// 직선이면 마지막 점을 꼭지점으로 설정
if (mVertexList.size() == 1) {
mBasePoint = mPointArray.get(mPointArray.size() - 1);
mVertexList.add(new Point(mBasePoint.x, mBasePoint.y, false));
}
// 직선이 아니면 처음과 끝이 어느정도 가까우면
// 처음 꼭지점을 마지막 꼭지점으로 입력
else {
mBasePoint = mVertexList.get(0);
Point sLastPoint = mPointArray.get(mPointArray.size() - 1);
if ((mBasePoint.x - sLastPoint.x > -30 && mBasePoint.x
- sLastPoint.x < 30)
&& (mBasePoint.y - sLastPoint.y > -30 && mBasePoint.y
- sLastPoint.y < 30)) {
mVertexList
.add(new Point(mBasePoint.x, mBasePoint.y, false));
// Log.i("xx", "mVertexList.size " + mVertexList.size());
// 꼭지점이 5보다 크고 모든 내각이 180보다 작으면 원으로 인식한다.
// 내각을 체크한다.
boolean sIsCircle = true;
float sInnerAngle = 0;
for (int i = 1; i < mVertexList.size(); i++) {
Point v1 = new Point();
if (i == 1) {
v1.x = mVertexList.get(mVertexList.size() - 2).x
- mVertexList.get(i - 1).x;
v1.y = mVertexList.get(mVertexList.size() - 2).y
- mVertexList.get(i - 1).y;
} else {
v1.x = mVertexList.get(i - 2).x
- mVertexList.get(i - 1).x;
v1.y = mVertexList.get(i - 2).y
- mVertexList.get(i - 1).y;
}
Point v2 = new Point();
v2.x = mVertexList.get(i).x - mVertexList.get(i - 1).x;
v2.y = mVertexList.get(i).y - mVertexList.get(i - 1).y;
// 두 직선의 내각을 구한다.
// 내각 = asin(x1y2-y1x2 / ( sqrt(x1*x1 + y1*y1) +
// sqrt(x2*x2 + y2*y2) )
double sRadian = Math.asin((v1.x * v2.y - v1.y * v2.x)
/ (Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math
.sqrt(v2.x * v2.x + v2.y * v2.y)));
// Log.i("check circle", "sRadian " + sRadian);
if (sRadian > 0) {
if (i == 1) {
sInnerAngle = 1;
} else if (sInnerAngle == -1) {
sIsCircle = false;
}
} else {
if (i == 1) {
sInnerAngle = -1;
} else if (sInnerAngle == 1) {
sIsCircle = false;
}
}
}
if (mVertexList.size() > 5 && sIsCircle == true) {
// 원을 그리기 위해 중심점과 반지름을 구한다.
Point sMin = new Point();
Point sMax = new Point();
Point sCenter = new Point();
// 원이면 x,y 축 각각 min + max /2 로 중심점을 구한다.
// 초기값은 첫번째 점
sMin.x = mPointArray.get(0).x;
sMin.y = mPointArray.get(0).y;
sMax.x = mPointArray.get(0).x;
sMax.y = mPointArray.get(0).y;
for (int i = 1; i < mPointArray.size(); i++) {
if (sMin.x > mPointArray.get(i).x) {
sMin.x = mPointArray.get(i).x;
}
if (sMin.y > mPointArray.get(i).y) {
sMin.y = mPointArray.get(i).y;
}
if (sMax.x < mPointArray.get(i).x) {
sMax.x = mPointArray.get(i).x;
}
if (sMax.y < mPointArray.get(i).y) {
sMax.y = mPointArray.get(i).y;
}
}
sCenter.mIsStart = true;
sCenter.x = (sMin.x + sMax.x) / 2;
sCenter.y = (sMin.y + sMax.y) / 2;
sCenter.mRadius = Math.abs((sCenter.x - sMin.x) / 2
+ (sCenter.y - sMin.y) / 2);
mVertexList.clear();
mVertexList.add(sCenter);
}
} else {
// Log.i("###", "xx: " + (mBasePoint.x - sLastPoint.x) +
// " yy: " + (mBasePoint.y - sLastPoint.y));
mVertexList.add(sLastPoint);
}
}
// for(int i=0; i<mVertexList.size(); i++)
// {
// Log.i("end", "index " + i +
// " x " + mVertexList.get(i).x +
// " y " + mVertexList.get(i).y +
// " isStart " + mVertexList.get(i).mIsStart);
// }
// mRecoginition.mVertexList가 직선이면 원과 접선을 그린것인지 체크해본다.
if( mVertexList.size() == 2 ) {
// size가 2이면 직선이다.
// 기존에 그려진 원을 찾는다.
for (int i = 0; i < mDrawPointArray.size(); i++) {
final Point sCircle = mDrawPointArray.get(i);
if (sCircle.mRadius > 0) {
Log.i("접선", "기존원 x:" + sCircle.x + " y " + sCircle.y +
" r : " + sCircle.mRadius );
// 원의 중심점과 직선의 거리를 구해서 반지름과 비교한다.
// 점과 직선의 거리 : d = |ax1 + by1 + c| / root(a^2 + b^2)
// 두점(x1,y1)(x2,y2)을 지나는 직선의 방정식 : y - y1 = (y2 - y1)/(x2 - x1) * (x - x1)
// 직선의 방정식을 적용하면 시작점과 끝점이 없는 직선이 만들어진다.
// 우리가 원하는 직선은 시잠점과 끝점이 있는데..
// 그래서 일단 쉽게 직선상의 점과 원의 중심점의 거리의 최소값을 구하는걸로 원의 중심점과 직선의 거리를 구한다.
double sDistance = 0;
double sMinDistance = 0;
Point sStart = mVertexList.get(0);
Point sEnd = mVertexList.get(1);
Point sPointOfTangency = new Point();
// 직선을 100개의 점으로 나눴을때 다음점으로 이동되는 값
float xChange = (sEnd.x - sStart.x) / 100;
float yChange = (sEnd.y - sStart.y) / 100;
// 100개의 점에 대해서 원의 중심점과 거리 구하고 그중에서 최소값을 원과 직선의 거리로 인식한다.
for( int j=0; j<100; j++ )
{
// 두점의 거리 d = root( (x1-x2)^2 + (y1-y2)^2 )
sDistance = Math.pow(sCircle.x - (sStart.x + xChange * j), 2);
sDistance += Math.pow(sCircle.y - (sStart.y + yChange * j), 2);
sDistance = Math.sqrt( sDistance );
if( j == 0 || sDistance < sMinDistance )
{
// MinDistance에 첫번째 값을 설정한다.
// 두번째 부터는 sMinDistance 보다 작은 값이면 sMinDistance를 sDistance로 설정한다.
sMinDistance = sDistance;
sPointOfTangency.x = sStart.x + xChange * j;
sPointOfTangency.y = sStart.y + yChange * j;
}
}
Log.i("접선", "직선과 거리 : " + sMinDistance );
// 원과 직선의 오차가 20 이내면 접선으로 인식
if( Math.abs(sMinDistance - sCircle.mRadius) < 20 )
{
Toast toast = Toast.makeText(mContext, "recognized Tangency", Toast.LENGTH_SHORT);
toast.show();
Log.i("접선", "after show" );
ProcessTangent(sMinDistance, sCircle, sPointOfTangency);
// 접선이 인식되었으면 다른 원과의 비교는 종료한다.
}
}
}
}
}
// 접선 처리하는 인터페이스
public void ProcessTangent(double sMinDistance, Point sCircle, Point sPointOfTangency) {
Point sStart = mVertexList.get(0);
Point sEnd = mVertexList.get(1);
// 움직여야 하는 거리(sMove)는 반지름 - 직선과 원중심점 거리이다.
double sMove = Math.sqrt(Math.pow(sCircle.mRadius - sMinDistance, 2) / 2);
// 접선 이면 직선을 접선이 되도록 이동
// 원의 중심을 기준으로 접점
Point sTemp = new Point(sPointOfTangency.x - sCircle.x, sPointOfTangency.y - sCircle.y, false);
// 접점의 각도
double sRadian = Math.atan2(sTemp.y, sTemp.x);
// 각도가 sRadian이고 대각선이sMove일때 이동해야 하는 x값
double sMoveX = Math.cos(sRadian) * sMove;
// 각도가 sRadian이고 대각선이sMove일때 이동해야 하는 y값
double sMoveY = Math.sin(sRadian) * sMove;
Log.i("접선", "sMoveX " + sMoveX + " sMoveY " + sMoveY );
if( sMinDistance > sCircle.mRadius )
{
// 직선을 원 중심으로 이동
sStart.x -= sMoveX;
sEnd.x -= sMoveX;
sStart.y -= sMoveY;
sEnd.y -= sMoveY;
}
else
{
// 직선을 원 바깥으로 이동
sStart.x += sMoveX;
sEnd.x += sMoveX;
sStart.y += sMoveY;
sEnd.y += sMoveY;
}
}
}
protected class DrawView extends View {
Paint mPaint; // 페인트 객체 선언
Context mContext;
public DrawView(Context context) {
super(context);
mContext = context;
// 페인트 객체 생성 후 설정
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(3);
mPaint.setAntiAlias(true); // 안티얼라이싱
mPaint.setStyle(Paint.Style.STROKE);
}
/** 터치이벤트를 받는 함수 */
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mCurrentPointArray.add(new Point(event.getX(), event.getY(),
true));
mRecoginition = new Recognition(mContext);
mRecoginition.add(event.getX(), event.getY(), true);
break;
case MotionEvent.ACTION_MOVE:
//Log.i("xx", "xy " + event.getX() + " : " + event.getY() );
mCurrentPointArray.add(new Point(event.getX(), event.getY(),
false));
mRecoginition.add(event.getX(), event.getY(), false);
break;
case MotionEvent.ACTION_UP:
mRecoginition.end();
mCurrentPointArray.clear();
mDrawPointArray.addAll(mRecoginition.mVertexList);
break;
}
invalidate(); // onDraw() 호출
return true;
}
/** 화면을 계속 그려주는 함수 */
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE); // 캔버스 배경색깔 설정
// 인식된 도형 그리기
for (int i = 0; i < mDrawPointArray.size(); i++) {
if (mDrawPointArray.get(i).mIsStart == false) { // 이어서 그리고 있는
// 중이라면
canvas.drawLine(mDrawPointArray.get(i - 1).x,
mDrawPointArray.get(i - 1).y,
mDrawPointArray.get(i).x, mDrawPointArray.get(i).y,
mPaint);
// 이전 좌표에서 다음좌표까지 그린다.
}
if (mDrawPointArray.get(i).mRadius > 0) {
// 원 그리기
canvas.drawCircle(mDrawPointArray.get(i).x,
mDrawPointArray.get(i).y,
mDrawPointArray.get(i).mRadius, mPaint);
} else {
// 점만 찍는다.
canvas.drawPoint(mDrawPointArray.get(i).x,
mDrawPointArray.get(i).y, mPaint);
}
}
// 현재 터치중인 모양 그리기
for (int i = 0; i < mCurrentPointArray.size(); i++) {
// 점만 찍는다.
canvas.drawPoint(mCurrentPointArray.get(i).x,
mCurrentPointArray.get(i).y, mPaint);
}
}
}
}
|
Java
|
package com.jason.recognition;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.jason.recognition.*;
/*
* public class MainActivity extends Activity {
*
* @Override protected void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
*
* Intent intent = new Intent(this, DrawLineActivity.class);
* startActivity(intent); }
*
* }
*/
|
Java
|
public class hello {
public static void main(String[] args){
System.out.println("hello world");
}
}
|
Java
|
package client;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client_Chat {
public void Chat() throws IOException {
try {
Socket sk = new Socket("localhost", 3200);
//System.out.println(sk.getPort());
InputStream is = sk.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStream os = sk.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
System.out.print("Client: ");
do {
Scanner sn = new Scanner(System.in);
String sentMessage = sn.nextLine();
bw.write(sentMessage);
bw.newLine();
bw.flush();
// Client muon cham dut viec chat thi go "quit"
if (sentMessage.equalsIgnoreCase("quit")) {
break;
}
else {
String receivedMessage = br.readLine();
System.out.print("Server: " + receivedMessage + "\nClient: ");
}
} while (true);
bw.close();
br.close();
sk.close();
} catch (IOException e) { }
}
}
|
Java
|
package client;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
Client_Chat cc = new Client_Chat();
cc.Chat();
}
}
|
Java
|
package server;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server_Chat {
public void Chat() throws IOException {
try {
ServerSocket sk = new ServerSocket(3200);
do {
//System.out.println("Waiting for a client...");
Socket ss = sk.accept();
//System.out.println("Client has joined to chat!");
//System.out.println(ss.getPort());
InputStream is = ss.getInputStream();
BufferedReader br;
br = new BufferedReader(new InputStreamReader(is));
OutputStream os = ss.getOutputStream();
BufferedWriter bw;
bw = new BufferedWriter(new OutputStreamWriter(os));
do {
String receivedMessage = br.readLine();
// Client go vao "quit" thi cham dut
// viec chat vs Server
if (receivedMessage.equalsIgnoreCase("quit")) {
System.out.println("Client has left!");
break;
}
System.out.print("Client : " + receivedMessage + "\nServer: ");
Scanner sn = new Scanner(System.in);
String sentMessage = sn.nextLine();
bw.write(sentMessage);
bw.newLine();
bw.flush();
} while (true);
bw.close();
br.close();
sk.close();
} while (true);
} catch (IOException e) { }
}
}
|
Java
|
package server;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
Server_Chat sc = new Server_Chat();
sc.Chat();
}
}
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package skdemo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocketExample {
public static void main(String[] args) {
try {
//
// Create a connection to the server socket on the server application
//
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(), 7777);
//
// Send a message to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hello There...");
//
// Read and display the response message sent by server application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
oos.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package skdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
public class Client1 extends javax.swing.JFrame {
static Socket client;
static PrintWriter OutputStream;
static BufferedReader InputServer;
public Client1() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
JIPadress = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
Connect = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
Disonnect = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
Screen = new javax.swing.JTextArea();
ServerSend = new javax.swing.JTextField();
Trangthai = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JIPadress.setText("Localhost");
JIPadress.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
JIPadressMousePressed(evt);
}
});
jLabel2.setText("Server");
jTextField3.setText("2424");
Connect.setText("Connect");
Connect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ConnectActionPerformed(evt);
}
});
jLabel3.setText("Status");
Disonnect.setText("Disonnect");
Disonnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DisonnectActionPerformed(evt);
}
});
Screen.setColumns(20);
Screen.setRows(5);
jScrollPane1.setViewportView(Screen);
ServerSend.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
ServerSendKeyReleased(evt);
}
});
Trangthai.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
.addComponent(ServerSend)))
.addGroup(layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(Trangthai, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(320, 320, 320))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JIPadress, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Connect, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Disonnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(26, 26, 26)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(43, Short.MAX_VALUE)
.addComponent(Trangthai)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ServerSend, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JIPadress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(Connect)
.addComponent(Disonnect))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addContainerGap(241, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void JIPadressMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JIPadressMousePressed
JIPadress.setText("");
}//GEN-LAST:event_JIPadressMousePressed
private void ServerSendKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ServerSendKeyReleased
if (evt.getKeyCode() == 10) {
try {
OutputStream = new PrintWriter(client.getOutputStream(), true);
OutputStream.println(ServerSend.getText());
Screen.append("\nClient: " + ServerSend.getText());
ServerSend.setText("");
} catch (Exception e) {
System.out.printf(":OIJI");
}
}
}//GEN-LAST:event_ServerSendKeyReleased
private void ConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConnectActionPerformed
}//GEN-LAST:event_ConnectActionPerformed
private void DisonnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DisonnectActionPerformed
try {
client.close();
} catch (IOException e) {
}
}//GEN-LAST:event_DisonnectActionPerformed
public static void main(String args[]) throws Exception {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Client1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Client1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Client1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Client1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Client1().setVisible(true);
}
});
try {
client = new Socket();
client.connect(new InetSocketAddress(InetAddress.getLocalHost(), 1991));
System.out.print("THANH CONG");
} catch (IOException e) {
System.out.print(e.toString());
}
while (true) {
InputServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
Screen.append("\nServer :" + InputServer.readLine());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Connect;
private javax.swing.JButton Disonnect;
private javax.swing.JTextField JIPadress;
static javax.swing.JTextArea Screen;
private javax.swing.JTextField ServerSend;
static javax.swing.JLabel Trangthai;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField3;
// End of variables declaration//GEN-END:variables
}
|
Java
|
package skdemo;
import java.io.Serializable;
public class ChatMessage implements Serializable {
protected static final long serialVersionUID = 1112122200L;
// The different types of message sent by the Client
// WHOISIN to receive the list of the users connected
// MESSAGE an ordinary message
// LOGOUT to disconnect from the Server
static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2;
private int type;
private String message;
// constructor
ChatMessage(int type, String message) {
this.type = type;
this.message = message;
}
// getters
int getType() {
return type;
}
String getMessage() {
return message;
}
}
|
Java
|
package skdemo;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class SKDemoClient {
public static void main(String agrS[]) throws Exception
{
SKDemoClient abc=new SKDemoClient();
abc.run();
}
public void run() throws Exception
{
Socket SOCK=new Socket(InetAddress.getLocalHost(),1993);
PrintStream PS=new PrintStream(SOCK.getOutputStream());
PS.println("CHAO!");
PS=new PrintStream(SOCK.getOutputStream());
PS.println("CHAO!");
InputStreamReader ISR=new InputStreamReader(SOCK.getInputStream());
BufferedReader BR=new BufferedReader(ISR);
String MESSAGE=BR.readLine();
System.out.println(MESSAGE);
}
}
|
Java
|
package skdemo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
public class SKCl {
private ServerSocket server;
private int port = 7777;
public SKCl() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SKCl example = new SKCl();
example.handleConnection();
}
public void handleConnection() {
System.out.println("Waiting for client message...");
//
// The server do a loop here to accept all connection initiated by the
// client application.
//
while (true) {
try {
Socket socket = server.accept();
new ConnectionHandler(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket) {
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
public void run() {
try
{
//
// Read a message sent by client application
//
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//
// Send a response information to the client application
//
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Hi...");
ois.close();
oos.close();
socket.close();
System.out.println("Waiting for client message...");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package skdemo;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* The server that can be run both as a console application or a GUI
*/
public class Server {
// a unique ID for each connection
private static int uniqueId;
// an ArrayList to keep the list of the Client
private ArrayList<ClientThread> al;
// if I am in a GUI
private ServerGUI sg;
// to display time
private SimpleDateFormat sdf;
// the port number to listen for connection
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
/*
* server constructor that receive the port to listen to for connection as parameter
* in console
*/
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
// GUI or not
this.sg = sg;
// the port
this.port = port;
// to display hh:mm:ss
sdf = new SimpleDateFormat("HH:mm:ss");
// ArrayList for the Client list
al = new ArrayList<ClientThread>();
}
public void start() {
keepGoing = true;
/* create socket server and wait for connection requests */
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a thread of it
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("localhost", port);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
/*
* to broadcast a message to all Clients
*/
private synchronized void broadcast(String message) {
// add HH:mm:ss and \n to the message
String time = sdf.format(new Date());
String messageLf = time + " " + message + "\n";
// display message on console or GUI
if(sg == null)
System.out.print(messageLf);
else
sg.appendRoom(messageLf); // append in the room window
// we loop in reverse order in case we would have to remove a Client
// because it has disconnected
for(int i = al.size(); --i >= 0;) {
ClientThread ct = al.get(i);
// try to write to the Client if it fails remove it from the list
if(!ct.writeMsg(messageLf)) {
al.remove(i);
display("Disconnected Client " + ct.username + " removed from list.");
}
}
}
// for a client who logoff using the LOGOUT message
synchronized void remove(int id) {
// scan the array list until we found the Id
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
// found it
if(ct.id == id) {
al.remove(i);
return;
}
}
}
/*
* To run as a console application just open a console window and:
* > java Server
* > java Server portNumber
* If the port number is not specified 1500 is used
*/
public static void main(String[] args) {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server [portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// the Username of the Client
String username;
// the only type of message a will receive
ChatMessage cm;
// the date I connect
String date;
// Constructore
ClientThread(Socket socket) {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
username = (String) sInput.readObject();
display(username + " just connected.");
}
catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return;
}
// have to catch ClassNotFoundException
// but I read a String, I am sure it will work
catch (ClassNotFoundException e) {
}
date = new Date().toString() + "\n";
}
// what will run forever
public void run() {
// to loop until LOGOUT
boolean keepGoing = true;
while(keepGoing) {
// read a String (which is an object)
try {
cm = (ChatMessage) sInput.readObject();
}
catch (IOException e) {
display(username + " Exception reading Streams: " + e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
// the messaage part of the ChatMessage
String message = cm.getMessage();
// Switch on the type of message receive
switch(cm.getType()) {
case ChatMessage.MESSAGE:
broadcast(username + ": " + message);
break;
case ChatMessage.LOGOUT:
display(username + " disconnected with a LOGOUT message.");
keepGoing = false;
break;
case ChatMessage.WHOISIN:
writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n");
// scan al the users connected
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
writeMsg((i+1) + ") " + ct.username + " since " + ct.date);
}
break;
}
}
// remove myself from the arrayList containing the list of the
// connected Clients
remove(id);
close();
}
// try to close everything
private void close() {
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
/*
* Write a String to the Client output stream
*/
private boolean writeMsg(String msg) {
// if Client is still connected send the message to it
if(!socket.isConnected()) {
close();
return false;
}
// write the message to the stream
try {
sOutput.writeObject(msg);
}
// if an error occurs, do not abort just inform the user
catch(IOException e) {
display("Error sending message to " + username);
display(e.toString());
}
return true;
}
}
}
|
Java
|
package skdemo;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SKDemo {
public static void main(String[] args) throws Exception{
SKDemo abc=new SKDemo();
abc.run();
}
public void run() throws Exception
{
ServerSocket Server = new ServerSocket(1993);
Socket client = Server.accept();
InputStreamReader Vao = new InputStreamReader(client.getInputStream());
BufferedReader Bvao = new BufferedReader(Vao);
String nhan = Bvao.readLine();
System.out.print(nhan);
if (nhan != null) {
PrintStream PS = new PrintStream(client.getOutputStream());
PS.println("Da nhan!");
}
}
}
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package skdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JEditorPane;
public class Server1 extends javax.swing.JFrame {
static ServerSocket Server;
static Socket Client;
static String gui, nhan;
static BufferedReader Input ;
public Server1() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
Open = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
Screen = new javax.swing.JTextArea();
Close = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
trangthai = new javax.swing.JLabel();
ServerSend = new javax.swing.JTextField();
jLabel1.setText("jLabel1");
jTextField1.setText("jTextField1");
jButton2.setText("jButton2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField2.setText("Localhost");
jTextField3.setText("2424");
jLabel2.setText("Server");
Open.setText("Open");
Open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenActionPerformed(evt);
}
});
Screen.setColumns(20);
Screen.setRows(5);
jScrollPane1.setViewportView(Screen);
Close.setText("Close");
Close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseActionPerformed(evt);
}
});
jLabel3.setText("Status");
trangthai.setText("Not connect");
ServerSend.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
ServerSendKeyReleased(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(trangthai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Open, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Close, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ServerSend)
.addComponent(jScrollPane1))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 7, Short.MAX_VALUE)
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Close, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(Open)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(trangthai))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ServerSend, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15))
);
jLabel4.getAccessibleContext().setAccessibleName("Status");
pack();
}// </editor-fold>//GEN-END:initComponents
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenActionPerformed
}//GEN-LAST:event_OpenActionPerformed
private void ServerSendKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ServerSendKeyReleased
if (evt.getKeyCode() == 10) {
try {
PrintWriter outputCliet = new PrintWriter(Client.getOutputStream(), true);
outputCliet.println(ServerSend.getText());
Screen.append("\nServer: " + ServerSend.getText());
ServerSend.setText("");
} catch (Exception e) {
}
}
}//GEN-LAST:event_ServerSendKeyReleased
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseActionPerformed
try {
Server.close();
trangthai.setText("Đã ngắt");
} catch (Exception e) {
trangthai.setText("Chưa kết nối mà");
}
}//GEN-LAST:event_CloseActionPerformed
public static void main(String args[]) throws Exception {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server1().setVisible(true);
}
});
try {
Server = new ServerSocket(1991);
System.out.printf("OK");
} catch (IOException ex) { System.out.printf("!OK");
}
Client = Server.accept();
Input = new BufferedReader(
new InputStreamReader(Client.getInputStream()));
while (true)
{
Screen.append("\n Client" + Input.readLine());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Close;
private javax.swing.JButton Open;
static javax.swing.JTextArea Screen;
private static javax.swing.JTextField ServerSend;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
static javax.swing.JLabel trangthai;
// End of variables declaration//GEN-END:variables
}
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package skdemo;
import java.net.*;
import java.io.*;
import java.util.*;
/*
* The Client that can be run both as a console or a GUI
*/
public class Client {
// for I/O
private ObjectInputStream sInput; // to read from the socket
private ObjectOutputStream sOutput; // to write on the socket
private Socket socket;
// if I use a GUI or not
private ClientGUI cg;
// the server, the port and the username
private String server, username;
private int port;
/*
* Constructor called by console mode
* server: the server address
* port: the port number
* username: the username
*/
Client(String server, int port, String username) {
// which calls the common constructor with the GUI set to null
this(server, port, username, null);
}
/*
* Constructor call when used from a GUI
* in console mode the ClienGUI parameter is null
*/
Client(String server, int port, String username, ClientGUI cg) {
this.server = server;
this.port = port;
this.username = username;
// save if we are in GUI mode or not
this.cg = cg;
}
/*
* To start the dialog
*/
public boolean start() {
// try to connect to the server
try {
socket = new Socket(server, port);
}
// if it failed not much I can so
catch(Exception ec) {
display("Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
/* Creating both Data Stream */
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}
// creates the Thread to listen from the server
new ListenFromServer().start();
// Send our username to the server this is the only message that we
// will send as a String. All other messages will be ChatMessage objects
try
{
sOutput.writeObject(username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}
// success we inform the caller that it worked
return true;
}
/*
* To send a message to the console or the GUI
*/
private void display(String msg) {
if(cg == null)
System.out.println(msg); // println in console mode
else
cg.append(msg + "\n"); // append to the ClientGUI JTextArea (or whatever)
}
/*
* To send a message to the server
*/
void sendMessage(ChatMessage msg) {
try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}
/*
* When something goes wrong
* Close the Input/Output streams and disconnect not much to do in the catch clause
*/
private void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {} // not much else I can do
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {} // not much else I can do
try{
if(socket != null) socket.close();
}
catch(Exception e) {} // not much else I can do
// inform the GUI
if(cg != null)
cg.connectionFailed();
}
/*
* To start the Client in console mode use one of the following command
* > java Client
* > java Client username
* > java Client username portNumber
* > java Client username portNumber serverAddress
* at the console prompt
* If the portNumber is not specified 1500 is used
* If the serverAddress is not specified "localHost" is used
* If the username is not specified "Anonymous" is used
* > java Client
* is equivalent to
* > java Client Anonymous 1500 localhost
* are eqquivalent
*
* In console mode, if an error occurs the program simply stops
* when a GUI id used, the GUI is informed of the disconnection
*/
public static void main(String[] args) {
// default values
int portNumber = 1500;
String serverAddress = "localhost";
String userName = "Anonymous";
// depending of the number of arguments provided we fall through
switch(args.length) {
// > javac Client username portNumber serverAddr
case 3:
serverAddress = args[2];
// > javac Client username portNumber
case 2:
try {
portNumber = Integer.parseInt(args[1]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]");
return;
}
// > javac Client username
case 1:
userName = args[0];
// > java Client
case 0:
break;
// invalid number of arguments
default:
System.out.println("Usage is: > java Client [username] [portNumber] {serverAddress]");
return;
}
// create the Client object
Client client = new Client(serverAddress, portNumber, userName);
// test if we can start the connection to the Server
// if it failed nothing we can do
if(!client.start())
return;
// wait for messages from user
Scanner scan = new Scanner(System.in);
// loop forever for message from the user
while(true) {
System.out.print("> ");
// read message from user
String msg = scan.nextLine();
// logout if message is LOGOUT
if(msg.equalsIgnoreCase("LOGOUT")) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
// break to do the disconnect
break;
}
// message WhoIsIn
else if(msg.equalsIgnoreCase("WHOISIN")) {
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
}
else { // default to ordinary message
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg));
}
}
// done disconnect
client.disconnect();
}
/*
* a class that waits for the message from the server and append them to the JTextArea
* if we have a GUI or simply System.out.println() it in console mode
*/
class ListenFromServer extends Thread {
public void run() {
while(true) {
try {
String msg = (String) sInput.readObject();
// if console mode print the message and add back the prompt
if(cg == null) {
System.out.println(msg);
System.out.print("> ");
}
else {
cg.append(msg);
}
}
catch(IOException e) {
display("Server has close the connection: " + e);
if(cg != null)
cg.connectionFailed();
break;
}
// can't happen with a String object but need the catch anyhow
catch(ClassNotFoundException e2) {
}
}
}
}
}
|
Java
|
package skdemo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
* The server as a GUI
*/
public class ServerGUI extends JFrame implements ActionListener, WindowListener {
private static final long serialVersionUID = 1L;
// the stop and start buttons
private JButton stopStart;
// JTextArea for the chat room and the events
private JTextArea chat, event;
// The port number
private JTextField tPortNumber;
// my server
private Server server;
// server constructor that receive the port to listen to for connection as parameter
ServerGUI(int port) {
super("Chat Server");
server = null;
// in the NorthPanel the PortNumber the Start and Stop buttons
JPanel north = new JPanel();
north.add(new JLabel("Port number: "));
tPortNumber = new JTextField(" " + port);
north.add(tPortNumber);
// to stop or start the server, we start with "Start"
stopStart = new JButton("Start");
stopStart.addActionListener(this);
north.add(stopStart);
add(north, BorderLayout.NORTH);
// the event and chat room
JPanel center = new JPanel(new GridLayout(2,1));
chat = new JTextArea(80,80);
chat.setEditable(false);
appendRoom("Chat room.\n");
center.add(new JScrollPane(chat));
event = new JTextArea(80,80);
event.setEditable(false);
appendEvent("Events log.\n");
center.add(new JScrollPane(event));
add(center);
// need to be informed when the user click the close button on the frame
addWindowListener(this);
setSize(400, 600);
setVisible(true);
}
// append message to the two JTextArea
// position at the end
void appendRoom(String str) {
chat.append(str);
chat.setCaretPosition(chat.getText().length() - 1);
}
void appendEvent(String str) {
event.append(str);
event.setCaretPosition(chat.getText().length() - 1);
}
// start or stop where clicked
public void actionPerformed(ActionEvent e) {
// if running we have to stop
if(server != null) {
server.stop();
server = null;
tPortNumber.setEditable(true);
stopStart.setText("Start");
return;
}
// OK start the server
int port;
try {
port = Integer.parseInt(tPortNumber.getText().trim());
}
catch(Exception er) {
appendEvent("Invalid port number");
return;
}
// ceate a new Server
server = new Server(port, this);
// and start it as a thread
new ServerRunning().start();
stopStart.setText("Stop");
tPortNumber.setEditable(false);
}
// entry point to start the Server
public static void main(String[] arg) {
// start server default port 1500
new ServerGUI(1500);
}
/*
* If the user click the X button to close the application
* I need to close the connection with the server to free the port
*/
public void windowClosing(WindowEvent e) {
// if my Server exist
if(server != null) {
try {
server.stop(); // ask the server to close the conection
}
catch(Exception eClose) {
}
server = null;
}
// dispose the frame
dispose();
System.exit(0);
}
// I can ignore the other WindowListener method
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/*
* A thread to run the Server
*/
class ServerRunning extends Thread {
public void run() {
server.start(); // should execute until if fails
// the server failed
stopStart.setText("Start");
tPortNumber.setEditable(true);
appendEvent("Server crashed\n");
server = null;
}
}
}
|
Java
|
package skdemo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
* The Client with its GUI
*/
public class ClientGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
// will first hold "Username:", later on "Enter message"
private JLabel label;
// to hold the Username and later on the messages
private JTextField tf;
// to hold the server address an the port number
private JTextField tfServer, tfPort;
// to Logout and get the list of the users
private JButton login, logout, whoIsIn;
// for the chat room
private JTextArea ta;
// if it is for connection
private boolean connected;
// the Client object
private Client client;
// the default port number
private int defaultPort;
private String defaultHost;
// Constructor connection receiving a socket number
ClientGUI(String host, int port) {
super("Chat Client");
defaultPort = port;
defaultHost = host;
// The NorthPanel with:
JPanel northPanel = new JPanel(new GridLayout(3,1));
// the server name anmd the port number
JPanel serverAndPort = new JPanel(new GridLayout(1,5, 1, 3));
// the two JTextField with default value for server address and port number
tfServer = new JTextField(host);
tfPort = new JTextField("" + port);
tfPort.setHorizontalAlignment(SwingConstants.RIGHT);
serverAndPort.add(new JLabel("Server Address: "));
serverAndPort.add(tfServer);
serverAndPort.add(new JLabel("Port Number: "));
serverAndPort.add(tfPort);
serverAndPort.add(new JLabel(""));
// adds the Server an port field to the GUI
northPanel.add(serverAndPort);
// the Label and the TextField
label = new JLabel("Enter your username below", SwingConstants.CENTER);
northPanel.add(label);
tf = new JTextField("Anonymous");
tf.setBackground(Color.WHITE);
northPanel.add(tf);
add(northPanel, BorderLayout.NORTH);
// The CenterPanel which is the chat room
ta = new JTextArea("Welcome to the Chat room\n", 80, 80);
JPanel centerPanel = new JPanel(new GridLayout(1,1));
centerPanel.add(new JScrollPane(ta));
ta.setEditable(false);
add(centerPanel, BorderLayout.CENTER);
// the 3 buttons
login = new JButton("Login");
login.addActionListener(this);
logout = new JButton("Logout");
logout.addActionListener(this);
logout.setEnabled(false); // you have to login before being able to logout
whoIsIn = new JButton("Who is in");
whoIsIn.addActionListener(this);
whoIsIn.setEnabled(false); // you have to login before being able to Who is in
JPanel southPanel = new JPanel();
southPanel.add(login);
southPanel.add(logout);
southPanel.add(whoIsIn);
add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
tf.requestFocus();
}
// called by the Client to append text in the TextArea
void append(String str) {
ta.append(str);
ta.setCaretPosition(ta.getText().length() - 1);
}
// called by the GUI is the connection failed
// we reset our buttons, label, textfield
void connectionFailed() {
login.setEnabled(true);
logout.setEnabled(false);
whoIsIn.setEnabled(false);
label.setText("Enter your username below");
tf.setText("Anonymous");
// reset port number and host name as a construction time
tfPort.setText("" + defaultPort);
tfServer.setText(defaultHost);
// let the user change them
tfServer.setEditable(false);
tfPort.setEditable(false);
// don't react to a <CR> after the username
tf.removeActionListener(this);
connected = false;
}
/*
* Button or JTextField clicked
*/
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
// if it is the Logout button
if(o == logout) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
return;
}
// if it the who is in button
if(o == whoIsIn) {
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
return;
}
// ok it is coming from the JTextField
if(connected) {
// just have to send the message
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf.getText()));
tf.setText("");
return;
}
if(o == login) {
// ok it is a connection request
String username = tf.getText().trim();
// empty username ignore it
if(username.length() == 0)
return;
// empty serverAddress ignore it
String server = tfServer.getText().trim();
if(server.length() == 0)
return;
// empty or invalid port numer, ignore it
String portNumber = tfPort.getText().trim();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
return; // nothing I can do if port number is not valid
}
// try creating a new Client with GUI
client = new Client(server, port, username, this);
// test if we can start the Client
if(!client.start())
return;
tf.setText("");
label.setText("Enter your message below");
connected = true;
// disable login button
login.setEnabled(false);
// enable the 2 buttons
logout.setEnabled(true);
whoIsIn.setEnabled(true);
// disable the Server and Port JTextField
tfServer.setEditable(false);
tfPort.setEditable(false);
// Action listener for when the user enter a message
tf.addActionListener(this);
}
}
// to start the whole thing the server
public static void main(String[] args) {
new ClientGUI("localhost", 1500);
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.tech;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.nfc.Util;
public class FeliCa {
public static final byte[] EMPTY = {};
protected byte[] data;
protected FeliCa() {
}
protected FeliCa(byte[] bytes) {
data = (bytes == null) ? FeliCa.EMPTY : bytes;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
public final static class IDm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public IDm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes);
}
public final String getManufactureCode() {
return Util.toHexString(data, 0, 2);
}
public final String getCardIdentification() {
return Util.toHexString(data, 2, 6);
}
public boolean isEmpty() {
final byte[] d = data;
for (final byte v : d) {
if (v != 0)
return false;
}
return true;
}
}
public final static class PMm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public PMm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes);
}
public final String getIcCode() {
return Util.toHexString(data, 0, 2);
}
public final String getMaximumResponseTime() {
return Util.toHexString(data, 2, 6);
}
}
public final static class SystemCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public SystemCode(byte[] sc) {
super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc);
}
public int toInt() {
return toInt(data);
}
public static int toInt(byte[] data) {
return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1]));
}
}
public final static class ServiceCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public static final int T_UNKNOWN = 0;
public static final int T_RANDOM = 1;
public static final int T_CYCLIC = 2;
public static final int T_PURSE = 3;
public ServiceCode(byte[] sc) {
super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc);
}
public ServiceCode(int code) {
this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) });
}
public int toInt() {
return 0x0000FFFF & ((data[1] << 8) | (0x000000FF & data[0]));
}
public boolean isEncrypt() {
return (data[0] & 0x1) == 0;
}
public boolean isWritable() {
final int f = data[0] & 0x3F;
return (f & 0x2) == 0 || f == 0x13 || f == 0x12;
}
public int getAccessAttr() {
return data[0] & 0x3F;
}
public int getDataType() {
final int f = data[0] & 0x3F;
if ((f & 0x10) == 0)
return T_PURSE;
return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC;
}
}
public final static class Block extends FeliCa {
public Block() {
data = new byte[16];
}
public Block(byte[] bytes) {
super((bytes == null || bytes.length < 16) ? new byte[16] : bytes);
}
}
public final static class BlockListElement extends FeliCa {
private static final byte LENGTH_2_BYTE = (byte) 0x80;
private static final byte LENGTH_3_BYTE = (byte) 0x00;
// private static final byte ACCESSMODE_DECREMENT = (byte) 0x00;
// private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01;
private final byte lengthAndaccessMode;
private final byte serviceCodeListOrder;
public BlockListElement(byte mode, byte order, byte... blockNumber) {
if (blockNumber.length > 1) {
lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF);
} else {
lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF);
}
serviceCodeListOrder = (byte) (order & 0x0F);
data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber;
}
@Override
public byte[] getBytes() {
if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) {
ByteBuffer buff = ByteBuffer.allocate(2);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[0]);
return buff.array();
} else {
ByteBuffer buff = ByteBuffer.allocate(3);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[1]).put(data[0]);
return buff.array();
}
}
}
public final static class MemoryConfigurationBlock extends FeliCa {
public MemoryConfigurationBlock(byte[] bytes) {
super((bytes == null || bytes.length < 4) ? new byte[4] : bytes);
}
public boolean isNdefSupport() {
return (data == null) ? false : (data[3] & (byte) 0xff) == 1;
}
public void setNdefSupport(boolean ndefSupport) {
data[3] = (byte) (ndefSupport ? 1 : 0);
}
public boolean isWritable(int... addrs) {
if (data == null)
return false;
boolean result = true;
for (int a : addrs) {
byte b = (byte) ((a & 0xff) + 1);
if (a < 8) {
result &= (data[0] & b) == b;
continue;
} else if (a < 16) {
result &= (data[1] & b) == b;
continue;
} else
result &= (data[2] & b) == b;
}
return result;
}
}
public final static class Service extends FeliCa {
private final ServiceCode[] serviceCodes;
private final BlockListElement[] blockListElements;
public Service(ServiceCode[] codes, BlockListElement... blocks) {
serviceCodes = (codes == null) ? new ServiceCode[0] : codes;
blockListElements = (blocks == null) ? new BlockListElement[0]
: blocks;
}
@Override
public byte[] getBytes() {
int length = 0;
for (ServiceCode s : this.serviceCodes) {
length += s.getBytes().length;
}
for (BlockListElement b : blockListElements) {
length += b.getBytes().length;
}
ByteBuffer buff = ByteBuffer.allocate(length);
for (ServiceCode s : this.serviceCodes) {
buff.put(s.getBytes());
}
for (BlockListElement b : blockListElements) {
buff.put(b.getBytes());
}
return buff.array();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ServiceCode s : serviceCodes) {
sb.append(s.toString());
}
for (BlockListElement b : blockListElements) {
sb.append(b.toString());
}
return sb.toString();
}
}
public final static class Command extends FeliCa {
private final int length;
private final byte code;
private final IDm idm;
public Command(final byte[] bytes) {
this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length));
}
public Command(byte code, final byte... bytes) {
this.code = code;
if (bytes.length >= 8) {
idm = new IDm(Arrays.copyOfRange(bytes, 0, 8));
data = Arrays.copyOfRange(bytes, 8, bytes.length);
} else {
idm = null;
data = bytes;
}
length = bytes.length + 2;
}
public Command(byte code, IDm idm, final byte... bytes) {
this.code = code;
this.idm = idm;
this.data = bytes;
this.length = idm.getBytes().length + data.length + 2;
}
public Command(byte code, byte[] idm, final byte... bytes) {
this.code = code;
this.idm = new IDm(idm);
this.data = bytes;
this.length = idm.length + data.length + 2;
}
@Override
public byte[] getBytes() {
ByteBuffer buff = ByteBuffer.allocate(length);
byte length = (byte) this.length;
if (idm != null) {
buff.put(length).put(code).put(idm.getBytes()).put(data);
} else {
buff.put(length).put(code).put(data);
}
return buff.array();
}
}
public static class Response extends FeliCa {
protected final int length;
protected final byte code;
protected final IDm idm;
public Response(byte[] bytes) {
if (bytes != null && bytes.length >= 10) {
length = bytes[0] & 0xff;
code = bytes[1];
idm = new IDm(Arrays.copyOfRange(bytes, 2, 10));
data = bytes;
} else {
length = 0;
code = 0;
idm = new IDm(null);
data = FeliCa.EMPTY;
}
}
public IDm getIDm() {
return idm;
}
}
public final static class PollingResponse extends Response {
private final PMm pmm;
public PollingResponse(byte[] bytes) {
super(bytes);
if (size() >= 18) {
pmm = new PMm(Arrays.copyOfRange(data, 10, 18));
} else {
pmm = new PMm(null);
}
}
public PMm getPMm() {
return pmm;
}
}
public final static class ReadResponse extends Response {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(byte) 0xFF, (byte) 0xFF };
private final byte[] blockData;
public ReadResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) {
blockData = Arrays.copyOfRange(data, 13, data.length);
} else {
blockData = FeliCa.EMPTY;
}
}
public int getStatusFlag1() {
return data[10] & 0x000000FF;
}
public int getStatusFlag2() {
return data[11] & 0x000000FF;
}
public int getStatusFlag12() {
return (getStatusFlag1() << 8) | getStatusFlag2();
}
public int getBlockCount() {
return (data.length > 12) ? (0xFF & data[12]) : 0;
}
public byte[] getBlockData() {
return blockData;
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class WriteResponse extends Response {
public WriteResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
}
public int getStatusFlag1() {
return data[0] & 0x000000FF;
}
public int getStatusFlag2() {
return data[1] & 0x000000FF;
}
public int getStatusFlag12() {
return (getStatusFlag1() << 8) | getStatusFlag2();
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class Tag {
private final NfcF nfcTag;
private boolean isFeliCaLite;
private byte[] sys;
private IDm idm;
private PMm pmm;
public Tag(NfcF tag) {
nfcTag = tag;
sys = tag.getSystemCode();
idm = new IDm(tag.getTag().getId());
pmm = new PMm(tag.getManufacturer());
}
public int getSystemCode() {
return SystemCode.toInt(sys);
}
public byte[] getSystemCodeByte() {
return sys;
}
public IDm getIDm() {
return idm;
}
public PMm getPMm() {
return pmm;
}
public boolean checkFeliCaLite() throws IOException {
isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty();
return isFeliCaLite;
}
public boolean isFeliCaLite() {
return isFeliCaLite;
}
public PollingResponse polling(int systemCode) throws IOException {
Command cmd = new Command(CMD_POLLING, new byte[] {
(byte) (systemCode >> 8), (byte) (systemCode & 0xff),
(byte) 0x01, (byte) 0x00 });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final PollingResponse rsp = new PollingResponse(r);
idm = rsp.getIDm();
pmm = rsp.getPMm();
return rsp;
}
public PollingResponse polling() throws IOException {
return polling(SYS_FELICA_LITE);
}
public final SystemCode[] getSystemCodeList() throws IOException {
final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm);
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final int num;
if (r == null || r.length < 12 || r[1] != (byte) 0x0d) {
num = 0;
} else {
num = r[10] & 0x000000FF;
}
final SystemCode ret[] = new SystemCode[num];
for (int i = 0; i < num; ++i) {
ret[i] = new SystemCode(Arrays.copyOfRange(r, 11 + i * 2,
13 + i * 2));
}
return ret;
}
public ServiceCode[] getServiceCodeList() throws IOException {
ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>();
int index = 1;
while (true) {
byte[] bytes = searchServiceCode(index);
if (bytes.length != 2 && bytes.length != 4)
break;
if (bytes.length == 2) {
if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff)
break;
ret.add(new ServiceCode(bytes));
}
++index;
}
return ret.toArray(new ServiceCode[ret.size()]);
}
public byte[] searchServiceCode(int index) throws IOException {
Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] {
(byte) (index & 0xff), (byte) (index >> 8) });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final byte ret[];
if (r == null || r.length < 12 || r[1] != (byte) 0x0b)
ret = FeliCa.EMPTY;
else
ret = Arrays.copyOfRange(r, 10, r.length);
return ret;
}
public ReadResponse readWithoutEncryption(byte addr, byte... service)
throws IOException {
Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] {
(byte) 0x01, (byte) service[0], (byte) service[1],
(byte) 0x01, (byte) 0x80, addr });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final ReadResponse ret = new ReadResponse(r);
return ret;
}
public ReadResponse readWithoutEncryption(ServiceCode code, byte addr)
throws IOException {
return readWithoutEncryption(addr, code.getBytes());
}
public ReadResponse readWithoutEncryption(byte addr) throws IOException {
final byte code0 = (byte) (SRV_FELICA_LITE_READWRITE >> 8);
final byte code1 = (byte) (SRV_FELICA_LITE_READWRITE & 0xff);
return readWithoutEncryption(addr, code0, code1);
}
public WriteResponse writeWithoutEncryption(ServiceCode code,
byte addr, byte[] buff) throws IOException {
byte[] bytes = code.getBytes();
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1],
(byte) 0x01, (byte) 0x80, (byte) addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public WriteResponse writeWithoutEncryption(byte addr, byte[] buff)
throws IOException {
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01,
(byte) (SRV_FELICA_LITE_READWRITE >> 8),
(byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01,
(byte) 0x80, addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public MemoryConfigurationBlock getMemoryConfigBlock()
throws IOException {
ReadResponse r = readWithoutEncryption((byte) 0x88);
return new MemoryConfigurationBlock(r.getBlockData());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (idm != null) {
sb.append(idm.toString());
if (pmm != null)
sb.append(pmm.toString());
}
return sb.toString();
}
public void connect() throws IOException {
nfcTag.connect();
}
public void close() throws IOException {
nfcTag.close();
}
public byte[] transceive(Command cmd) throws IOException {
return transceive(cmd.getBytes());
}
public byte[] transceive(byte... cmd) throws IOException {
return nfcTag.transceive(cmd);
}
}
// polling
public static final byte CMD_POLLING = 0x00;
public static final byte RSP_POLLING = 0x01;
// request service
public static final byte CMD_REQUEST_SERVICE = 0x02;
public static final byte RSP_REQUEST_SERVICE = 0x03;
// request RESPONSE
public static final byte CMD_REQUEST_RESPONSE = 0x04;
public static final byte RSP_REQUEST_RESPONSE = 0x05;
// read without encryption
public static final byte CMD_READ_WO_ENCRYPTION = 0x06;
public static final byte RSP_READ_WO_ENCRYPTION = 0x07;
// write without encryption
public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08;
public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09;
// search service code
public static final byte CMD_SEARCH_SERVICECODE = 0x0a;
public static final byte RSP_SEARCH_SERVICECODE = 0x0b;
// request system code
public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c;
public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d;
// authentication 1
public static final byte CMD_AUTHENTICATION1 = 0x10;
public static final byte RSP_AUTHENTICATION1 = 0x11;
// authentication 2
public static final byte CMD_AUTHENTICATION2 = 0x12;
public static final byte RSP_AUTHENTICATION2 = 0x13;
// read
public static final byte CMD_READ = 0x14;
public static final byte RSP_READ = 0x15;
// write
public static final byte CMD_WRITE = 0x16;
public static final byte RSP_WRITE = 0x17;
public static final int SYS_ANY = 0xffff;
public static final int SYS_FELICA_LITE = 0x88b4;
public static final int SYS_COMMON = 0xfe00;
public static final int SRV_FELICA_LITE_READONLY = 0x0b00;
public static final int SRV_FELICA_LITE_READWRITE = 0x0900;
public static final int STA1_NORMAL = 0x00;
public static final int STA1_ERROR = 0xff;
public static final int STA2_NORMAL = 0x00;
public static final int STA2_ERROR_LENGTH = 0x01;
public static final int STA2_ERROR_FLOWN = 0x02;
public static final int STA2_ERROR_MEMORY = 0x70;
public static final int STA2_ERROR_WRITELIMIT = 0x71;
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.tech;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import com.sinpo.xnfc.nfc.Util;
import android.nfc.tech.IsoDep;
public class Iso7816 {
public static final byte[] EMPTY = { 0 };
protected byte[] data;
protected Iso7816() {
data = Iso7816.EMPTY;
}
protected Iso7816(byte[] bytes) {
data = (bytes == null) ? Iso7816.EMPTY : bytes;
}
public boolean match(byte[] bytes) {
return match(bytes, 0);
}
public boolean match(byte[] bytes, int start) {
final byte[] data = this.data;
if (data.length <= bytes.length - start) {
for (final byte v : data) {
if (v != bytes[start++])
return false;
}
} else {
return false;
}
return true;
}
public boolean match(byte tag) {
return (data.length == 1 && data[0] == tag);
}
public boolean match(short tag) {
final byte[] data = this.data;
if (data.length == 2) {
final byte d0 = (byte) (0x000000FF & (tag >> 8));
final byte d1 = (byte) (0x000000FF & tag);
return (data[0] == d0 && data[1] == d1);
}
return (tag >= 0 && tag <= 255) ? match((byte) tag) : false;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
public byte[] getBytes(int start, int count) {
return Arrays.copyOfRange(data, start, start + count);
}
public int toInt() {
return Util.toInt(getBytes());
}
public int toIntR() {
return Util.toIntR(getBytes());
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof Iso7816))
return false;
return match(((Iso7816) obj).getBytes(), 0);
}
public final static class ID extends Iso7816 {
public ID(byte... bytes) {
super(bytes);
}
}
public static class Response extends Iso7816 {
public static final byte[] EMPTY = {};
public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN
public Response(byte[] bytes) {
super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes);
}
public byte getSw1() {
return data[data.length - 2];
}
public byte getSw2() {
return data[data.length - 1];
}
public String getSw12String() {
int sw1 = getSw1() & 0x000000FF;
int sw2 = getSw2() & 0x000000FF;
return String.format("0x%02X%02X", sw1, sw2);
}
public short getSw12() {
final byte[] d = this.data;
int n = d.length;
return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1]));
}
public boolean isOkey() {
return equalsSw12(SW_NO_ERROR);
}
public boolean equalsSw12(short val) {
return getSw12() == val;
}
public int size() {
return data.length - 2;
}
public byte[] getBytes() {
return isOkey() ? Arrays.copyOfRange(data, 0, size())
: Response.EMPTY;
}
}
public final static class MifareDResponse extends Response {
public MifareDResponse(byte[] bytes) {
super(bytes);
}
}
public final static class BerT extends Iso7816 {
// tag template
public static final byte TMPL_FCP = 0x62; // File Control Parameters
public static final byte TMPL_FMD = 0x64; // File Management Data
public static final byte TMPL_FCI = 0x6F; // FCP and FMD
// proprietary information
public final static BerT CLASS_PRI = new BerT((byte) 0xA5);
// short EF identifier
public final static BerT CLASS_SFI = new BerT((byte) 0x88);
// dedicated file name
public final static BerT CLASS_DFN = new BerT((byte) 0x84);
// application data object
public final static BerT CLASS_ADO = new BerT((byte) 0x61);
// application id
public final static BerT CLASS_AID = new BerT((byte) 0x4F);
// proprietary information
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x1F) == 0x1F) {
while ((bytes[start + len] & 0x80) == 0x80)
++len;
++len;
}
return len;
}
public static BerT read(byte[] bytes, int start) {
return new BerT(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerT(byte tag) {
this(new byte[] { tag });
}
public BerT(short tag) {
this(new byte[] { (byte) (0x000000FF & (tag >> 8)),
(byte) (0x000000FF & tag) });
}
public BerT(byte[] bytes) {
super(bytes);
}
public boolean hasChild() {
return ((data[0] & 0x20) == 0x20);
}
public short toShort() {
if (size() <= 2) {
return (short) Util.toInt(data);
}
return 0;
}
}
public final static class BerL extends Iso7816 {
private final int val;
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x80) == 0x80) {
len += bytes[start] & 0x07;
}
return len;
}
public static int calc(byte[] bytes, int start) {
if ((bytes[start] & 0x80) == 0x80) {
int v = 0;
int e = start + bytes[start] & 0x07;
while (++start <= e) {
v <<= 8;
v |= bytes[start] & 0xFF;
}
return v;
}
return bytes[start];
}
public static BerL read(byte[] bytes, int start) {
return new BerL(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerL(byte[] bytes) {
super(bytes);
val = calc(bytes, 0);
}
public BerL(int len) {
super(null);
val = len;
}
public int toInt() {
return val;
}
}
public final static class BerV extends Iso7816 {
public static BerV read(byte[] bytes, int start, int len) {
return new BerV(Arrays.copyOfRange(bytes, start, start + len));
}
public BerV(byte[] bytes) {
super(bytes);
}
}
public final static class BerTLV extends Iso7816 {
public static int test(byte[] bytes, int start) {
final int lt = BerT.test(bytes, start);
final int ll = BerL.test(bytes, start + lt);
final int lv = BerL.calc(bytes, start + lt);
return lt + ll + lv;
}
public static byte[] getValue(BerTLV tlv) {
if (tlv == null || tlv.length() == 0)
return null;
return tlv.v.getBytes();
}
public static BerTLV read(Iso7816 obj) {
return read(obj.getBytes(), 0);
}
public static BerTLV read(byte[] bytes, int start) {
int s = start;
final BerT t = BerT.read(bytes, s);
s += t.size();
final BerL l = BerL.read(bytes, s);
s += l.size();
final BerV v = BerV.read(bytes, s, l.toInt());
s += v.size();
final BerTLV tlv = new BerTLV(t, l, v);
tlv.data = Arrays.copyOfRange(bytes, start, s);
return tlv;
}
public static void extractChildren(ArrayList<BerTLV> out, Iso7816 obj) {
extractChildren(out, obj.getBytes());
}
public static void extractChildren(ArrayList<BerTLV> out, byte[] data) {
int start = 0;
int end = data.length - 3;
while (start <= end) {
final BerTLV tlv = read(data, start);
out.add(tlv);
start += tlv.size();
}
}
public static void extractPrimitives(BerHouse out, Iso7816 obj) {
extractPrimitives(out.tlvs, obj.getBytes());
}
public static void extractPrimitives(ArrayList<BerTLV> out, Iso7816 obj) {
extractPrimitives(out, obj.getBytes());
}
public static void extractPrimitives(BerHouse out, byte[] data) {
extractPrimitives(out.tlvs, data);
}
public static void extractPrimitives(ArrayList<BerTLV> out, byte[] data) {
int start = 0;
int end = data.length - 3;
while (start <= end) {
final BerTLV tlv = read(data, start);
if (tlv.t.hasChild())
extractPrimitives(out, tlv.v.getBytes());
else
out.add(tlv);
start += tlv.size();
}
}
public static ArrayList<BerTLV> extractOptionList(byte[] data) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
int start = 0;
int end = data.length;
while (start < end) {
final BerT t = BerT.read(data, start);
start += t.size();
if (start < end) {
BerL l = BerL.read(data, start);
start += l.size();
if (start <= end)
ret.add(new BerTLV(t, l, null));
}
}
return ret;
}
public final BerT t;
public final BerL l;
public final BerV v;
public BerTLV(BerT t, BerL l, BerV v) {
this.t = t;
this.l = l;
this.v = v;
}
public int length() {
return l.toInt();
}
}
public final static class BerHouse {
final ArrayList<BerTLV> tlvs = new ArrayList<BerTLV>();
public int count() {
return tlvs.size();
}
public void add(short t, Response v) {
tlvs.add(new BerTLV(new BerT(t), new BerL(v.size()), new BerV(v
.getBytes())));
}
public void add(short t, byte[] v) {
tlvs.add(new BerTLV(new BerT(t), new BerL(v.length), new BerV(v)));
}
public void add(BerT t, byte[] v) {
tlvs.add(new BerTLV(t, new BerL(v.length), new BerV(v)));
}
public void add(BerTLV tlv) {
tlvs.add(tlv);
}
public BerTLV get(int index) {
return tlvs.get(index);
}
public BerTLV findFirst(byte tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(byte... tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(short tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(BerT tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag.getBytes()))
return tlv;
return null;
}
public ArrayList<BerTLV> findAll(byte tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(byte... tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(short tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(BerT tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag.getBytes()))
ret.add(tlv);
return ret;
}
public String toString() {
final StringBuilder ret = new StringBuilder();
for (BerTLV t : tlvs) {
ret.append(t.t.toString()).append(' ');
ret.append(t.l.toInt()).append(' ');
ret.append(t.v.toString()).append('\n');
}
return ret.toString();
}
}
public final static class StdTag {
private final IsoDep nfcTag;
private ID id;
public StdTag(IsoDep tag) {
nfcTag = tag;
id = new ID(tag.getTag().getId());
}
public ID getID() {
return id;
}
public Response getBalance(boolean isEP) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0x5C, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (isEP ? 2 : 1), // P2 Parameter 2
(byte) 0x04, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi, int index) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) index, // P1 Parameter 1
(byte) ((sfi << 3) | 0x04), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) 0x01, // P1 Parameter 1
(byte) ((sfi << 3) | 0x05), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readBinary(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB0, // INS Instruction
(byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1
(byte) 0x00, // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readData(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (sfi & 0x1F), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response getData(short tag) throws IOException {
final byte[] cmd = {
(byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) ((tag >> 8) & 0xFF), (byte) (tag & 0xFF),
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readData(short tag) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) ((tag >> 8) & 0xFF), // P1 Parameter 1
(byte) (tag & 0x1F), // P2 Parameter 2
(byte) 0x00, // Lc
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response selectByID(byte... id) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(id.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x00) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) id.length) // Lc
.put(id).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public Response selectByName(byte... name) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(name.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x04) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) name.length) // Lc
.put(name).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public Response getProcessingOptions(byte... pdol) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(pdol.length + 6);
buff.put((byte) 0x80) // CLA Class
.put((byte) 0xA8) // INS Instruction
.put((byte) 0x00) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) pdol.length) // Lc
.put(pdol).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public void connect() throws IOException {
nfcTag.connect();
}
public void close() throws IOException {
nfcTag.close();
}
public byte[] transceive(final byte[] cmd) throws IOException {
try {
byte[] rsp = null;
byte c[] = cmd;
do {
byte[] r = nfcTag.transceive(c);
if (r == null)
break;
int N = r.length - 2;
if (N < 0) {
rsp = r;
break;
}
if (r[N] == CH_STA_LE) {
c[c.length - 1] = r[N + 1];
continue;
}
if (rsp == null) {
rsp = r;
} else {
int n = rsp.length;
N += n;
rsp = Arrays.copyOf(rsp, N);
n -= 2;
for (byte i : r)
rsp[n++] = i;
}
if (r[N] != CH_STA_MORE)
break;
byte s = r[N + 1];
if (s != 0) {
c = CMD_GETRESPONSE.clone();
} else {
rsp[rsp.length - 1] = CH_STA_OK;
break;
}
} while (true);
return rsp;
} catch (Exception e) {
return Response.ERROR;
}
}
private static final byte CH_STA_OK = (byte) 0x90;
private static final byte CH_STA_MORE = (byte) 0x61;
private static final byte CH_STA_LE = (byte) 0x6C;
private static final byte CMD_GETRESPONSE[] = { 0, (byte) 0xC0, 0, 0,
0, };
}
public static final short SW_NO_ERROR = (short) 0x9000;
public static final short SW_DESFIRE_NO_ERROR = (short) 0x9100;
public static final short SW_BYTES_REMAINING_00 = 0x6100;
public static final short SW_WRONG_LENGTH = 0x6700;
public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982;
public static final short SW_FILE_INVALID = 0x6983;
public static final short SW_DATA_INVALID = 0x6984;
public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985;
public static final short SW_COMMAND_NOT_ALLOWED = 0x6986;
public static final short SW_APPLET_SELECT_FAILED = 0x6999;
public static final short SW_WRONG_DATA = 0x6A80;
public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81;
public static final short SW_FILE_NOT_FOUND = 0x6A82;
public static final short SW_RECORD_NOT_FOUND = 0x6A83;
public static final short SW_INCORRECT_P1P2 = 0x6A86;
public static final short SW_WRONG_P1P2 = 0x6B00;
public static final short SW_CORRECT_LENGTH_00 = 0x6C00;
public static final short SW_INS_NOT_SUPPORTED = 0x6D00;
public static final short SW_CLA_NOT_SUPPORTED = 0x6E00;
public static final short SW_UNKNOWN = 0x6F00;
public static final short SW_FILE_FULL = 0x6A84;
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc;
import static android.nfc.NfcAdapter.EXTRA_TAG;
import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.nfc.reader.ReaderListener;
import com.sinpo.xnfc.nfc.reader.ReaderManager;
public final class NfcManager {
private final Activity activity;
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private static String[][] TECHLISTS;
private static IntentFilter[] TAGFILTERS;
private int status;
static {
try {
TECHLISTS = new String[][] { { IsoDep.class.getName() },
{ NfcF.class.getName() }, };
TAGFILTERS = new IntentFilter[] { new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
} catch (Exception e) {
}
}
public NfcManager(Activity activity) {
this.activity = activity;
nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(
activity, activity.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
setupBeam(true);
status = getStatus();
}
public void onPause() {
setupOldFashionBeam(false);
if (nfcAdapter != null)
nfcAdapter.disableForegroundDispatch(activity);
}
public void onResume() {
setupOldFashionBeam(true);
if (nfcAdapter != null)
nfcAdapter.enableForegroundDispatch(activity, pendingIntent,
TAGFILTERS, TECHLISTS);
}
public boolean updateStatus() {
int sta = getStatus();
if (sta != status) {
status = sta;
return true;
}
return false;
}
public boolean readCard(Intent intent, ReaderListener listener) {
final Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG);
if (tag != null) {
ReaderManager.readCard(tag, listener);
return true;
}
return false;
}
private int getStatus() {
return (nfcAdapter == null) ? -1 : nfcAdapter.isEnabled() ? 1 : 0;
}
@SuppressLint("NewApi")
private void setupBeam(boolean enable) {
final int api = android.os.Build.VERSION.SDK_INT;
if (nfcAdapter != null && api >= ICE_CREAM_SANDWICH) {
if (enable)
nfcAdapter.setNdefPushMessage(createNdefMessage(), activity);
}
}
@SuppressWarnings("deprecation")
private void setupOldFashionBeam(boolean enable) {
final int api = android.os.Build.VERSION.SDK_INT;
if (nfcAdapter != null && api >= GINGERBREAD_MR1
&& api < ICE_CREAM_SANDWICH) {
if (enable)
nfcAdapter.enableForegroundNdefPush(activity,
createNdefMessage());
else
nfcAdapter.disableForegroundNdefPush(activity);
}
}
NdefMessage createNdefMessage() {
String uri = "3play.google.com/store/apps/details?id=com.sinpo.xnfc";
byte[] data = uri.getBytes();
// about this '3'.. see NdefRecord.createUri which need api level 14
data[0] = 3;
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_URI, null, data);
return new NdefMessage(new NdefRecord[] { record });
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc;
public final class Util {
private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private Util() {
}
public static byte[] toBytes(int a) {
return new byte[] { (byte) (0x000000ff & (a >>> 24)),
(byte) (0x000000ff & (a >>> 16)),
(byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) };
}
public static boolean testBit(byte data, int bit) {
final byte mask = (byte) ((1 << bit) & 0x000000FF);
return (data & mask) == mask;
}
public static int toInt(byte[] b, int s, int n) {
int ret = 0;
final int e = s + n;
for (int i = s; i < e; ++i) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toIntR(byte[] b, int s, int n) {
int ret = 0;
for (int i = s; (i >= 0 && n > 0); --i, --n) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toInt(byte... b) {
int ret = 0;
for (final byte a : b) {
ret <<= 8;
ret |= a & 0xFF;
}
return ret;
}
public static int toIntR(byte... b) {
return toIntR(b, b.length - 1, b.length);
}
public static String toHexString(byte... d) {
return (d == null || d.length == 0) ? "" : toHexString(d, 0, d.length);
}
public static String toHexString(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
final int e = s + n;
int x = 0;
for (int i = s; i < e; ++i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static String toHexStringR(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
int x = 0;
for (int i = s + n - 1; i >= s; --i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static String ensureString(String str) {
return str == null ? "" : str;
}
public static String toStringR(int n) {
final StringBuilder ret = new StringBuilder(16).append('0');
long N = 0xFFFFFFFFL & n;
while (N != 0) {
ret.append((int) (N % 100));
N /= 100;
}
return ret.toString();
}
public static int parseInt(String txt, int radix, int def) {
int ret;
try {
ret = Integer.valueOf(txt, radix);
} catch (Exception e) {
ret = def;
}
return ret;
}
public static int BCDtoInt(byte[] b, int s, int n) {
int ret = 0;
final int e = s + n;
for (int i = s; i < e; ++i) {
int h = (b[i] >> 4) & 0x0F;
int l = b[i] & 0x0F;
if (h > 9 || l > 9)
return -1;
ret = ret * 100 + h * 10 + l;
}
return ret;
}
public static int BCDtoInt(byte... b) {
return BCDtoInt(b, 0, b.length);
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
public class Card extends Application {
public static final Card EMPTY = new Card();
private final ArrayList<Application> applications;
public Card() {
applications = new ArrayList<Application>(2);
}
public Exception getReadingException() {
return (Exception) getProperty(SPEC.PROP.EXCEPTION);
}
public boolean hasReadingException() {
return hasProperty(SPEC.PROP.EXCEPTION);
}
public final boolean isUnknownCard() {
return applicationCount() == 0;
}
public final int applicationCount() {
return applications.size();
}
public final Application getApplication(int index) {
return applications.get(index);
}
public final void addApplication(Application app) {
if (app != null)
applications.add(app);
}
public String toHtml() {
return HtmlFormatter.formatCardInfo(this);
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import com.sinpo.xnfc.SPEC;
import android.util.SparseArray;
public class Application {
private final SparseArray<Object> properties = new SparseArray<Object>();
public final void setProperty(SPEC.PROP prop, Object value) {
properties.put(prop.ordinal(), value);
}
public final Object getProperty(SPEC.PROP prop) {
return properties.get(prop.ordinal());
}
public final boolean hasProperty(SPEC.PROP prop) {
return getProperty(prop) != null;
}
public final String getStringProperty(SPEC.PROP prop) {
final Object v = getProperty(prop);
return (v != null) ? v.toString() : "";
}
public final float getFloatProperty(SPEC.PROP prop) {
final Object v = getProperty(prop);
if (v == null)
return Float.NaN;
if (v instanceof Float)
return ((Float) v).floatValue();
return Float.parseFloat(v.toString());
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import com.sinpo.xnfc.SPEC;
public final class HtmlFormatter {
static String formatCardInfo(Card card) {
final StringBuilder ret = new StringBuilder();
startTag(ret, SPEC.TAG_BLK);
final int N = card.applicationCount();
for (int i = 0; i < N; ++i) {
if (i > 0) {
newline(ret);
newline(ret);
}
formatApplicationInfo(ret, card.getApplication(i));
}
endTag(ret, SPEC.TAG_BLK);
return ret.toString();
}
private static void startTag(StringBuilder out, String tag) {
out.append('<').append(tag).append('>');
}
private static void endTag(StringBuilder out, String tag) {
out.append('<').append('/').append(tag).append('>');
}
private static void newline(StringBuilder out) {
out.append("<br />");
}
private static void spliter(StringBuilder out) {
out.append("\n<").append(SPEC.TAG_SP).append(" />\n");
}
private static boolean formatProperty(StringBuilder out, String tag,
Object value) {
if (value == null)
return false;
startTag(out, tag);
out.append(value.toString());
endTag(out, tag);
return true;
}
private static boolean formatProperty(StringBuilder out, String tag,
Object prop, String value) {
if (value == null || value.isEmpty())
return false;
startTag(out, tag);
out.append(prop.toString());
endTag(out, tag);
startTag(out, SPEC.TAG_TEXT);
out.append(value);
endTag(out, SPEC.TAG_TEXT);
return true;
}
private static boolean formatApplicationInfo(StringBuilder out,
Application app) {
if (!formatProperty(out, SPEC.TAG_H1, app.getProperty(SPEC.PROP.ID)))
return false;
newline(out);
spliter(out);
newline(out);
{
SPEC.PROP prop = SPEC.PROP.SERIAL;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.PARAM;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.VERSION;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.DATE;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.COUNT;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.TLIMIT;
Float balance = (Float) app.getProperty(prop);
if (balance != null && !balance.isNaN()) {
String cur = app.getProperty(SPEC.PROP.CURRENCY).toString();
String val = String.format("%.2f %s", balance, cur);
if (formatProperty(out, SPEC.TAG_LAB, prop, val))
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.DLIMIT;
Float balance = (Float) app.getProperty(prop);
if (balance != null && !balance.isNaN()) {
String cur = app.getProperty(SPEC.PROP.CURRENCY).toString();
String val = String.format("%.2f %s", balance, cur);
if (formatProperty(out, SPEC.TAG_LAB, prop, val))
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.ECASH;
Float balance = (Float) app.getProperty(prop);
if (balance != null) {
formatProperty(out, SPEC.TAG_LAB, prop);
if (balance.isNaN()) {
out.append(SPEC.PROP.ACCESS);
} else {
formatProperty(out, SPEC.TAG_H2,
String.format("%.2f ", balance));
formatProperty(out, SPEC.TAG_LAB,
app.getProperty(SPEC.PROP.CURRENCY).toString());
}
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.BALANCE;
Float balance = (Float) app.getProperty(prop);
if (balance != null) {
formatProperty(out, SPEC.TAG_LAB, prop);
if (balance.isNaN()) {
out.append(SPEC.PROP.ACCESS);
} else {
formatProperty(out, SPEC.TAG_H2,
String.format("%.2f ", balance));
formatProperty(out, SPEC.TAG_LAB,
app.getProperty(SPEC.PROP.CURRENCY).toString());
}
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.TRANSLOG;
String[] logs = (String[]) app.getProperty(prop);
if (logs != null && logs.length > 0) {
spliter(out);
newline(out);
startTag(out, SPEC.TAG_PARAG);
formatProperty(out, SPEC.TAG_LAB, prop);
newline(out);
endTag(out, SPEC.TAG_PARAG);
for (String log : logs) {
formatProperty(out, SPEC.TAG_H3, log);
newline(out);
}
newline(out);
}
}
return true;
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.os.AsyncTask;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.reader.pboc.StandardPboc;
public final class ReaderManager extends AsyncTask<Tag, SPEC.EVENT, Card> {
public static void readCard(Tag tag, ReaderListener listener) {
new ReaderManager(listener).execute(tag);
}
private ReaderListener realListener;
private ReaderManager(ReaderListener listener) {
realListener = listener;
}
@Override
protected Card doInBackground(Tag... detectedTag) {
return readCard(detectedTag[0]);
}
@Override
protected void onProgressUpdate(SPEC.EVENT... events) {
if (realListener != null)
realListener.onReadEvent(events[0]);
}
@Override
protected void onPostExecute(Card card) {
if (realListener != null)
realListener.onReadEvent(SPEC.EVENT.FINISHED, card);
}
private Card readCard(Tag tag) {
final Card card = new Card();
try {
publishProgress(SPEC.EVENT.READING);
card.setProperty(SPEC.PROP.ID, Util.toHexString(tag.getId()));
final IsoDep isodep = IsoDep.get(tag);
if (isodep != null)
StandardPboc.readCard(isodep, card);
final NfcF nfcf = NfcF.get(tag);
if (nfcf != null)
FelicaReader.readCard(nfcf, card);
publishProgress(SPEC.EVENT.IDLE);
} catch (Exception e) {
card.setProperty(SPEC.PROP.EXCEPTION, e);
publishProgress(SPEC.EVENT.ERROR);
}
return card;
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import com.sinpo.xnfc.SPEC;
public interface ReaderListener {
void onReadEvent(SPEC.EVENT event, Object... obj);
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import android.nfc.tech.IsoDep;
@SuppressWarnings("unchecked")
public abstract class StandardPboc {
private static Class<?>[][] readers = {
{ BeijingMunicipal.class, WuhanTong.class, ShenzhenTong.class,
CityUnion.class, }, { Quickpass.class, } };
public static void readCard(IsoDep tech, Card card)
throws InstantiationException, IllegalAccessException, IOException {
final Iso7816.StdTag tag = new Iso7816.StdTag(tech);
tag.connect();
for (final Class<?> g[] : readers) {
HINT hint = HINT.RESETANDGONEXT;
for (final Class<?> r : g) {
final StandardPboc reader = (StandardPboc) r.newInstance();
switch (hint) {
case RESETANDGONEXT:
if (!reader.resetTag(tag))
continue;
case GONEXT:
hint = reader.readCard(tag, card);
break;
default:
break;
}
if (hint == HINT.STOP)
break;
}
}
tag.close();
}
protected boolean resetTag(Iso7816.StdTag tag) throws IOException {
return tag.selectByID(DFI_MF).isOkey()
|| tag.selectByName(DFN_PSE).isOkey();
}
protected enum HINT {
STOP, GONEXT, RESETANDGONEXT,
}
protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 };
protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 };
protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P',
(byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
(byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
(byte) '0', (byte) '1', };
protected final static byte[] DFN_PXX = { (byte) 'P' };
protected final static int SFI_EXTRA = 21;
protected static int MAX_LOG = 10;
protected static int SFI_LOG = 24;
protected final static byte TRANS_CSU = 6;
protected final static byte TRANS_CSU_CPX = 9;
protected abstract SPEC.APP getApplicationId();
protected byte[] getMainApplicationId() {
return DFI_EP;
}
protected SPEC.CUR getCurrency() {
return SPEC.CUR.CNY;
}
protected boolean selectMainApplication(Iso7816.StdTag tag)
throws IOException {
final byte[] aid = getMainApplicationId();
return ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid))
.isOkey();
}
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!selectMainApplication(tag))
return HINT.GONEXT;
Iso7816.Response INFO, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo21(app, INFO, 4, true);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
protected void parseBalance(Application app, Iso7816.Response... data) {
int amount = 0;
for (Iso7816.Response rsp : data) {
if (rsp.isOkey() && rsp.size() >= 4) {
int n = Util.toInt(rsp.getBytes(), 0, 4);
if (n > 1000000 || n < -1000000)
n -= 0x80000000;
amount += n;
}
}
app.setProperty(SPEC.PROP.BALANCE, (amount / 100.0f));
}
protected void parseInfo21(Application app, Iso7816.Response data, int dec,
boolean bigEndian) {
if (!data.isOkey() || data.size() < 30) {
return;
}
final byte[] d = data.getBytes();
if (dec < 1 || dec > 10) {
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10));
} else {
final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d,
20 - dec, dec);
app.setProperty(SPEC.PROP.SERIAL,
String.format("%d", 0xFFFFFFFFL & sn));
}
if (d[9] != 0)
app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[24], d[25], d[26], d[27]));
}
protected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) {
if (!r.isOkey())
return false;
final byte[] raw = r.getBytes();
final int N = raw.length - 23;
if (N < 0)
return false;
for (int s = 0, e = 0; s <= N; s = e) {
l.add(Arrays.copyOfRange(raw, s, (e = s + 23)));
}
return true;
}
protected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi)
throws IOException {
final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG);
final Iso7816.Response rsp = tag.readRecord(sfi);
if (rsp.isOkey()) {
addLog24(rsp, ret);
} else {
for (int i = 1; i <= MAX_LOG; ++i) {
if (!addLog24(tag.readRecord(sfi, i), ret))
break;
}
}
return ret;
}
protected void parseLog24(Application app, ArrayList<byte[]>... logs) {
final ArrayList<String> ret = new ArrayList<String>(MAX_LOG);
for (final ArrayList<byte[]> log : logs) {
if (log == null)
continue;
for (final byte[] v : log) {
final int money = Util.toInt(v, 5, 4);
if (money > 0) {
final char s = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-'
: '+';
final int over = Util.toInt(v, 2, 3);
final String slog;
if (over > 0) {
slog = String
.format("%02X%02X.%02X.%02X %02X:%02X %c%.2f [o:%.2f] [%02X%02X%02X%02X%02X%02X]",
v[16], v[17], v[18], v[19], v[20],
v[21], s, (money / 100.0f),
(over / 100.0f), v[10], v[11], v[12],
v[13], v[14], v[15]);
} else {
slog = String
.format("%02X%02X.%02X.%02X %02X:%02X %C%.2f [%02X%02X%02X%02X%02X%02X]",
v[16], v[17], v[18], v[19], v[20],
v[21], s, (money / 100.0f), v[10],
v[11], v[12], v[13], v[14], v[15]);
}
ret.add(slog);
}
}
}
if (!ret.isEmpty())
app.setProperty(SPEC.PROP.TRANSLOG,
ret.toArray(new String[ret.size()]));
}
protected Application createApplication() {
return new Application();
}
protected void configApplication(Application app) {
app.setProperty(SPEC.PROP.ID, getApplicationId());
app.setProperty(SPEC.PROP.CURRENCY, getCurrency());
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
final class WuhanTong extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.WUHANTONG;
}
@Override
protected byte[] getMainApplicationId() {
return new byte[] { (byte) 0x41, (byte) 0x50, (byte) 0x31, (byte) 0x2E,
(byte) 0x57, (byte) 0x48, (byte) 0x43, (byte) 0x54,
(byte) 0x43, };
}
@SuppressWarnings("unchecked")
@Override
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
Iso7816.Response INFO, SERL, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (5, 10)
/*--------------------------------------------------------------*/
if (!(SERL = tag.readBinary(SFI_SERL)).isOkey())
return HINT.GONEXT;
if (!(INFO = tag.readBinary(SFI_INFO)).isOkey())
return HINT.GONEXT;
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!tag.selectByName(getMainApplicationId()).isOkey())
return HINT.RESETANDGONEXT;
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
if (!BALANCE.isOkey())
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo5(app, SERL, INFO);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
private final static int SFI_INFO = 5;
private final static int SFI_SERL = 10;
private void parseInfo5(Application app, Iso7816.Response sn,
Iso7816.Response info) {
if (sn.size() < 27 || info.size() < 27) {
return;
}
final byte[] d = info.getBytes();
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(sn.getBytes(), 0, 5));
app.setProperty(SPEC.PROP.VERSION, String.format("%02d", d[24]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[16], d[17], d[18], d[19]));
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import com.sinpo.xnfc.SPEC;
final class ShenzhenTong extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.SHENZHENTONG;
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import android.annotation.SuppressLint;
final class CityUnion extends StandardPboc {
private SPEC.APP applicationId = SPEC.APP.UNKNOWN;
@Override
protected SPEC.APP getApplicationId() {
return applicationId;
}
@Override
protected byte[] getMainApplicationId() {
return new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x03, (byte) 0x86, (byte) 0x98, (byte) 0x07,
(byte) 0x01, };
}
@SuppressLint("DefaultLocale")
@Override
protected void parseInfo21(Application app, Iso7816.Response data, int dec,
boolean bigEndian) {
if (!data.isOkey() || data.size() < 30) {
return;
}
final byte[] d = data.getBytes();
if (d[2] == 0x20 && d[3] == 0x00) {
applicationId = SPEC.APP.SHANGHAIGJ;
bigEndian = true;
} else {
applicationId = SPEC.APP.CHANGANTONG;
bigEndian = false;
}
if (dec < 1 || dec > 10) {
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10));
} else {
final int sn = Util.toInt(d, 20 - dec, dec);
final String ss = bigEndian ? Util.toStringR(sn) : String.format(
"%d", 0xFFFFFFFFL & sn);
app.setProperty(SPEC.PROP.SERIAL, ss);
}
if (d[9] != 0)
app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[24], d[25], d[26], d[27]));
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import com.sinpo.xnfc.nfc.tech.Iso7816.BerHouse;
import com.sinpo.xnfc.nfc.tech.Iso7816.BerTLV;
public class Quickpass extends StandardPboc {
protected final static byte[] DFN_PPSE = { (byte) '2', (byte) 'P',
(byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
(byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
(byte) '0', (byte) '1', };
protected final static byte[] AID_DEBIT = { (byte) 0xA0, 0x00, 0x00, 0x03,
0x33, 0x01, 0x01, 0x01 };
protected final static byte[] AID_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03,
0x33, 0x01, 0x01, 0x02 };
protected final static byte[] AID_QUASI_CREDIT = { (byte) 0xA0, 0x00, 0x00,
0x03, 0x33, 0x01, 0x01, 0x03 };
public final static short MARK_LOG = (short) 0xDFFF;
protected final static short[] TAG_GLOBAL = { (short) 0x9F79 /* 电子现金余额 */,
(short) 0x9F78 /* 电子现金单笔上限 */, (short) 0x9F77 /* 电子现金余额上限 */,
(short) 0x9F13 /* 联机ATC */, (short) 0x9F36 /* ATC */,
(short) 0x9F51 /* 货币代码 */, (short) 0x9F4F /* 日志文件格式 */,
(short) 0x9F4D /* 日志文件ID */, (short) 0x5A /* 帐号 */,
(short) 0x5F24 /* 失效日期 */, (short) 0x5F25 /* 生效日期 */, };
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.QUICKPASS;
}
@Override
protected boolean resetTag(Iso7816.StdTag tag) throws IOException {
Iso7816.Response rsp = tag.selectByName(DFN_PPSE);
if (!rsp.isOkey())
return false;
BerTLV.extractPrimitives(topTLVs, rsp);
return true;
}
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
final ArrayList<Iso7816.ID> aids = getApplicationIds(tag);
for (Iso7816.ID aid : aids) {
/*--------------------------------------------------------------*/
// select application
/*--------------------------------------------------------------*/
Iso7816.Response rsp = tag.selectByName(aid.getBytes());
if (!rsp.isOkey())
continue;
final BerHouse subTLVs = new BerHouse();
/*--------------------------------------------------------------*/
// collect info
/*--------------------------------------------------------------*/
BerTLV.extractPrimitives(subTLVs, rsp);
collectTLVFromGlobalTags(tag, subTLVs);
/*--------------------------------------------------------------*/
// parse PDOL and get processing options
// 这是正规途径,但是每次GPO都会使ATC加1,达到65535卡片就锁定了
/*--------------------------------------------------------------*/
// rsp = tag.getProcessingOptions(buildPDOL(subTLVs));
// if (rsp.isOkey())
// BerTLV.extractPrimitives(subTLVs, rsp);
/*--------------------------------------------------------------*/
// 遍历目录下31个文件,山寨途径,微暴力,不知会对卡片折寿多少
// 相对于GPO不停的增加ATC,这是一种折中
// (遍历过程一般不会超过15个文件就会结束)
/*--------------------------------------------------------------*/
collectTLVFromRecords(tag, subTLVs);
// String dump = subTLVs.toString();
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseInfo(app, subTLVs);
parseLogs(app, subTLVs);
card.addApplication(app);
}
return card.isUnknownCard() ? HINT.RESETANDGONEXT : HINT.STOP;
}
private static void parseInfo(Application app, BerHouse tlvs) {
Object prop = parseString(tlvs, (short) 0x5A);
if (prop != null)
app.setProperty(SPEC.PROP.SERIAL, prop);
prop = parseApplicationName(tlvs, (String) prop);
if (prop != null)
app.setProperty(SPEC.PROP.ID, prop);
prop = parseInteger(tlvs, (short) 0x9F08);
if (prop != null)
app.setProperty(SPEC.PROP.VERSION, prop);
prop = parseInteger(tlvs, (short) 0x9F36);
if (prop != null)
app.setProperty(SPEC.PROP.COUNT, prop);
prop = parseValidity(tlvs, (short) 0x5F25, (short) 0x5F24);
if (prop != null)
app.setProperty(SPEC.PROP.DATE, prop);
prop = parseCurrency(tlvs, (short) 0x9F51);
if (prop != null)
app.setProperty(SPEC.PROP.CURRENCY, prop);
prop = parseAmount(tlvs, (short) 0x9F77);
if (prop != null)
app.setProperty(SPEC.PROP.DLIMIT, prop);
prop = parseAmount(tlvs, (short) 0x9F78);
if (prop != null)
app.setProperty(SPEC.PROP.TLIMIT, prop);
prop = parseAmount(tlvs, (short) 0x9F79);
if (prop != null)
app.setProperty(SPEC.PROP.ECASH, prop);
}
private ArrayList<Iso7816.ID> getApplicationIds(Iso7816.StdTag tag)
throws IOException {
final ArrayList<Iso7816.ID> ret = new ArrayList<Iso7816.ID>();
// try to read DDF
BerTLV sfi = topTLVs.findFirst(Iso7816.BerT.CLASS_SFI);
if (sfi != null && sfi.length() == 1) {
final int SFI = sfi.v.toInt();
Iso7816.Response r = tag.readRecord(SFI, 1);
for (int p = 2; r.isOkey(); ++p) {
BerTLV.extractPrimitives(topTLVs, r);
r = tag.readRecord(SFI, p);
}
}
// add extracted
ArrayList<BerTLV> aids = topTLVs.findAll(Iso7816.BerT.CLASS_AID);
if (aids != null) {
for (BerTLV aid : aids)
ret.add(new Iso7816.ID(aid.v.getBytes()));
}
// use default list
if (ret.isEmpty()) {
ret.add(new Iso7816.ID(AID_DEBIT));
ret.add(new Iso7816.ID(AID_CREDIT));
ret.add(new Iso7816.ID(AID_QUASI_CREDIT));
}
return ret;
}
/**
* private static void buildPDO(ByteBuffer out, int len, byte... val) {
* final int n = Math.min((val != null) ? val.length : 0, len);
*
* int i = 0; while (i < n) out.put(val[i++]);
*
* while (i++ < len) out.put((byte) 0); }
*
* private static byte[] buildPDOL(Iso7816.BerHouse tlvs) {
*
* final ByteBuffer buff = ByteBuffer.allocate(64);
*
* buff.put((byte) 0x83).put((byte) 0x00);
*
* try { final byte[] pdol = tlvs.findFirst((short) 0x9F38).v.getBytes();
*
* ArrayList<BerTLV> list = BerTLV.extractOptionList(pdol); for
* (Iso7816.BerTLV tlv : list) { final int tag = tlv.t.toInt(); final int
* len = tlv.l.toInt();
*
* switch (tag) { case 0x9F66: // 终端交易属性 buildPDO(buff, len, (byte) 0x48);
* break; case 0x9F02: // 授权金额 buildPDO(buff, len); break; case 0x9F03: //
* 其它金额 buildPDO(buff, len); break; case 0x9F1A: // 终端国家代码 buildPDO(buff,
* len, (byte) 0x01, (byte) 0x56); break; case 0x9F37: // 不可预知数
* buildPDO(buff, len); break; case 0x5F2A: // 交易货币代码 buildPDO(buff, len,
* (byte) 0x01, (byte) 0x56); break; case 0x95: // 终端验证结果 buildPDO(buff,
* len); break; case 0x9A: // 交易日期 buildPDO(buff, len); break; case 0x9C: //
* 交易类型 buildPDO(buff, len); break; default: throw null; } } // 更新数据长度
* buff.put(1, (byte) (buff.position() - 2)); } catch (Exception e) {
* buff.position(2); }
*
* return Arrays.copyOfRange(buff.array(), 0, buff.position()); }
*/
private static void collectTLVFromGlobalTags(Iso7816.StdTag tag,
BerHouse tlvs) throws IOException {
for (short t : TAG_GLOBAL) {
Iso7816.Response r = tag.getData(t);
if (r.isOkey())
tlvs.add(BerTLV.read(r));
}
}
private static void collectTLVFromRecords(Iso7816.StdTag tag, BerHouse tlvs)
throws IOException {
// info files
for (int sfi = 1; sfi <= 10; ++sfi) {
Iso7816.Response r = tag.readRecord(sfi, 1);
for (int idx = 2; r.isOkey() && idx <= 10; ++idx) {
BerTLV.extractPrimitives(tlvs, r);
r = tag.readRecord(sfi, idx);
}
}
// check if already get sfi of log file
BerTLV logEntry = tlvs.findFirst((short) 0x9F4D);
final int S, E;
if (logEntry != null && logEntry.length() == 2) {
S = E = logEntry.v.getBytes()[0] & 0x000000FF;
} else {
S = 11;
E = 31;
}
// log files
for (int sfi = S; sfi <= E; ++sfi) {
Iso7816.Response r = tag.readRecord(sfi, 1);
boolean findOne = r.isOkey();
for (int idx = 2; r.isOkey() && idx <= 10; ++idx) {
tlvs.add(MARK_LOG, r);
r = tag.readRecord(sfi, idx);
}
if (findOne)
break;
}
}
private static SPEC.APP parseApplicationName(BerHouse tlvs, String serial) {
String f = parseString(tlvs, (short) 0x84);
if (f != null) {
if (f.endsWith("010101"))
return SPEC.APP.DEBIT;
if (f.endsWith("010102"))
return SPEC.APP.CREDIT;
if (f.endsWith("010103"))
return SPEC.APP.QCREDIT;
}
return SPEC.APP.UNKNOWN;
}
private static SPEC.CUR parseCurrency(BerHouse tlvs, short tag) {
return SPEC.CUR.CNY;
}
private static String parseValidity(BerHouse tlvs, short from, short to) {
final byte[] f = BerTLV.getValue(tlvs.findFirst(from));
final byte[] t = BerTLV.getValue(tlvs.findFirst(to));
if (t == null || t.length != 3 || t[0] == 0 || t[0] == (byte) 0xFF)
return null;
if (f == null || f.length != 3 || f[0] == 0 || f[0] == (byte) 0xFF)
return String.format("? - 20%02x.%02x.%02x", t[0], t[1], t[2]);
return String.format("20%02x.%02x.%02x - 20%02x.%02x.%02x", f[0], f[1],
f[2], t[0], t[1], t[2]);
}
private static String parseString(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.toHexString(v) : null;
}
private static Float parseAmount(BerHouse tlvs, short tag) {
Integer v = parseIntegerBCD(tlvs, tag);
return (v != null) ? v / 100.0f : null;
}
private static Integer parseInteger(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.toInt(v) : null;
}
private static Integer parseIntegerBCD(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.BCDtoInt(v) : null;
}
private static void parseLogs(Application app, BerHouse tlvs) {
final byte[] rawTemp = BerTLV.getValue(tlvs.findFirst((short) 0x9F4F));
if (rawTemp == null)
return;
final ArrayList<BerTLV> temp = BerTLV.extractOptionList(rawTemp);
if (temp == null || temp.isEmpty())
return;
final ArrayList<BerTLV> logs = tlvs.findAll(MARK_LOG);
final ArrayList<String> ret = new ArrayList<String>(logs.size());
for (BerTLV log : logs) {
String l = parseLog(temp, log.v.getBytes());
if (l != null)
ret.add(l);
}
if (!ret.isEmpty())
app.setProperty(SPEC.PROP.TRANSLOG,
ret.toArray(new String[ret.size()]));
}
private static String parseLog(ArrayList<BerTLV> temp, byte[] data) {
try {
int date = -1, time = -1;
int amount = 0, type = -1;
int cursor = 0;
for (BerTLV f : temp) {
final int n = f.length();
switch (f.t.toInt()) {
case 0x9A: // 交易日期
date = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F21: // 交易时间
time = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F02: // 授权金额
amount = Util.BCDtoInt(data, cursor, n);
break;
case 0x9C: // 交易类型
type = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F03: // 其它金额
case 0x9F1A: // 终端国家代码
case 0x5F2A: // 交易货币代码
case 0x9F4E: // 商户名称
case 0x9F36: // 应用交易计数器(ATC)
default:
break;
}
cursor += n;
}
if (amount <= 0)
return null;
final char sign;
switch (type) {
case 0: // 刷卡消费
case 1: // 取现
case 8: // 转账
case 9: // 支付
case 20: // 退款
case 40: // 持卡人账户转账
sign = '-';
break;
default:
sign = '+';
break;
}
String sd = (date <= 0) ? "****.**.**" : String.format(
"20%02d.%02d.%02d", (date / 10000) % 100,
(date / 100) % 100, date % 100);
String st = (time <= 0) ? "**:**" : String.format("%02d:%02d",
(time / 10000) % 100, (time / 100) % 100);
final StringBuilder ret = new StringBuilder();
ret.append(String.format("%s %s %c%.2f", sd, st, sign,
amount / 100f));
return ret.toString();
} catch (Exception e) {
return null;
}
}
private final BerHouse topTLVs = new BerHouse();
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
final class BeijingMunicipal extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.BEIJINGMUNICIPAL;
}
@SuppressWarnings("unchecked")
@Override
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
Iso7816.Response INFO, CNT, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (4)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA_LOG);
if (!INFO.isOkey())
return HINT.GONEXT;
/*--------------------------------------------------------------*/
// read card operation file, binary (5)
/*--------------------------------------------------------------*/
CNT = tag.readBinary(SFI_EXTRA_CNT);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!tag.selectByID(DFI_EP).isOkey())
return HINT.RESETANDGONEXT;
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo4(app, INFO, CNT);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
private final static int SFI_EXTRA_LOG = 4;
private final static int SFI_EXTRA_CNT = 5;
private void parseInfo4(Application app, Iso7816.Response info,
Iso7816.Response cnt) {
if (!info.isOkey() || info.size() < 32) {
return;
}
final byte[] d = info.getBytes();
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 0, 8));
app.setProperty(SPEC.PROP.VERSION,
String.format("%02X.%02X%02X", d[8], d[9], d[10]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24], d[25], d[26],
d[27], d[28], d[29], d[30], d[31]));
if (cnt != null && cnt.isOkey() && cnt.size() > 4) {
byte[] e = cnt.getBytes();
final int n = Util.toInt(e, 1, 4);
if (e[0] == 0)
app.setProperty(SPEC.PROP.COUNT, String.format("%d", n));
else
app.setProperty(SPEC.PROP.COUNT, String.format("%d*", n));
}
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import java.io.IOException;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.FeliCa;
import android.nfc.tech.NfcF;
final class FelicaReader {
static void readCard(NfcF tech, Card card) throws IOException {
final FeliCa.Tag tag = new FeliCa.Tag(tech);
tag.connect();
/*
*
FeliCa.SystemCode systems[] = tag.getSystemCodeList();
if (systems.length == 0) {
systems = new FeliCa.SystemCode[] { new FeliCa.SystemCode(
tag.getSystemCodeByte()) };
}
for (final FeliCa.SystemCode sys : systems)
card.addApplication(readApplication(tag, sys.toInt()));
*/
// better old card compatibility
card.addApplication(readApplication(tag, SYS_OCTOPUS));
try {
card.addApplication(readApplication(tag, SYS_SZT));
} catch (IOException e) {
// for early version of OCTOPUS which will throw shit
}
tag.close();
}
private static final int SYS_SZT = 0x8005;
private static final int SYS_OCTOPUS = 0x8008;
private static final int SRV_SZT = 0x0118;
private static final int SRV_OCTOPUS = 0x0117;
private static Application readApplication(FeliCa.Tag tag, int system)
throws IOException {
final FeliCa.ServiceCode scode;
final Application app;
if (system == SYS_OCTOPUS) {
app = new Application();
app.setProperty(SPEC.PROP.ID, SPEC.APP.OCTOPUS);
app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.HKD);
scode = new FeliCa.ServiceCode(SRV_OCTOPUS);
} else if (system == SYS_SZT) {
app = new Application();
app.setProperty(SPEC.PROP.ID, SPEC.APP.SHENZHENTONG);
app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.CNY);
scode = new FeliCa.ServiceCode(SRV_SZT);
} else {
return null;
}
app.setProperty(SPEC.PROP.SERIAL, tag.getIDm().toString());
app.setProperty(SPEC.PROP.PARAM, tag.getPMm().toString());
tag.polling(system);
final float[] data = new float[] { 0, 0, 0 };
int p = 0;
for (byte i = 0; p < data.length; ++i) {
final FeliCa.ReadResponse r = tag.readWithoutEncryption(scode, i);
if (!r.isOkey())
break;
data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f;
}
if (p != 0)
app.setProperty(SPEC.PROP.BALANCE, parseBalance(data));
else
app.setProperty(SPEC.PROP.BALANCE, Float.NaN);
return app;
}
private static float parseBalance(float[] value) {
float balance = 0f;
for (float v : value)
balance += v;
return balance;
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import java.lang.Thread.UncaughtExceptionHandler;
import com.sinpo.xnfc.R;
import android.app.Application;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.widget.Toast;
public final class ThisApplication extends Application implements
UncaughtExceptionHandler {
private static ThisApplication instance;
@Override
public void uncaughtException(Thread thread, Throwable ex) {
System.exit(0);
}
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(this);
instance = this;
}
public static String name() {
return getStringResource(R.string.app_name);
}
public static String version() {
try {
return instance.getPackageManager().getPackageInfo(
instance.getPackageName(), 0).versionName;
} catch (Exception e) {
return "1.0";
}
}
public static void showMessage(int fmt, CharSequence... msgs) {
String msg = String.format(getStringResource(fmt), msgs);
Toast.makeText(instance, msg, Toast.LENGTH_LONG).show();
}
public static Typeface getFontResource(int pathId) {
String path = getStringResource(pathId);
return Typeface.createFromAsset(instance.getAssets(), path);
}
public static int getDimensionResourcePixelSize(int resId) {
return instance.getResources().getDimensionPixelSize(resId);
}
public static int getColorResource(int resId) {
return instance.getResources().getColor(resId);
}
public static String getStringResource(int resId) {
return instance.getString(resId);
}
public static Drawable getDrawableResource(int resId) {
return instance.getResources().getDrawable(resId);
}
public static DisplayMetrics getDisplayMetrics() {
return instance.getResources().getDisplayMetrics();
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.app.Activity;
import android.content.Intent;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class AboutPage {
private static final String TAG = "ABOUTPAGE_ACTION";
public static CharSequence getContent(Activity activity) {
String tip = ThisApplication
.getStringResource(R.string.info_main_about);
tip = tip.replace("<app />", ThisApplication.name());
tip = tip.replace("<version />", ThisApplication.version());
return new SpanFormatter(null).toSpanned(tip);
}
public static boolean isSendByMe(Intent intent) {
return intent != null && TAG.equals(intent.getAction());
}
static SpanFormatter.ActionHandler getActionHandler(Activity activity) {
return new Handler(activity);
}
private static final class Handler implements SpanFormatter.ActionHandler {
private final Activity activity;
Handler(Activity activity) {
this.activity = activity;
}
@Override
public void handleAction(CharSequence name) {
activity.setIntent(new Intent(TAG));
}
}
private AboutPage() {
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.animation.LayoutTransition;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.ClipboardManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class Toolbar {
final ViewGroup toolbar;
@SuppressLint("NewApi")
public Toolbar(ViewGroup toolbar) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
toolbar.setLayoutTransition(new LayoutTransition());
this.toolbar = toolbar;
}
public void copyPageContent(TextView textArea) {
final CharSequence text = textArea.getText();
if (text != null) {
((ClipboardManager) textArea.getContext().getSystemService(
Context.CLIPBOARD_SERVICE)).setText(text);
ThisApplication.showMessage(R.string.info_main_copied);
}
}
public void show(int... buttons) {
hide();
showDelayed(1000, buttons);
}
private void hide() {
final int n = toolbar.getChildCount();
for (int i = 0; i < n; ++i)
toolbar.getChildAt(i).setVisibility(View.GONE);
}
private void showDelayed(int delay, int... buttons) {
toolbar.postDelayed(new Helper(buttons), delay);
}
private final class Helper implements Runnable {
private final int[] buttons;
Helper(int... buttons) {
this.buttons = buttons;
}
@Override
public void run() {
final int n = toolbar.getChildCount();
for (int i = 0; i < n; ++i) {
final View view = toolbar.getChildAt(i);
int visibility = View.GONE;
if (buttons != null) {
final int id = view.getId();
for (int btn : buttons) {
if (btn == id) {
visibility = View.VISIBLE;
break;
}
}
}
view.setVisibility(visibility);
}
}
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import java.lang.ref.WeakReference;
import org.xml.sax.XMLReader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.LineHeightSpan;
import android.text.style.MetricAffectingSpan;
import android.text.style.ReplacementSpan;
import android.util.DisplayMetrics;
import android.view.View;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.ThisApplication;
public final class SpanFormatter implements Html.TagHandler {
public interface ActionHandler {
void handleAction(CharSequence name);
}
private final ActionHandler handler;
public SpanFormatter(ActionHandler handler) {
this.handler = handler;
}
public CharSequence toSpanned(String html) {
return Html.fromHtml(html, null, this);
}
private static final class ActionSpan extends ClickableSpan {
private final String action;
private final ActionHandler handler;
private final int color;
ActionSpan(String action, ActionHandler handler, int color) {
this.action = action;
this.handler = handler;
this.color = color;
}
@Override
public void onClick(View widget) {
if (handler != null)
handler.handleAction(action);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(color);
}
}
private static final class FontSpan extends MetricAffectingSpan {
final int color;
final float size;
final Typeface face;
final boolean bold;
FontSpan(int color, float size, Typeface face) {
this.color = color;
this.size = size;
if (face == Typeface.DEFAULT) {
this.face = null;
this.bold = false;
} else if (face == Typeface.DEFAULT_BOLD) {
this.face = null;
this.bold = true;
} else {
this.face = face;
this.bold = false;
}
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setTextSize(size);
ds.setColor(color);
if (face != null) {
ds.setTypeface(face);
} else if (bold) {
Typeface tf = ds.getTypeface();
if (tf != null) {
int style = tf.getStyle() | Typeface.BOLD;
tf = Typeface.create(tf, style);
ds.setTypeface(tf);
style &= ~tf.getStyle();
if ((style & Typeface.BOLD) != 0) {
ds.setFakeBoldText(true);
}
}
}
}
@Override
public void updateMeasureState(TextPaint p) {
updateDrawState(p);
}
}
private static final class ParagSpan implements LineHeightSpan {
private final int linespaceDelta;
ParagSpan(int linespaceDelta) {
this.linespaceDelta = linespaceDelta;
}
@Override
public void chooseHeight(CharSequence text, int start, int end,
int spanstartv, int v, FontMetricsInt fm) {
fm.bottom += linespaceDelta;
fm.descent += linespaceDelta;
}
}
private static final class SplitterSpan extends ReplacementSpan {
private final int color;
private final int width;
private final int height;
SplitterSpan(int color, int width, int height) {
this.color = color;
this.width = width;
this.height = height;
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setTextSize(1);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
Paint.FontMetricsInt fm) {
return 0;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end,
float x, int top, int y, int bottom, Paint paint) {
canvas.save();
canvas.translate(x, (bottom + top) / 2 - height);
final int c = paint.getColor();
paint.setColor(color);
canvas.drawRect(x, 0, x + width, height, paint);
paint.setColor(c);
canvas.restore();
}
}
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
final int len = output.length();
if (opening) {
if (SPEC.TAG_TEXT.equals(tag)) {
markFontSpan(output, len, R.color.tag_text, R.dimen.tag_text,
Typeface.DEFAULT);
} else if (SPEC.TAG_TIP.equals(tag)) {
markParagSpan(output, len, R.dimen.tag_parag);
markFontSpan(output, len, R.color.tag_tip, R.dimen.tag_tip,
getTipFont());
} else if (SPEC.TAG_LAB.equals(tag)) {
markFontSpan(output, len, R.color.tag_lab, R.dimen.tag_lab,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_ITEM.equals(tag)) {
markFontSpan(output, len, R.color.tag_item, R.dimen.tag_item,
Typeface.DEFAULT);
} else if (SPEC.TAG_H1.equals(tag)) {
markFontSpan(output, len, R.color.tag_h1, R.dimen.tag_h1,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_H2.equals(tag)) {
markFontSpan(output, len, R.color.tag_h2, R.dimen.tag_h2,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_H3.equals(tag)) {
markFontSpan(output, len, R.color.tag_h3, R.dimen.tag_h3,
Typeface.SERIF);
} else if (tag.startsWith(SPEC.TAG_ACT)) {
markActionSpan(output, len, tag, R.color.tag_action);
} else if (SPEC.TAG_PARAG.equals(tag)) {
markParagSpan(output, len, R.dimen.tag_parag);
} else if (SPEC.TAG_SP.equals(tag)) {
markSpliterSpan(output, len, R.color.tag_action,
R.dimen.tag_spliter);
}
} else {
if (SPEC.TAG_TEXT.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_TIP.equals(tag)) {
setSpan(output, len, FontSpan.class);
setSpan(output, len, ParagSpan.class);
} else if (SPEC.TAG_LAB.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_ITEM.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H1.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H2.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H3.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (tag.startsWith(SPEC.TAG_ACT)) {
setSpan(output, len, ActionSpan.class);
} else if (SPEC.TAG_PARAG.equals(tag)) {
setSpan(output, len, ParagSpan.class);
}
}
}
private static void markSpliterSpan(Editable out, int pos, int colorId,
int heightId) {
DisplayMetrics dm = ThisApplication.getDisplayMetrics();
int color = ThisApplication.getColorResource(colorId);
int height = ThisApplication.getDimensionResourcePixelSize(heightId);
out.append("-------------------").setSpan(
new SplitterSpan(color, dm.widthPixels, height), pos,
out.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static void markFontSpan(Editable out, int pos, int colorId,
int sizeId, Typeface face) {
int color = ThisApplication.getColorResource(colorId);
float size = ThisApplication.getDimensionResourcePixelSize(sizeId);
FontSpan span = new FontSpan(color, size, face);
out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK);
}
private static void markParagSpan(Editable out, int pos, int linespaceId) {
int linespace = ThisApplication
.getDimensionResourcePixelSize(linespaceId);
ParagSpan span = new ParagSpan(linespace);
out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK);
}
private void markActionSpan(Editable out, int pos, String tag, int colorId) {
int color = ThisApplication.getColorResource(colorId);
out.setSpan(new ActionSpan(tag, handler, color), pos, pos,
Spannable.SPAN_MARK_MARK);
}
private static void setSpan(Editable out, int pos, Class<?> kind) {
Object span = getLastMarkSpan(out, kind);
out.setSpan(span, out.getSpanStart(span), pos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static Object getLastMarkSpan(Spanned text, Class<?> kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
return objs[objs.length - 1];
}
}
private static Typeface getTipFont() {
Typeface ret = null;
WeakReference<Typeface> wr = TIPFONT;
if (wr != null)
ret = wr.get();
if (ret == null) {
ret = ThisApplication.getFontResource(R.string.font_oem3);
TIPFONT = new WeakReference<Typeface>(ret);
}
return ret;
}
private static WeakReference<Typeface> TIPFONT;
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
import com.sinpo.xnfc.SPEC.EVENT;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.reader.ReaderListener;
public final class NfcPage implements ReaderListener {
private static final String TAG = "READCARD_ACTION";
private static final String RET = "READCARD_RESULT";
private static final String STA = "READCARD_STATUS";
private final Activity activity;
public NfcPage(Activity activity) {
this.activity = activity;
}
public static boolean isSendByMe(Intent intent) {
return intent != null && TAG.equals(intent.getAction());
}
public static boolean isNormalInfo(Intent intent) {
return intent != null && intent.hasExtra(STA);
}
public static CharSequence getContent(Activity activity, Intent intent) {
String info = intent.getStringExtra(RET);
if (info == null || info.length() == 0)
return null;
return new SpanFormatter(AboutPage.getActionHandler(activity))
.toSpanned(info);
}
@Override
public void onReadEvent(EVENT event, Object... objs) {
if (event == EVENT.IDLE) {
showProgressBar();
} else if (event == EVENT.FINISHED) {
hideProgressBar();
final Card card;
if (objs != null && objs.length > 0)
card = (Card) objs[0];
else
card = null;
activity.setIntent(buildResult(card));
}
}
private Intent buildResult(Card card) {
final Intent ret = new Intent(TAG);
if (card != null && !card.hasReadingException()) {
if (card.isUnknownCard()) {
ret.putExtra(RET, ThisApplication
.getStringResource(R.string.info_nfc_unknown));
} else {
ret.putExtra(RET, card.toHtml());
ret.putExtra(STA, 1);
}
} else {
ret.putExtra(RET,
ThisApplication.getStringResource(R.string.info_nfc_error));
}
return ret;
}
private void showProgressBar() {
Dialog d = progressBar;
if (d == null) {
d = new Dialog(activity, R.style.progressBar);
d.setCancelable(false);
d.setContentView(R.layout.progress);
progressBar = d;
}
if (!d.isShowing())
d.show();
}
private void hideProgressBar() {
final Dialog d = progressBar;
if (d != null && d.isShowing())
d.cancel();
}
private Dialog progressBar;
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import static android.provider.Settings.ACTION_SETTINGS;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class MainPage {
public static CharSequence getContent(Activity activity) {
final NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity);
final int resid;
if (nfc == null)
resid = R.string.info_nfc_notsupport;
else if (!nfc.isEnabled())
resid = R.string.info_nfc_disabled;
else
resid = R.string.info_nfc_nocard;
String tip = ThisApplication.getStringResource(resid);
return new SpanFormatter(new Handler(activity)).toSpanned(tip);
}
private static final class Handler implements SpanFormatter.ActionHandler {
private final Activity activity;
Handler(Activity activity) {
this.activity = activity;
}
@Override
public void handleAction(CharSequence name) {
startNfcSettingsActivity();
}
private void startNfcSettingsActivity() {
activity.startActivityForResult(new Intent(ACTION_SETTINGS), 0);
}
}
private MainPage() {
}
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import com.sinpo.xnfc.R;
public final class SPEC {
public enum PAGE {
DEFAULT, INFO, ABOUT,
}
public enum EVENT {
IDLE, ERROR, READING, FINISHED,
}
public enum PROP {
ID(R.string.spec_prop_id),
SERIAL(R.string.spec_prop_serial),
PARAM(R.string.spec_prop_param),
VERSION(R.string.spec_prop_version),
DATE(R.string.spec_prop_date),
COUNT(R.string.spec_prop_count),
CURRENCY(R.string.spec_prop_currency),
TLIMIT(R.string.spec_prop_tlimit),
DLIMIT(R.string.spec_prop_dlimit),
ECASH(R.string.spec_prop_ecash),
BALANCE(R.string.spec_prop_balance),
TRANSLOG(R.string.spec_prop_translog),
ACCESS(R.string.spec_prop_access),
EXCEPTION(R.string.spec_prop_exception);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private PROP(int resId) {
this.resId = resId;
}
}
public enum APP {
UNKNOWN(R.string.spec_app_unknown),
SHENZHENTONG(R.string.spec_app_shenzhentong),
QUICKPASS(R.string.spec_app_quickpass),
OCTOPUS(R.string.spec_app_octopus_hk),
BEIJINGMUNICIPAL(R.string.spec_app_beijing),
WUHANTONG(R.string.spec_app_wuhantong),
CHANGANTONG(R.string.spec_app_changantong),
SHANGHAIGJ(R.string.spec_app_shanghai),
DEBIT(R.string.spec_app_debit),
CREDIT(R.string.spec_app_credit),
QCREDIT(R.string.spec_app_qcredit);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private APP(int resId) {
this.resId = resId;
}
}
public enum CUR {
UNKNOWN(R.string.spec_cur_unknown),
USD(R.string.spec_cur_usd),
CNY(R.string.spec_cur_cny),
HKD(R.string.spec_cur_hkd);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private CUR(int resId) {
this.resId = resId;
}
}
public static final String TAG_BLK = "div";
public static final String TAG_TIP = "t_tip";
public static final String TAG_ACT = "t_action";
public static final String TAG_EM = "t_em";
public static final String TAG_H1 = "t_head1";
public static final String TAG_H2 = "t_head2";
public static final String TAG_H3 = "t_head3";
public static final String TAG_SP = "t_splitter";
public static final String TAG_TEXT = "t_text";
public static final String TAG_ITEM = "t_item";
public static final String TAG_LAB = "t_label";
public static final String TAG_PARAG = "t_parag";
}
|
Java
|
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.nfc.NfcManager;
import com.sinpo.xnfc.ui.AboutPage;
import com.sinpo.xnfc.ui.MainPage;
import com.sinpo.xnfc.ui.NfcPage;
import com.sinpo.xnfc.ui.Toolbar;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
nfc = new NfcManager(this);
onNewIntent(getIntent());
}
@Override
public void onBackPressed() {
if (isCurrentPage(SPEC.PAGE.ABOUT))
loadDefaultPage();
else if (safeExit)
super.onBackPressed();
}
@Override
public void setIntent(Intent intent) {
if (NfcPage.isSendByMe(intent))
loadNfcPage(intent);
else if (AboutPage.isSendByMe(intent))
loadAboutPage();
else
super.setIntent(intent);
}
@Override
protected void onPause() {
super.onPause();
nfc.onPause();
}
@Override
protected void onResume() {
super.onResume();
nfc.onResume();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
if (nfc.updateStatus())
loadDefaultPage();
// 有些ROM将关闭系统状态下拉面板的BACK事件发给最顶层窗口
// 这里加入一个延迟避免意外退出
board.postDelayed(new Runnable() {
public void run() {
safeExit = true;
}
}, 800);
} else {
safeExit = false;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
loadDefaultPage();
}
@Override
protected void onNewIntent(Intent intent) {
if (!nfc.readCard(intent, new NfcPage(this)))
loadDefaultPage();
}
public void onSwitch2DefaultPage(View view) {
if (!isCurrentPage(SPEC.PAGE.DEFAULT))
loadDefaultPage();
}
public void onSwitch2AboutPage(View view) {
if (!isCurrentPage(SPEC.PAGE.ABOUT))
loadAboutPage();
}
public void onCopyPageContent(View view) {
toolbar.copyPageContent(getFrontPage());
}
private void loadDefaultPage() {
toolbar.show(null);
TextView ta = getBackPage();
resetTextArea(ta, SPEC.PAGE.DEFAULT, Gravity.CENTER);
ta.setText(MainPage.getContent(this));
board.showNext();
}
private void loadAboutPage() {
toolbar.show(R.id.btnBack);
TextView ta = getBackPage();
resetTextArea(ta, SPEC.PAGE.ABOUT, Gravity.LEFT);
ta.setText(AboutPage.getContent(this));
board.showNext();
}
private void loadNfcPage(Intent intent) {
final CharSequence info = NfcPage.getContent(this, intent);
TextView ta = getBackPage();
if (NfcPage.isNormalInfo(intent)) {
toolbar.show(R.id.btnCopy, R.id.btnReset);
resetTextArea(ta, SPEC.PAGE.INFO, Gravity.LEFT);
} else {
toolbar.show(R.id.btnBack);
resetTextArea(ta, SPEC.PAGE.INFO, Gravity.CENTER);
}
ta.setText(info);
board.showNext();
}
private boolean isCurrentPage(SPEC.PAGE which) {
Object obj = getFrontPage().getTag();
if (obj == null)
return which.equals(SPEC.PAGE.DEFAULT);
return which.equals(obj);
}
private void resetTextArea(TextView textArea, SPEC.PAGE type, int gravity) {
((View) textArea.getParent()).scrollTo(0, 0);
textArea.setTag(type);
textArea.setGravity(gravity);
}
private TextView getFrontPage() {
return (TextView) ((ViewGroup) board.getCurrentView()).getChildAt(0);
}
private TextView getBackPage() {
return (TextView) ((ViewGroup) board.getNextView()).getChildAt(0);
}
private void initViews() {
board = (ViewSwitcher) findViewById(R.id.switcher);
Typeface tf = ThisApplication.getFontResource(R.string.font_oem1);
TextView tv = (TextView) findViewById(R.id.txtAppName);
tv.setTypeface(tf);
tf = ThisApplication.getFontResource(R.string.font_oem2);
tv = getFrontPage();
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setTypeface(tf);
tv = getBackPage();
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setTypeface(tf);
toolbar = new Toolbar((ViewGroup) findViewById(R.id.toolbar));
}
private ViewSwitcher board;
private Toolbar toolbar;
private NfcManager nfc;
private boolean safeExit;
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.test.ActivityInstrumentationTestCase2;
/**
* This is a simple framework for a test of an Application. See
* {@link android.test.ApplicationTestCase ApplicationTestCase} for more
* information on how to write and extend Application tests.
* <p/>
* To run this test, you can type:
* adb shell am instrument -w \
* -e class org.connectbot.HostListActivityTest \
* org.connectbot.tests/android.test.InstrumentationTestRunner
*/
public class SettingsActivityTest extends
ActivityInstrumentationTestCase2<SettingsActivity> {
public SettingsActivityTest() {
super("org.connectbot", SettingsActivity.class);
}
public void testOpenMenu() {
SettingsActivity a = getActivity();
a.openOptionsMenu();
a.closeOptionsMenu();
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import org.connectbot.bean.HostBean;
import org.connectbot.mock.BeanTestCase;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class HostBeanTest extends AndroidTestCase {
private static final String[] FIELDS = { "nickname", "username",
"hostname", "port" };
HostBean host1;
HostBean host2;
@Override
protected void setUp() throws Exception {
super.setUp();
host1 = new HostBean();
host1.setNickname("Home");
host1.setUsername("bob");
host1.setHostname("server.example.com");
host1.setPort(22);
host2 = new HostBean();
host2.setNickname("Home");
host2.setUsername("bob");
host2.setHostname("server.example.com");
host2.setPort(22);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testIdEquality() {
host1.setId(1);
host2.setId(1);
assertTrue(host1.equals(host2));
assertTrue(host1.hashCode() == host2.hashCode());
}
public void testIdInequality() {
host1.setId(1);
host2.setId(2);
// HostBeans shouldn't be equal when their IDs are not the same
assertFalse("HostBeans are equal when their ID is different", host1
.equals(host2));
assertFalse("HostBean hash codes are equal when their ID is different",
host1.hashCode() == host2.hashCode());
}
public void testIdEquality2() {
host1.setId(1);
host2.setId(1);
host2.setNickname("Work");
host2.setUsername("alice");
host2.setHostname("client.example.com");
assertTrue(
"HostBeans are not equal when their ID is the same but other fields are different!",
host1.equals(host2));
assertTrue(
"HostBeans hashCodes are not equal when their ID is the same but other fields are different!",
host1.hashCode() == host2.hashCode());
}
public void testBeanMeetsEqualsContract() {
BeanTestCase.assertMeetsEqualsContract(HostBean.class, FIELDS);
}
public void testBeanMeetsHashCodeContract() {
BeanTestCase.assertMeetsHashCodeContract(HostBean.class, FIELDS);
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import org.connectbot.bean.SelectionArea;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class SelectionAreaTest extends AndroidTestCase {
private static final int WIDTH = 80;
private static final int HEIGHT = 24;
public void testCreate() {
SelectionArea sa = new SelectionArea();
assertTrue(sa.getLeft() == 0);
assertTrue(sa.getRight() == 0);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getBottom() == 0);
assertTrue(sa.isSelectingOrigin());
}
public void testCheckMovement() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
sa.incrementColumn();
// Should be (1,0) to (1,0)
assertTrue(sa.getLeft() == 1);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getRight() == 1);
assertTrue(sa.getBottom() == 0);
sa.finishSelectingOrigin();
assertFalse(sa.isSelectingOrigin());
sa.incrementColumn();
sa.incrementColumn();
// Should be (1,0) to (3,0)
assertTrue(sa.getLeft() == 1);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getRight() == 3);
assertTrue(sa.getBottom() == 0);
}
public void testBounds() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
for (int i = 0; i <= WIDTH; i++)
sa.decrementColumn();
assertTrue("Left bound should be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
for (int i = 0; i <= HEIGHT; i++)
sa.decrementRow();
assertTrue("Top bound should be 0, but instead is " + sa.getLeft(),
sa.getTop() == 0);
sa.finishSelectingOrigin();
for (int i = 0; i <= WIDTH * 2; i++)
sa.incrementColumn();
assertTrue("Left bound should be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
assertTrue("Right bound should be " + (WIDTH - 1) + ", but instead is " + sa.getRight(),
sa.getRight() == (WIDTH - 1));
for (int i = 0; i <= HEIGHT * 2; i++)
sa.incrementRow();
assertTrue("Bottom bound should be " + (HEIGHT - 1) + ", but instead is " + sa.getBottom(),
sa.getBottom() == (HEIGHT - 1));
assertTrue("Top bound should be 0, but instead is " + sa.getTop(),
sa.getTop() == 0);
}
public void testSetThenMove() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
int targetColumn = WIDTH / 2;
int targetRow = HEIGHT / 2;
sa.setColumn(targetColumn);
sa.setRow(targetRow);
sa.incrementRow();
assertTrue("Row should be " + (targetRow + 1) + ", but instead is " + sa.getTop(),
sa.getTop() == (targetRow + 1));
sa.decrementColumn();
assertTrue("Column shold be " + (targetColumn - 1) + ", but instead is " + sa.getLeft(),
sa.getLeft() == (targetColumn - 1));
sa.finishSelectingOrigin();
sa.setRow(0);
sa.setColumn(0);
sa.incrementRow();
sa.decrementColumn();
assertTrue("Top row should be 1, but instead is " + sa.getTop(),
sa.getTop() == 1);
assertTrue("Left column shold be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
assertTrue("Bottom row should be " + (targetRow + 1) + ", but instead is " + sa.getBottom(),
sa.getBottom() == (targetRow + 1));
assertTrue("Right column shold be " + (targetColumn - 1) + ", but instead is " + sa.getRight(),
sa.getRight() == (targetColumn - 1));
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
/**
* This is a simple framework for a test of an Application. See
* {@link android.test.ApplicationTestCase ApplicationTestCase} for more
* information on how to write and extend Application tests.
* <p/>
* To run this test, you can type: adb shell am instrument -w \ -e class
* org.connectbot.HostListActivityTest \
* org.connectbot.tests/android.test.InstrumentationTestRunner
*/
public class HostListActivityTest extends ActivityInstrumentationTestCase2<HostListActivity> {
private Activity mActivity;
public HostListActivityTest() {
super("org.connectbot", HostListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
mActivity = getActivity();
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.util;
import java.util.Arrays;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class PubkeyUtilsTest extends AndroidTestCase {
public void testEncodeHex_Null_Failure() throws Exception {
try {
PubkeyUtils.encodeHex(null);
fail("Should throw null pointer exception when argument is null");
} catch (NullPointerException e) {
// success
}
}
public void testEncodeHex_Success() throws Exception {
byte[] input = {(byte) 0xFF, 0x00, (byte) 0xA5, 0x5A, 0x12, 0x23};
String expected = "ff00a55a1223";
assertEquals("Encoded hex should match expected",
PubkeyUtils.encodeHex(input), expected);
}
public void testSha256_Empty_Success() throws Exception {
byte[] empty_hashed = new byte[] {
(byte) 0xe3, (byte) 0xb0, (byte) 0xc4, (byte) 0x42,
(byte) 0x98, (byte) 0xfc, (byte) 0x1c, (byte) 0x14,
(byte) 0x9a, (byte) 0xfb, (byte) 0xf4, (byte) 0xc8,
(byte) 0x99, (byte) 0x6f, (byte) 0xb9, (byte) 0x24,
(byte) 0x27, (byte) 0xae, (byte) 0x41, (byte) 0xe4,
(byte) 0x64, (byte) 0x9b, (byte) 0x93, (byte) 0x4c,
(byte) 0xa4, (byte) 0x95, (byte) 0x99, (byte) 0x1b,
(byte) 0x78, (byte) 0x52, (byte) 0xb8, (byte) 0x55,
};
final byte[] empty = new byte[] {};
assertTrue("Empty string should be equal to known test vector",
Arrays.equals(empty_hashed, PubkeyUtils.sha256(empty)));
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class TerminalBridgeTest extends AndroidTestCase {
public void testShiftLock() throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
// TerminalBridge bridge = new TerminalBridge();
// AbsTransport nullTransport = new NullTransport();
//
// // Make sure onKey will work when we call it
// Field disconnected = TerminalBridge.class
// .getDeclaredField("disconnected");
// Field keymode = TerminalBridge.class.getDeclaredField("keymode");
// Field transport = TerminalBridge.class.getDeclaredField("transport");
//
// disconnected.setAccessible(true);
// keymode.setAccessible(true);
// transport.setAccessible(true);
//
// disconnected.setBoolean(bridge, false);
// keymode.set(bridge, PreferenceConstants.KEYMODE_RIGHT);
// transport.set(bridge, nullTransport);
//
// // Begin tests
// assertTrue("Meta state is " + bridge.getMetaState()
// + " when it should be 0", bridge.getMetaState() == 0);
//
// KeyEvent shiftDown = new KeyEvent(KeyEvent.ACTION_DOWN,
// KeyEvent.KEYCODE_SHIFT_LEFT);
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
//
// assertTrue("Shift test: after shift press, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_ON,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_ON);
//
// KeyEvent shiftUp = KeyEvent.changeAction(shiftDown, KeyEvent.ACTION_UP);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
//
// assertTrue("Shift test: after shift release, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_ON,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_ON);
//
// KeyEvent letterAdown = new KeyEvent(KeyEvent.ACTION_DOWN,
// KeyEvent.KEYCODE_A);
// KeyEvent letterAup = KeyEvent.changeAction(letterAdown,
// KeyEvent.ACTION_UP);
//
// bridge.onKey(null, letterAdown.getKeyCode(), letterAdown);
// bridge.onKey(null, letterAup.getKeyCode(), letterAup);
//
// assertTrue("Shift test: after letter press and release, meta state is "
// + bridge.getMetaState() + " when it should be 0", bridge
// .getMetaState() == 0);
//
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
//
// assertTrue("Shift lock test: after two shift presses, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
//
// bridge.onKey(null, letterAdown.getKeyCode(), letterAdown);
//
// assertTrue(
// "Shift lock test: after letter press, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
//
// bridge.onKey(null, letterAup.getKeyCode(), letterAup);
//
// assertTrue(
// "Shift lock test: after letter press and release, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
}
}
|
Java
|
/**
* Originally from http://www.cornetdesign.com/files/BeanTestCase.java.txt
*/
package org.connectbot.mock;
import junit.framework.TestCase;
import java.lang.reflect.Field;
public class BeanTestCase extends TestCase {
private static final String TEST_STRING_VAL1 = "Some Value";
private static final String TEST_STRING_VAL2 = "Some Other Value";
public static void assertMeetsEqualsContract(Class<?> classUnderTest,
String[] fieldNames) {
Object o1;
Object o2;
try {
// Get Instances
o1 = classUnderTest.newInstance();
o2 = classUnderTest.newInstance();
assertTrue(
"Instances with default constructor not equal (o1.equals(o2))",
o1.equals(o2));
assertTrue(
"Instances with default constructor not equal (o2.equals(o1))",
o2.equals(o1));
Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames);
for (int i = 0; i < fields.length; i++) {
// Reset the instances
o1 = classUnderTest.newInstance();
o2 = classUnderTest.newInstance();
Field field = fields[i];
field.setAccessible(true);
if (field.getType() == String.class) {
field.set(o1, TEST_STRING_VAL1);
} else if (field.getType() == boolean.class) {
field.setBoolean(o1, true);
} else if (field.getType() == short.class) {
field.setShort(o1, (short) 1);
} else if (field.getType() == long.class) {
field.setLong(o1, (long) 1);
} else if (field.getType() == float.class) {
field.setFloat(o1, (float) 1);
} else if (field.getType() == int.class) {
field.setInt(o1, 1);
} else if (field.getType() == byte.class) {
field.setByte(o1, (byte) 1);
} else if (field.getType() == char.class) {
field.setChar(o1, (char) 1);
} else if (field.getType() == double.class) {
field.setDouble(o1, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o1, field.getType().getEnumConstants()[0]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o1, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
assertFalse("Instances with o1 having " + field.getName()
+ " set and o2 having it not set are equal", o1
.equals(o2));
field.set(o2, field.get(o1));
assertTrue(
"After setting o2 with the value of the object in o1, the two objects in the field are not equal",
field.get(o1).equals(field.get(o2)));
assertTrue(
"Instances with o1 having "
+ field.getName()
+ " set and o2 having it set to the same object of type "
+ field.get(o2).getClass().getName()
+ " are not equal", o1.equals(o2));
if (field.getType() == String.class) {
field.set(o2, TEST_STRING_VAL2);
} else if (field.getType() == boolean.class) {
field.setBoolean(o2, false);
} else if (field.getType() == short.class) {
field.setShort(o2, (short) 0);
} else if (field.getType() == long.class) {
field.setLong(o2, (long) 0);
} else if (field.getType() == float.class) {
field.setFloat(o2, (float) 0);
} else if (field.getType() == int.class) {
field.setInt(o2, 0);
} else if (field.getType() == byte.class) {
field.setByte(o2, (byte) 0);
} else if (field.getType() == char.class) {
field.setChar(o2, (char) 0);
} else if (field.getType() == double.class) {
field.setDouble(o2, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o2, field.getType().getEnumConstants()[1]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o2, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
if (field.get(o1).equals(field.get(o2))) {
// Even though we have different instances, they are equal.
// Let's walk one of them
// to see if we can find a field to set
Field[] paramFields = field.get(o1).getClass()
.getDeclaredFields();
for (int j = 0; j < paramFields.length; j++) {
paramFields[j].setAccessible(true);
if (paramFields[j].getType() == String.class) {
paramFields[j].set(field.get(o1), TEST_STRING_VAL1);
}
}
}
assertFalse(
"After setting o2 with a different object than what is in o1, the two objects in the field are equal. "
+ "This is after an attempt to walk the fields to make them different",
field.get(o1).equals(field.get(o2)));
assertFalse(
"Instances with o1 having "
+ field.getName()
+ " set and o2 having it set to a different object are equal",
o1.equals(o2));
}
} catch (InstantiationException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (SecurityException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to read the field from the class under test");
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to find field in the class under test");
}
}
/**
* @param classUnderTest
* @param fieldNames
* @return
* @throws NoSuchFieldException
*/
private static Field[] getFieldsByNameOrAll(Class<?> classUnderTest,
String[] fieldNames) throws NoSuchFieldException {
Field fields[];
if (fieldNames == null) {
fields = classUnderTest.getDeclaredFields();
} else {
fields = new Field[fieldNames.length];
for (int i = 0; i < fieldNames.length; i++)
fields[i] = classUnderTest.getDeclaredField(fieldNames[i]);
}
return fields;
}
public static void assertMeetsHashCodeContract(Class<?> classUnderTest,
String[] fieldNames) {
try {
Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames);
for (int i = 0; i < fields.length; i++) {
Object o1 = classUnderTest.newInstance();
int initialHashCode = o1.hashCode();
Field field = fields[i];
field.setAccessible(true);
if (field.getType() == String.class) {
field.set(o1, TEST_STRING_VAL1);
} else if (field.getType() == boolean.class) {
field.setBoolean(o1, true);
} else if (field.getType() == short.class) {
field.setShort(o1, (short) 1);
} else if (field.getType() == long.class) {
field.setLong(o1, (long) 1);
} else if (field.getType() == float.class) {
field.setFloat(o1, (float) 1);
} else if (field.getType() == int.class) {
field.setInt(o1, 1);
} else if (field.getType() == byte.class) {
field.setByte(o1, (byte) 1);
} else if (field.getType() == char.class) {
field.setChar(o1, (char) 1);
} else if (field.getType() == double.class) {
field.setDouble(o1, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o1, field.getType().getEnumConstants()[0]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o1, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
int updatedHashCode = o1.hashCode();
assertFalse(
"The field "
+ field.getName()
+ " was not taken into account for the hashCode contract ",
initialHashCode == updatedHashCode);
}
} catch (InstantiationException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to find field in the class under test");
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.mock;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author Kenny Root
*
*/
public class NullOutputStream extends OutputStream {
@Override
public void write(int arg0) throws IOException {
// do nothing
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.mock;
import java.io.IOException;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.AbsTransport;
import android.net.Uri;
/**
* @author kenny
*
*/
public class NullTransport extends AbsTransport {
/**
*
*/
public NullTransport() {
// TODO Auto-generated constructor stub
}
/**
* @param host
* @param bridge
* @param manager
*/
public NullTransport(HostBean host, TerminalBridge bridge,
TerminalManager manager) {
super(host, bridge, manager);
// TODO Auto-generated constructor stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public void connect() {
// TODO Auto-generated method stub
}
@Override
public HostBean createHost(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public void flush() throws IOException {
// TODO Auto-generated method stub
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getDefaultPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
// TODO Auto-generated method stub
}
@Override
public boolean isConnected() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSessionOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void write(byte[] buffer) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void write(int c) throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean usesNetwork() {
// TODO Auto-generated method stub
return false;
}
}
|
Java
|
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
/**
* Generic display
*/
public interface VDUDisplay {
public void redraw();
public void updateScrollBar();
public void setVDUBuffer(VDUBuffer buffer);
public VDUBuffer getVDUBuffer();
public void setColor(int index, int red, int green, int blue);
public void resetColors();
}
|
Java
|
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Mei�ner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import java.util.Arrays;
/**
* Implementation of a Video Display Unit (VDU) buffer. This class contains
* all methods to manipulate the buffer that stores characters and their
* attributes as well as the regions displayed.
*
* @author Matthias L. Jugel, Marcus Meißner
* @version $Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $
*/
public class VDUBuffer {
/** The current version id tag */
public final static String ID = "$Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $";
/** Enable debug messages. */
public final static int debug = 0;
public int height, width; /* rows and columns */
public boolean[] update; /* contains the lines that need update */
public char[][] charArray; /* contains the characters */
public int[][] charAttributes; /* contains character attrs */
public int bufSize;
public int maxBufSize; /* buffer sizes */
public int screenBase; /* the actual screen start */
public int windowBase; /* where the start displaying */
public int scrollMarker; /* marks the last line inserted */
private int topMargin; /* top scroll margin */
private int bottomMargin; /* bottom scroll margin */
// cursor variables
protected boolean showcursor = true;
protected int cursorX, cursorY;
/** Scroll up when inserting a line. */
public final static boolean SCROLL_UP = false;
/** Scroll down when inserting a line. */
public final static boolean SCROLL_DOWN = true;
/* Attributes bit-field usage:
*
* 8421 8421 8421 8421 8421 8421 8421 8421
* |||| |||| |||| |||| |||| |||| |||| |||`- Bold
* |||| |||| |||| |||| |||| |||| |||| ||`-- Underline
* |||| |||| |||| |||| |||| |||| |||| |`--- Invert
* |||| |||| |||| |||| |||| |||| |||| `---- Low
* |||| |||| |||| |||| |||| |||| |||`------ Invisible
* |||| |||| |||| |||| ||`+-++++-+++------- Foreground Color
* |||| |||| |`++-++++-++------------------ Background Color
* |||| |||| `----------------------------- Fullwidth character
* `+++-++++------------------------------- Reserved for future use
*/
/** Make character normal. */
public final static int NORMAL = 0x00;
/** Make character bold. */
public final static int BOLD = 0x01;
/** Underline character. */
public final static int UNDERLINE = 0x02;
/** Invert character. */
public final static int INVERT = 0x04;
/** Lower intensity character. */
public final static int LOW = 0x08;
/** Invisible character. */
public final static int INVISIBLE = 0x10;
/** Unicode full-width character (CJK, et al.) */
public final static int FULLWIDTH = 0x8000000;
/** how much to left shift the foreground color */
public final static int COLOR_FG_SHIFT = 5;
/** how much to left shift the background color */
public final static int COLOR_BG_SHIFT = 14;
/** color mask */
public final static int COLOR = 0x7fffe0; /* 0000 0000 0111 1111 1111 1111 1110 0000 */
/** foreground color mask */
public final static int COLOR_FG = 0x3fe0; /* 0000 0000 0000 0000 0011 1111 1110 0000 */
/** background color mask */
public final static int COLOR_BG = 0x7fc000; /* 0000 0000 0111 1111 1100 0000 0000 0000 */
/**
* Create a new video display buffer with the passed width and height in
* characters.
* @param width the length of the character lines
* @param height the amount of lines on the screen
*/
public VDUBuffer(int width, int height) {
// set the display screen size
setScreenSize(width, height, false);
}
/**
* Create a standard video display buffer with 80 columns and 24 lines.
*/
public VDUBuffer() {
this(80, 24);
}
/**
* Put a character on the screen with normal font and outline.
* The character previously on that position will be overwritten.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to show on the screen
* @see #insertChar
* @see #deleteChar
* @see #redraw
*/
public void putChar(int c, int l, char ch) {
putChar(c, l, ch, NORMAL);
}
/**
* Put a character on the screen with specific font and outline.
* The character previously on that position will be overwritten.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to show on the screen
* @param attributes the character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #insertChar
* @see #deleteChar
* @see #redraw
*/
public void putChar(int c, int l, char ch, int attributes) {
charArray[screenBase + l][c] = ch;
charAttributes[screenBase + l][c] = attributes;
if (l < height)
update[l + 1] = true;
}
/**
* Get the character at the specified position.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
*/
public char getChar(int c, int l) {
return charArray[screenBase + l][c];
}
/**
* Get the attributes for the specified position.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
*/
public int getAttributes(int c, int l) {
return charAttributes[screenBase + l][c];
}
/**
* Insert a character at a specific position on the screen.
* All character right to from this position will be moved one to the right.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to insert
* @param attributes the character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #deleteChar
* @see #redraw
*/
public void insertChar(int c, int l, char ch, int attributes) {
System.arraycopy(charArray[screenBase + l], c,
charArray[screenBase + l], c + 1, width - c - 1);
System.arraycopy(charAttributes[screenBase + l], c,
charAttributes[screenBase + l], c + 1, width - c - 1);
putChar(c, l, ch, attributes);
}
/**
* Delete a character at a given position on the screen.
* All characters right to the position will be moved one to the left.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
* @see #insertChar
* @see #redraw
*/
public void deleteChar(int c, int l) {
if (c < width - 1) {
System.arraycopy(charArray[screenBase + l], c + 1,
charArray[screenBase + l], c, width - c - 1);
System.arraycopy(charAttributes[screenBase + l], c + 1,
charAttributes[screenBase + l], c, width - c - 1);
}
putChar(width - 1, l, (char) 0);
}
/**
* Put a String at a specific position. Any characters previously on that
* position will be overwritten. You need to call redraw() for screen update.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param s the string to be shown on the screen
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #insertLine
* @see #deleteLine
* @see #redraw
*/
public void putString(int c, int l, String s) {
putString(c, l, s, NORMAL);
}
/**
* Put a String at a specific position giving all characters the same
* attributes. Any characters previously on that position will be
* overwritten. You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param s the string to be shown on the screen
* @param attributes character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #insertLine
* @see #deleteLine
* @see #redraw
*/
public void putString(int c, int l, String s, int attributes) {
for (int i = 0; i < s.length() && c + i < width; i++)
putChar(c + i, l, s.charAt(i), attributes);
}
/**
* Insert a blank line at a specific position.
* The current line and all previous lines are scrolled one line up. The
* top line is lost. You need to call redraw() to update the screen.
* @param l the y-coordinate to insert the line
* @see #deleteLine
* @see #redraw
*/
public void insertLine(int l) {
insertLine(l, 1, SCROLL_UP);
}
/**
* Insert blank lines at a specific position.
* You need to call redraw() to update the screen
* @param l the y-coordinate to insert the line
* @param n amount of lines to be inserted
* @see #deleteLine
* @see #redraw
*/
public void insertLine(int l, int n) {
insertLine(l, n, SCROLL_UP);
}
/**
* Insert a blank line at a specific position. Scroll text according to
* the argument.
* You need to call redraw() to update the screen
* @param l the y-coordinate to insert the line
* @param scrollDown scroll down
* @see #deleteLine
* @see #SCROLL_UP
* @see #SCROLL_DOWN
* @see #redraw
*/
public void insertLine(int l, boolean scrollDown) {
insertLine(l, 1, scrollDown);
}
/**
* Insert blank lines at a specific position.
* The current line and all previous lines are scrolled one line up. The
* top line is lost. You need to call redraw() to update the screen.
* @param l the y-coordinate to insert the line
* @param n number of lines to be inserted
* @param scrollDown scroll down
* @see #deleteLine
* @see #SCROLL_UP
* @see #SCROLL_DOWN
* @see #redraw
*/
public synchronized void insertLine(int l, int n, boolean scrollDown) {
char cbuf[][] = null;
int abuf[][] = null;
int offset = 0;
int oldBase = screenBase;
int newScreenBase = screenBase;
int newWindowBase = windowBase;
int newBufSize = bufSize;
if (l > bottomMargin) /* We do not scroll below bottom margin (below the scrolling region). */
return;
int top = (l < topMargin ?
0 : (l > bottomMargin ?
(bottomMargin + 1 < height ?
bottomMargin + 1 : height - 1) : topMargin));
int bottom = (l > bottomMargin ?
height - 1 : (l < topMargin ?
(topMargin > 0 ?
topMargin - 1 : 0) : bottomMargin));
// System.out.println("l is "+l+", top is "+top+", bottom is "+bottom+", bottomargin is "+bottomMargin+", topMargin is "+topMargin);
if (scrollDown) {
if (n > (bottom - top)) n = (bottom - top);
int size = bottom - l - (n - 1);
if(size < 0) size = 0;
cbuf = new char[size][];
abuf = new int[size][];
System.arraycopy(charArray, oldBase + l, cbuf, 0, bottom - l - (n - 1));
System.arraycopy(charAttributes, oldBase + l,
abuf, 0, bottom - l - (n - 1));
System.arraycopy(cbuf, 0, charArray, oldBase + l + n,
bottom - l - (n - 1));
System.arraycopy(abuf, 0, charAttributes, oldBase + l + n,
bottom - l - (n - 1));
cbuf = charArray;
abuf = charAttributes;
} else {
try {
if (n > (bottom - top) + 1) n = (bottom - top) + 1;
if (bufSize < maxBufSize) {
if (bufSize + n > maxBufSize) {
offset = n - (maxBufSize - bufSize);
scrollMarker += offset;
newBufSize = maxBufSize;
newScreenBase = maxBufSize - height - 1;
newWindowBase = screenBase;
} else {
scrollMarker += n;
newScreenBase += n;
newWindowBase += n;
newBufSize += n;
}
cbuf = new char[newBufSize][];
abuf = new int[newBufSize][];
} else {
offset = n;
cbuf = charArray;
abuf = charAttributes;
}
// copy anything from the top of the buffer (+offset) to the new top
// up to the screenBase.
if (oldBase > 0) {
System.arraycopy(charArray, offset,
cbuf, 0,
oldBase - offset);
System.arraycopy(charAttributes, offset,
abuf, 0,
oldBase - offset);
}
// copy anything from the top of the screen (screenBase) up to the
// topMargin to the new screen
if (top > 0) {
System.arraycopy(charArray, oldBase,
cbuf, newScreenBase,
top);
System.arraycopy(charAttributes, oldBase,
abuf, newScreenBase,
top);
}
// copy anything from the topMargin up to the amount of lines inserted
// to the gap left over between scrollback buffer and screenBase
if (oldBase >= 0) {
System.arraycopy(charArray, oldBase + top,
cbuf, oldBase - offset,
n);
System.arraycopy(charAttributes, oldBase + top,
abuf, oldBase - offset,
n);
}
// copy anything from topMargin + n up to the line linserted to the
// topMargin
System.arraycopy(charArray, oldBase + top + n,
cbuf, newScreenBase + top,
l - top - (n - 1));
System.arraycopy(charAttributes, oldBase + top + n,
abuf, newScreenBase + top,
l - top - (n - 1));
//
// copy the all lines next to the inserted to the new buffer
if (l < height - 1) {
System.arraycopy(charArray, oldBase + l + 1,
cbuf, newScreenBase + l + 1,
(height - 1) - l);
System.arraycopy(charAttributes, oldBase + l + 1,
abuf, newScreenBase + l + 1,
(height - 1) - l);
}
} catch (ArrayIndexOutOfBoundsException e) {
// this should not happen anymore, but I will leave the code
// here in case something happens anyway. That code above is
// so complex I always have a hard time understanding what
// I did, even though there are comments
System.err.println("*** Error while scrolling up:");
System.err.println("--- BEGIN STACK TRACE ---");
e.printStackTrace();
System.err.println("--- END STACK TRACE ---");
System.err.println("bufSize=" + bufSize + ", maxBufSize=" + maxBufSize);
System.err.println("top=" + top + ", bottom=" + bottom);
System.err.println("n=" + n + ", l=" + l);
System.err.println("screenBase=" + screenBase + ", windowBase=" + windowBase);
System.err.println("newScreenBase=" + newScreenBase + ", newWindowBase=" + newWindowBase);
System.err.println("oldBase=" + oldBase);
System.err.println("size.width=" + width + ", size.height=" + height);
System.err.println("abuf.length=" + abuf.length + ", cbuf.length=" + cbuf.length);
System.err.println("*** done dumping debug information");
}
}
// this is a little helper to mark the scrolling
scrollMarker -= n;
for (int i = 0; i < n; i++) {
cbuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new char[width];
Arrays.fill(cbuf[(newScreenBase + l) + (scrollDown ? i : -i)], ' ');
abuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new int[width];
}
charArray = cbuf;
charAttributes = abuf;
screenBase = newScreenBase;
windowBase = newWindowBase;
bufSize = newBufSize;
if (scrollDown)
markLine(l, bottom - l + 1);
else
markLine(top, l - top + 1);
display.updateScrollBar();
}
/**
* Delete a line at a specific position. Subsequent lines will be scrolled
* up to fill the space and a blank line is inserted at the end of the
* screen.
* @param l the y-coordinate to insert the line
* @see #deleteLine
*/
public void deleteLine(int l) {
int bottom = (l > bottomMargin ? height - 1:
(l < topMargin?topMargin:bottomMargin + 1));
int numRows = bottom - l - 1;
char[] discardedChars = charArray[screenBase + l];
int[] discardedAttributes = charAttributes[screenBase + l];
if (numRows > 0) {
System.arraycopy(charArray, screenBase + l + 1,
charArray, screenBase + l, numRows);
System.arraycopy(charAttributes, screenBase + l + 1,
charAttributes, screenBase + l, numRows);
}
int newBottomRow = screenBase + bottom - 1;
charArray[newBottomRow] = discardedChars;
charAttributes[newBottomRow] = discardedAttributes;
Arrays.fill(charArray[newBottomRow], ' ');
Arrays.fill(charAttributes[newBottomRow], 0);
markLine(l, bottom - l);
}
/**
* Delete a rectangular portion of the screen.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (row)
* @param w with of the area in characters
* @param h height of the area in characters
* @param curAttr attribute to fill
* @see #deleteChar
* @see #deleteLine
* @see #redraw
*/
public void deleteArea(int c, int l, int w, int h, int curAttr) {
int endColumn = c + w;
int targetRow = screenBase + l;
for (int i = 0; i < h && l + i < height; i++) {
Arrays.fill(charAttributes[targetRow], c, endColumn, curAttr);
Arrays.fill(charArray[targetRow], c, endColumn, ' ');
targetRow++;
}
markLine(l, h);
}
/**
* Delete a rectangular portion of the screen.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (row)
* @param w with of the area in characters
* @param h height of the area in characters
* @see #deleteChar
* @see #deleteLine
* @see #redraw
*/
public void deleteArea(int c, int l, int w, int h) {
deleteArea(c, l, w, h, 0);
}
/**
* Sets whether the cursor is visible or not.
* @param doshow
*/
public void showCursor(boolean doshow) {
showcursor = doshow;
}
/**
* Check whether the cursor is currently visible.
* @return visibility
*/
public boolean isCursorVisible() {
return showcursor;
}
/**
* Puts the cursor at the specified position.
* @param c column
* @param l line
*/
public void setCursorPosition(int c, int l) {
cursorX = c;
cursorY = l;
}
/**
* Get the current column of the cursor position.
*/
public int getCursorColumn() {
return cursorX;
}
/**
* Get the current line of the cursor position.
*/
public int getCursorRow() {
return cursorY;
}
/**
* Set the current window base. This allows to view the scrollback buffer.
* @param line the line where the screen window starts
* @see #setBufferSize
* @see #getBufferSize
*/
public void setWindowBase(int line) {
if (line > screenBase)
line = screenBase;
else if (line < 0) line = 0;
windowBase = line;
update[0] = true;
redraw();
}
/**
* Get the current window base.
* @see #setWindowBase
*/
public int getWindowBase() {
return windowBase;
}
/**
* Set the scroll margins simultaneously. If they're out of bounds, trim them.
* @param l1 line that is the top
* @param l2 line that is the bottom
*/
public void setMargins(int l1, int l2) {
if (l1 > l2)
return;
if (l1 < 0)
l1 = 0;
if (l2 >= height)
l2 = height - 1;
topMargin = l1;
bottomMargin = l2;
}
/**
* Set the top scroll margin for the screen. If the current bottom margin
* is smaller it will become the top margin and the line will become the
* bottom margin.
* @param l line that is the margin
*/
public void setTopMargin(int l) {
if (l > bottomMargin) {
topMargin = bottomMargin;
bottomMargin = l;
} else
topMargin = l;
if (topMargin < 0) topMargin = 0;
if (bottomMargin >= height) bottomMargin = height - 1;
}
/**
* Get the top scroll margin.
*/
public int getTopMargin() {
return topMargin;
}
/**
* Set the bottom scroll margin for the screen. If the current top margin
* is bigger it will become the bottom margin and the line will become the
* top margin.
* @param l line that is the margin
*/
public void setBottomMargin(int l) {
if (l < topMargin) {
bottomMargin = topMargin;
topMargin = l;
} else
bottomMargin = l;
if (topMargin < 0) topMargin = 0;
if (bottomMargin >= height) bottomMargin = height - 1;
}
/**
* Get the bottom scroll margin.
*/
public int getBottomMargin() {
return bottomMargin;
}
/**
* Set scrollback buffer size.
* @param amount new size of the buffer
*/
public void setBufferSize(int amount) {
if (amount < height) amount = height;
if (amount < maxBufSize) {
char cbuf[][] = new char[amount][width];
int abuf[][] = new int[amount][width];
int copyStart = bufSize - amount < 0 ? 0 : bufSize - amount;
int copyCount = bufSize - amount < 0 ? bufSize : amount;
if (charArray != null)
System.arraycopy(charArray, copyStart, cbuf, 0, copyCount);
if (charAttributes != null)
System.arraycopy(charAttributes, copyStart, abuf, 0, copyCount);
charArray = cbuf;
charAttributes = abuf;
bufSize = copyCount;
screenBase = bufSize - height;
windowBase = screenBase;
}
maxBufSize = amount;
update[0] = true;
redraw();
}
/**
* Retrieve current scrollback buffer size.
* @see #setBufferSize
*/
public int getBufferSize() {
return bufSize;
}
/**
* Retrieve maximum buffer Size.
* @see #getBufferSize
*/
public int getMaxBufferSize() {
return maxBufSize;
}
/**
* Change the size of the screen. This will include adjustment of the
* scrollback buffer.
* @param w of the screen
* @param h of the screen
*/
public void setScreenSize(int w, int h, boolean broadcast) {
char cbuf[][];
int abuf[][];
int maxSize = bufSize;
if (w < 1 || h < 1) return;
if (debug > 0)
System.err.println("VDU: screen size [" + w + "," + h + "]");
if (h > maxBufSize)
maxBufSize = h;
if (h > bufSize) {
bufSize = h;
screenBase = 0;
windowBase = 0;
}
if (windowBase + h >= bufSize)
windowBase = bufSize - h;
if (screenBase + h >= bufSize)
screenBase = bufSize - h;
cbuf = new char[bufSize][w];
abuf = new int[bufSize][w];
for (int i = 0; i < bufSize; i++) {
Arrays.fill(cbuf[i], ' ');
}
if (bufSize < maxSize)
maxSize = bufSize;
int rowLength;
if (charArray != null && charAttributes != null) {
for (int i = 0; i < maxSize && charArray[i] != null; i++) {
rowLength = charArray[i].length;
System.arraycopy(charArray[i], 0, cbuf[i], 0,
w < rowLength ? w : rowLength);
System.arraycopy(charAttributes[i], 0, abuf[i], 0,
w < rowLength ? w : rowLength);
}
}
int C = getCursorColumn();
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
int R = getCursorRow();
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
setCursorPosition(C, R);
charArray = cbuf;
charAttributes = abuf;
width = w;
height = h;
topMargin = 0;
bottomMargin = h - 1;
update = new boolean[h + 1];
update[0] = true;
/* FIXME: ???
if(resizeStrategy == RESIZE_FONT)
setBounds(getBounds());
*/
}
/**
* Get amount of rows on the screen.
*/
public int getRows() {
return height;
}
/**
* Get amount of columns on the screen.
*/
public int getColumns() {
return width;
}
/**
* Mark lines to be updated with redraw().
* @param l starting line
* @param n amount of lines to be updated
* @see #redraw
*/
public void markLine(int l, int n) {
for (int i = 0; (i < n) && (l + i < height); i++)
update[l + i + 1] = true;
}
// private static int checkBounds(int value, int lower, int upper) {
// if (value < lower)
// return lower;
// else if (value > upper)
// return upper;
// else
// return value;
// }
/** a generic display that should redraw on demand */
protected VDUDisplay display;
public void setDisplay(VDUDisplay display) {
this.display = display;
}
/**
* Trigger a redraw on the display.
*/
protected void redraw() {
if (display != null)
display.redraw();
}
}
|
Java
|
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meiner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import android.text.AndroidCharacter;
import java.util.Properties;
/**
* Implementation of a VT terminal emulation plus ANSI compatible.
* <P>
* <B>Maintainer:</B> Marcus Meißner
*
* @version $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $
* @author Matthias L. Jugel, Marcus Meißner
*/
public abstract class vt320 extends VDUBuffer implements VDUInput {
/** The current version id tag.<P>
* $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $
*
*/
public final static String ID = "$Id: vt320.java 507 2005-10-25 10:14:52Z marcus $";
/** the debug level */
private final static int debug = 0;
private StringBuilder debugStr;
public abstract void debug(String notice);
/**
* Write an answer back to the remote host. This is needed to be able to
* send terminal answers requests like status and type information.
* @param b the array of bytes to be sent
*/
public abstract void write(byte[] b);
/**
* Write an answer back to the remote host. This is needed to be able to
* send terminal answers requests like status and type information.
* @param b the array of bytes to be sent
*/
public abstract void write(int b);
/**
* Play the beep sound ...
*/
public void beep() { /* do nothing by default */
}
/**
* Convenience function for putString(char[], int, int)
*/
public void putString(String s) {
int len = s.length();
char[] tmp = new char[len];
s.getChars(0, len, tmp, 0);
putString(tmp, null, 0, len);
}
/**
* Put string at current cursor position. Moves cursor
* according to the String. Does NOT wrap.
* @param s character array
* @param start place to start in array
* @param len number of characters to process
*/
public void putString(char[] s, byte[] fullwidths, int start, int len) {
if (len > 0) {
//markLine(R, 1);
int lastChar = -1;
char c;
boolean isWide = false;
for (int i = 0; i < len; i++) {
c = s[start + i];
// Shortcut for my favorite ASCII
if (c <= 0x7F) {
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
lastChar = c;
isWide = false;
} else if (!Character.isLowSurrogate(c) && !Character.isHighSurrogate(c)) {
if (Character.getType(c) == Character.NON_SPACING_MARK) {
if (lastChar != -1) {
char nc = Precomposer.precompose((char) lastChar, c);
putChar(nc, isWide, false);
lastChar = -1;
}
} else {
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
lastChar = c;
if (fullwidths != null) {
final byte width = fullwidths[i];
isWide = (width == AndroidCharacter.EAST_ASIAN_WIDTH_WIDE)
|| (width == AndroidCharacter.EAST_ASIAN_WIDTH_FULL_WIDTH);
}
}
}
}
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
setCursorPosition(C, R);
redraw();
}
}
protected void sendTelnetCommand(byte cmd) {
}
/**
* Sent the changed window size from the terminal to all listeners.
*/
protected void setWindowSize(int c, int r) {
/* To be overridden by Terminal.java */
}
@Override
public void setScreenSize(int c, int r, boolean broadcast) {
int oldrows = height;
if (debug>2) {
if (debugStr == null)
debugStr = new StringBuilder();
debugStr.append("setscreensize (")
.append(c)
.append(',')
.append(r)
.append(',')
.append(broadcast)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
}
super.setScreenSize(c,r,false);
boolean cursorChanged = false;
// Don't let the cursor go off the screen.
if (C >= c) {
C = c - 1;
cursorChanged = true;
}
if (R >= r) {
R = r - 1;
cursorChanged = true;
}
if (cursorChanged) {
setCursorPosition(C, R);
redraw();
}
if (broadcast) {
setWindowSize(c, r); /* broadcast up */
}
}
/**
* Create a new vt320 terminal and intialize it with useful settings.
*/
public vt320(int width, int height) {
super(width, height);
debugStr = new StringBuilder();
setVMS(false);
setIBMCharset(false);
setTerminalID("vt320");
setBufferSize(100);
//setBorder(2, false);
gx = new char[4];
reset();
/* top row of numpad */
PF1 = "\u001bOP";
PF2 = "\u001bOQ";
PF3 = "\u001bOR";
PF4 = "\u001bOS";
/* the 3x2 keyblock on PC keyboards */
Insert = new String[4];
Remove = new String[4];
KeyHome = new String[4];
KeyEnd = new String[4];
NextScn = new String[4];
PrevScn = new String[4];
Escape = new String[4];
BackSpace = new String[4];
TabKey = new String[4];
Insert[0] = Insert[1] = Insert[2] = Insert[3] = "\u001b[2~";
Remove[0] = Remove[1] = Remove[2] = Remove[3] = "\u001b[3~";
PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[5~";
NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[6~";
KeyHome[0] = KeyHome[1] = KeyHome[2] = KeyHome[3] = "\u001b[H";
KeyEnd[0] = KeyEnd[1] = KeyEnd[2] = KeyEnd[3] = "\u001b[F";
Escape[0] = Escape[1] = Escape[2] = Escape[3] = "\u001b";
if (vms) {
BackSpace[1] = "" + (char) 10; // VMS shift deletes word back
BackSpace[2] = "\u0018"; // VMS control deletes line back
BackSpace[0] = BackSpace[3] = "\u007f"; // VMS other is delete
} else {
//BackSpace[0] = BackSpace[1] = BackSpace[2] = BackSpace[3] = "\b";
// ConnectBot modifications.
BackSpace[0] = "\b";
BackSpace[1] = "\u007f";
BackSpace[2] = "\u001b[3~";
BackSpace[3] = "\u001b[2~";
}
/* some more VT100 keys */
Find = "\u001b[1~";
Select = "\u001b[4~";
Help = "\u001b[28~";
Do = "\u001b[29~";
FunctionKey = new String[21];
FunctionKey[0] = "";
FunctionKey[1] = PF1;
FunctionKey[2] = PF2;
FunctionKey[3] = PF3;
FunctionKey[4] = PF4;
/* following are defined differently for vt220 / vt132 ... */
FunctionKey[5] = "\u001b[15~";
FunctionKey[6] = "\u001b[17~";
FunctionKey[7] = "\u001b[18~";
FunctionKey[8] = "\u001b[19~";
FunctionKey[9] = "\u001b[20~";
FunctionKey[10] = "\u001b[21~";
FunctionKey[11] = "\u001b[23~";
FunctionKey[12] = "\u001b[24~";
FunctionKey[13] = "\u001b[25~";
FunctionKey[14] = "\u001b[26~";
FunctionKey[15] = Help;
FunctionKey[16] = Do;
FunctionKey[17] = "\u001b[31~";
FunctionKey[18] = "\u001b[32~";
FunctionKey[19] = "\u001b[33~";
FunctionKey[20] = "\u001b[34~";
FunctionKeyShift = new String[21];
FunctionKeyAlt = new String[21];
FunctionKeyCtrl = new String[21];
for (int i = 0; i < 20; i++) {
FunctionKeyShift[i] = "";
FunctionKeyAlt[i] = "";
FunctionKeyCtrl[i] = "";
}
FunctionKeyShift[15] = Find;
FunctionKeyShift[16] = Select;
TabKey[0] = "\u0009";
TabKey[1] = "\u001bOP\u0009";
TabKey[2] = TabKey[3] = "";
KeyUp = new String[4];
KeyUp[0] = "\u001b[A";
KeyDown = new String[4];
KeyDown[0] = "\u001b[B";
KeyRight = new String[4];
KeyRight[0] = "\u001b[C";
KeyLeft = new String[4];
KeyLeft[0] = "\u001b[D";
Numpad = new String[10];
Numpad[0] = "\u001bOp";
Numpad[1] = "\u001bOq";
Numpad[2] = "\u001bOr";
Numpad[3] = "\u001bOs";
Numpad[4] = "\u001bOt";
Numpad[5] = "\u001bOu";
Numpad[6] = "\u001bOv";
Numpad[7] = "\u001bOw";
Numpad[8] = "\u001bOx";
Numpad[9] = "\u001bOy";
KPMinus = PF4;
KPComma = "\u001bOl";
KPPeriod = "\u001bOn";
KPEnter = "\u001bOM";
NUMPlus = new String[4];
NUMPlus[0] = "+";
NUMDot = new String[4];
NUMDot[0] = ".";
}
public void setBackspace(int type) {
switch (type) {
case DELETE_IS_DEL:
BackSpace[0] = "\u007f";
BackSpace[1] = "\b";
break;
case DELETE_IS_BACKSPACE:
BackSpace[0] = "\b";
BackSpace[1] = "\u007f";
break;
}
}
/**
* Create a default vt320 terminal with 80 columns and 24 lines.
*/
public vt320() {
this(80, 24);
}
/**
* Terminal is mouse-aware and requires (x,y) coordinates of
* on the terminal (character coordinates) and the button clicked.
* @param x
* @param y
* @param modifiers
*/
public void mousePressed(int x, int y, int modifiers) {
if (mouserpt == 0)
return;
int mods = modifiers;
mousebut = 3;
if ((mods & 16) == 16) mousebut = 0;
if ((mods & 8) == 8) mousebut = 1;
if ((mods & 4) == 4) mousebut = 2;
int mousecode;
if (mouserpt == 9) /* X10 Mouse */
mousecode = 0x20 | mousebut;
else /* normal xterm mouse reporting */
mousecode = mousebut | 0x20 | ((mods & 7) << 2);
byte b[] = new byte[6];
b[0] = 27;
b[1] = (byte) '[';
b[2] = (byte) 'M';
b[3] = (byte) mousecode;
b[4] = (byte) (0x20 + x + 1);
b[5] = (byte) (0x20 + y + 1);
write(b); // FIXME: writeSpecial here
}
/**
* Terminal is mouse-aware and requires the coordinates and button
* of the release.
* @param x
* @param y
* @param modifiers
*/
public void mouseReleased(int x, int y, int modifiers) {
if (mouserpt == 0)
return;
/* problem is tht modifiers still have the released button set in them.
int mods = modifiers;
mousebut = 3;
if ((mods & 16)==16) mousebut=0;
if ((mods & 8)==8 ) mousebut=1;
if ((mods & 4)==4 ) mousebut=2;
*/
int mousecode;
if (mouserpt == 9)
mousecode = 0x20 + mousebut; /* same as press? appears so. */
else
mousecode = '#';
byte b[] = new byte[6];
b[0] = 27;
b[1] = (byte) '[';
b[2] = (byte) 'M';
b[3] = (byte) mousecode;
b[4] = (byte) (0x20 + x + 1);
b[5] = (byte) (0x20 + y + 1);
write(b); // FIXME: writeSpecial here
mousebut = 0;
}
/** we should do localecho (passed from other modules). false is default */
private boolean localecho = false;
/**
* Enable or disable the local echo property of the terminal.
* @param echo true if the terminal should echo locally
*/
public void setLocalEcho(boolean echo) {
localecho = echo;
}
/**
* Enable the VMS mode of the terminal to handle some things differently
* for VMS hosts.
* @param vms true for vms mode, false for normal mode
*/
public void setVMS(boolean vms) {
this.vms = vms;
}
/**
* Enable the usage of the IBM character set used by some BBS's. Special
* graphical character are available in this mode.
* @param ibm true to use the ibm character set
*/
public void setIBMCharset(boolean ibm) {
useibmcharset = ibm;
}
/**
* Override the standard key codes used by the terminal emulation.
* @param codes a properties object containing key code definitions
*/
public void setKeyCodes(Properties codes) {
String res, prefixes[] = {"", "S", "C", "A"};
int i;
for (i = 0; i < 10; i++) {
res = codes.getProperty("NUMPAD" + i);
if (res != null) Numpad[i] = unEscape(res);
}
for (i = 1; i < 20; i++) {
res = codes.getProperty("F" + i);
if (res != null) FunctionKey[i] = unEscape(res);
res = codes.getProperty("SF" + i);
if (res != null) FunctionKeyShift[i] = unEscape(res);
res = codes.getProperty("CF" + i);
if (res != null) FunctionKeyCtrl[i] = unEscape(res);
res = codes.getProperty("AF" + i);
if (res != null) FunctionKeyAlt[i] = unEscape(res);
}
for (i = 0; i < 4; i++) {
res = codes.getProperty(prefixes[i] + "PGUP");
if (res != null) PrevScn[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "PGDOWN");
if (res != null) NextScn[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "END");
if (res != null) KeyEnd[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "HOME");
if (res != null) KeyHome[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "INSERT");
if (res != null) Insert[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "REMOVE");
if (res != null) Remove[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "UP");
if (res != null) KeyUp[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "DOWN");
if (res != null) KeyDown[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "LEFT");
if (res != null) KeyLeft[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "RIGHT");
if (res != null) KeyRight[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "ESCAPE");
if (res != null) Escape[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "BACKSPACE");
if (res != null) BackSpace[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "TAB");
if (res != null) TabKey[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "NUMPLUS");
if (res != null) NUMPlus[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "NUMDECIMAL");
if (res != null) NUMDot[i] = unEscape(res);
}
}
/**
* Set the terminal id used to identify this terminal.
* @param terminalID the id string
*/
public void setTerminalID(String terminalID) {
this.terminalID = terminalID;
if (terminalID.equals("scoansi")) {
FunctionKey[1] = "\u001b[M"; FunctionKey[2] = "\u001b[N";
FunctionKey[3] = "\u001b[O"; FunctionKey[4] = "\u001b[P";
FunctionKey[5] = "\u001b[Q"; FunctionKey[6] = "\u001b[R";
FunctionKey[7] = "\u001b[S"; FunctionKey[8] = "\u001b[T";
FunctionKey[9] = "\u001b[U"; FunctionKey[10] = "\u001b[V";
FunctionKey[11] = "\u001b[W"; FunctionKey[12] = "\u001b[X";
FunctionKey[13] = "\u001b[Y"; FunctionKey[14] = "?";
FunctionKey[15] = "\u001b[a"; FunctionKey[16] = "\u001b[b";
FunctionKey[17] = "\u001b[c"; FunctionKey[18] = "\u001b[d";
FunctionKey[19] = "\u001b[e"; FunctionKey[20] = "\u001b[f";
PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[I";
NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[G";
// more theoretically.
}
}
public void setAnswerBack(String ab) {
this.answerBack = unEscape(ab);
}
/**
* Get the terminal id used to identify this terminal.
*/
public String getTerminalID() {
return terminalID;
}
/**
* A small conveniance method thar converts the string to a byte array
* for sending.
* @param s the string to be sent
*/
private boolean write(String s, boolean doecho) {
if (debug > 2) {
debugStr.append("write(|")
.append(s)
.append("|,")
.append(doecho);
debug(debugStr.toString());
debugStr.setLength(0);
}
if (s == null) // aka the empty string.
return true;
/* NOTE: getBytes() honours some locale, it *CONVERTS* the string.
* However, we output only 7bit stuff towards the target, and *some*
* 8 bit control codes. We must not mess up the latter, so we do hand
* by hand copy.
*/
byte arr[] = new byte[s.length()];
for (int i = 0; i < s.length(); i++) {
arr[i] = (byte) s.charAt(i);
}
write(arr);
if (doecho)
putString(s);
return true;
}
private boolean write(int s, boolean doecho) {
if (debug > 2) {
debugStr.append("write(|")
.append(s)
.append("|,")
.append(doecho);
debug(debugStr.toString());
debugStr.setLength(0);
}
write(s);
// TODO check if character is wide
if (doecho)
putChar((char)s, false, false);
return true;
}
private boolean write(String s) {
return write(s, localecho);
}
// ===================================================================
// the actual terminal emulation code comes here:
// ===================================================================
private String terminalID = "vt320";
private String answerBack = "Use Terminal.answerback to set ...\n";
// X - COLUMNS, Y - ROWS
int R,C;
int attributes = 0;
int Sc,Sr,Sa,Stm,Sbm;
char Sgr,Sgl;
char Sgx[];
int insertmode = 0;
int statusmode = 0;
boolean vt52mode = false;
boolean keypadmode = false; /* false - numeric, true - application */
boolean output8bit = false;
int normalcursor = 0;
boolean moveoutsidemargins = true;
boolean wraparound = true;
boolean sendcrlf = true;
boolean capslock = false;
boolean numlock = false;
int mouserpt = 0;
byte mousebut = 0;
boolean useibmcharset = false;
int lastwaslf = 0;
boolean usedcharsets = false;
private final static char ESC = 27;
private final static char IND = 132;
private final static char NEL = 133;
private final static char RI = 141;
private final static char SS2 = 142;
private final static char SS3 = 143;
private final static char DCS = 144;
private final static char HTS = 136;
private final static char CSI = 155;
private final static char OSC = 157;
private final static int TSTATE_DATA = 0;
private final static int TSTATE_ESC = 1; /* ESC */
private final static int TSTATE_CSI = 2; /* ESC [ */
private final static int TSTATE_DCS = 3; /* ESC P */
private final static int TSTATE_DCEQ = 4; /* ESC [? */
private final static int TSTATE_ESCSQUARE = 5; /* ESC # */
private final static int TSTATE_OSC = 6; /* ESC ] */
private final static int TSTATE_SETG0 = 7; /* ESC (? */
private final static int TSTATE_SETG1 = 8; /* ESC )? */
private final static int TSTATE_SETG2 = 9; /* ESC *? */
private final static int TSTATE_SETG3 = 10; /* ESC +? */
private final static int TSTATE_CSI_DOLLAR = 11; /* ESC [ Pn $ */
private final static int TSTATE_CSI_EX = 12; /* ESC [ ! */
private final static int TSTATE_ESCSPACE = 13; /* ESC <space> */
private final static int TSTATE_VT52X = 14;
private final static int TSTATE_VT52Y = 15;
private final static int TSTATE_CSI_TICKS = 16;
private final static int TSTATE_CSI_EQUAL = 17; /* ESC [ = */
private final static int TSTATE_TITLE = 18; /* xterm title */
/* Keys we support */
public final static int KEY_PAUSE = 1;
public final static int KEY_F1 = 2;
public final static int KEY_F2 = 3;
public final static int KEY_F3 = 4;
public final static int KEY_F4 = 5;
public final static int KEY_F5 = 6;
public final static int KEY_F6 = 7;
public final static int KEY_F7 = 8;
public final static int KEY_F8 = 9;
public final static int KEY_F9 = 10;
public final static int KEY_F10 = 11;
public final static int KEY_F11 = 12;
public final static int KEY_F12 = 13;
public final static int KEY_UP = 14;
public final static int KEY_DOWN =15 ;
public final static int KEY_LEFT = 16;
public final static int KEY_RIGHT = 17;
public final static int KEY_PAGE_DOWN = 18;
public final static int KEY_PAGE_UP = 19;
public final static int KEY_INSERT = 20;
public final static int KEY_DELETE = 21;
public final static int KEY_BACK_SPACE = 22;
public final static int KEY_HOME = 23;
public final static int KEY_END = 24;
public final static int KEY_NUM_LOCK = 25;
public final static int KEY_CAPS_LOCK = 26;
public final static int KEY_SHIFT = 27;
public final static int KEY_CONTROL = 28;
public final static int KEY_ALT = 29;
public final static int KEY_ENTER = 30;
public final static int KEY_NUMPAD0 = 31;
public final static int KEY_NUMPAD1 = 32;
public final static int KEY_NUMPAD2 = 33;
public final static int KEY_NUMPAD3 = 34;
public final static int KEY_NUMPAD4 = 35;
public final static int KEY_NUMPAD5 = 36;
public final static int KEY_NUMPAD6 = 37;
public final static int KEY_NUMPAD7 = 38;
public final static int KEY_NUMPAD8 = 39;
public final static int KEY_NUMPAD9 = 40;
public final static int KEY_DECIMAL = 41;
public final static int KEY_ADD = 42;
public final static int KEY_ESCAPE = 43;
public final static int DELETE_IS_DEL = 0;
public final static int DELETE_IS_BACKSPACE = 1;
/* The graphics charsets
* B - default ASCII
* A - ISO Latin 1
* 0 - DEC SPECIAL
* < - User defined
* ....
*/
char gx[];
char gl; // GL (left charset)
char gr; // GR (right charset)
int onegl; // single shift override for GL.
// Map from scoansi linedrawing to DEC _and_ unicode (for the stuff which
// is not in linedrawing). Got from experimenting with scoadmin.
private final static String scoansi_acs = "Tm7k3x4u?kZl@mYjEnB\u2566DqCtAvM\u2550:\u2551N\u2557I\u2554;\u2557H\u255a0a<\u255d";
// array to store DEC Special -> Unicode mapping
// Unicode DEC Unicode name (DEC name)
private static char DECSPECIAL[] = {
'\u0040', //5f blank
'\u2666', //60 black diamond
'\u2592', //61 grey square
'\u2409', //62 Horizontal tab (ht) pict. for control
'\u240c', //63 Form Feed (ff) pict. for control
'\u240d', //64 Carriage Return (cr) pict. for control
'\u240a', //65 Line Feed (lf) pict. for control
'\u00ba', //66 Masculine ordinal indicator
'\u00b1', //67 Plus or minus sign
'\u2424', //68 New Line (nl) pict. for control
'\u240b', //69 Vertical Tab (vt) pict. for control
'\u2518', //6a Forms light up and left
'\u2510', //6b Forms light down and left
'\u250c', //6c Forms light down and right
'\u2514', //6d Forms light up and right
'\u253c', //6e Forms light vertical and horizontal
'\u2594', //6f Upper 1/8 block (Scan 1)
'\u2580', //70 Upper 1/2 block (Scan 3)
'\u2500', //71 Forms light horizontal or ?em dash? (Scan 5)
'\u25ac', //72 \u25ac black rect. or \u2582 lower 1/4 (Scan 7)
'\u005f', //73 \u005f underscore or \u2581 lower 1/8 (Scan 9)
'\u251c', //74 Forms light vertical and right
'\u2524', //75 Forms light vertical and left
'\u2534', //76 Forms light up and horizontal
'\u252c', //77 Forms light down and horizontal
'\u2502', //78 vertical bar
'\u2264', //79 less than or equal
'\u2265', //7a greater than or equal
'\u00b6', //7b paragraph
'\u2260', //7c not equal
'\u00a3', //7d Pound Sign (british)
'\u00b7' //7e Middle Dot
};
/** Strings to send on function key pressing */
private String Numpad[];
private String FunctionKey[];
private String FunctionKeyShift[];
private String FunctionKeyCtrl[];
private String FunctionKeyAlt[];
private String TabKey[];
private String KeyUp[],KeyDown[],KeyLeft[],KeyRight[];
private String KPMinus, KPComma, KPPeriod, KPEnter;
private String PF1, PF2, PF3, PF4;
private String Help, Do, Find, Select;
private String KeyHome[], KeyEnd[], Insert[], Remove[], PrevScn[], NextScn[];
private String Escape[], BackSpace[], NUMDot[], NUMPlus[];
private String osc,dcs; /* to memorize OSC & DCS control sequence */
/** vt320 state variable (internal) */
private int term_state = TSTATE_DATA;
/** in vms mode, set by Terminal.VMS property */
private boolean vms = false;
/** Tabulators */
private byte[] Tabs;
/** The list of integers as used by CSI */
private int[] DCEvars = new int[30];
private int DCEvar;
/**
* Replace escape code characters (backslash + identifier) with their
* respective codes.
* @param tmp the string to be parsed
* @return a unescaped string
*/
static String unEscape(String tmp) {
int idx = 0, oldidx = 0;
String cmd;
// f.println("unescape("+tmp+")");
cmd = "";
while ((idx = tmp.indexOf('\\', oldidx)) >= 0 &&
++idx <= tmp.length()) {
cmd += tmp.substring(oldidx, idx - 1);
if (idx == tmp.length()) return cmd;
switch (tmp.charAt(idx)) {
case 'b':
cmd += "\b";
break;
case 'e':
cmd += "\u001b";
break;
case 'n':
cmd += "\n";
break;
case 'r':
cmd += "\r";
break;
case 't':
cmd += "\t";
break;
case 'v':
cmd += "\u000b";
break;
case 'a':
cmd += "\u0012";
break;
default :
if ((tmp.charAt(idx) >= '0') && (tmp.charAt(idx) <= '9')) {
int i;
for (i = idx; i < tmp.length(); i++)
if ((tmp.charAt(i) < '0') || (tmp.charAt(i) > '9'))
break;
cmd += (char) Integer.parseInt(tmp.substring(idx, i));
idx = i - 1;
} else
cmd += tmp.substring(idx, ++idx);
break;
}
oldidx = ++idx;
}
if (oldidx <= tmp.length()) cmd += tmp.substring(oldidx);
return cmd;
}
/**
* A small conveniance method thar converts a 7bit string to the 8bit
* version depending on VT52/Output8Bit mode.
*
* @param s the string to be sent
*/
private boolean writeSpecial(String s) {
if (s == null)
return true;
if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == 'O'))) {
if (vt52mode) {
if ((s.charAt(2) >= 'P') && (s.charAt(2) <= 'S')) {
s = "\u001b" + s.substring(2); /* ESC x */
} else {
s = "\u001b?" + s.substring(2); /* ESC ? x */
}
} else {
if (output8bit) {
s = "\u008f" + s.substring(2); /* SS3 x */
} /* else keep string as it is */
}
}
if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == '['))) {
if (output8bit) {
s = "\u009b" + s.substring(2); /* CSI ... */
} /* else keep */
}
return write(s, false);
}
/**
* main keytyping event handler...
*/
public void keyPressed(int keyCode, char keyChar, int modifiers) {
boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0;
boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0;
boolean alt = (modifiers & VDUInput.KEY_ALT) != 0;
if (debug > 1) {
debugStr.append("keyPressed(")
.append(keyCode)
.append(", ")
.append((int)keyChar)
.append(", ")
.append(modifiers)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
}
int xind;
String fmap[];
xind = 0;
fmap = FunctionKey;
if (shift) {
fmap = FunctionKeyShift;
xind = 1;
}
if (control) {
fmap = FunctionKeyCtrl;
xind = 2;
}
if (alt) {
fmap = FunctionKeyAlt;
xind = 3;
}
switch (keyCode) {
case KEY_PAUSE:
if (shift || control)
sendTelnetCommand((byte) 243); // BREAK
break;
case KEY_F1:
writeSpecial(fmap[1]);
break;
case KEY_F2:
writeSpecial(fmap[2]);
break;
case KEY_F3:
writeSpecial(fmap[3]);
break;
case KEY_F4:
writeSpecial(fmap[4]);
break;
case KEY_F5:
writeSpecial(fmap[5]);
break;
case KEY_F6:
writeSpecial(fmap[6]);
break;
case KEY_F7:
writeSpecial(fmap[7]);
break;
case KEY_F8:
writeSpecial(fmap[8]);
break;
case KEY_F9:
writeSpecial(fmap[9]);
break;
case KEY_F10:
writeSpecial(fmap[10]);
break;
case KEY_F11:
writeSpecial(fmap[11]);
break;
case KEY_F12:
writeSpecial(fmap[12]);
break;
case KEY_UP:
writeSpecial(KeyUp[xind]);
break;
case KEY_DOWN:
writeSpecial(KeyDown[xind]);
break;
case KEY_LEFT:
writeSpecial(KeyLeft[xind]);
break;
case KEY_RIGHT:
writeSpecial(KeyRight[xind]);
break;
case KEY_PAGE_DOWN:
writeSpecial(NextScn[xind]);
break;
case KEY_PAGE_UP:
writeSpecial(PrevScn[xind]);
break;
case KEY_INSERT:
writeSpecial(Insert[xind]);
break;
case KEY_DELETE:
writeSpecial(Remove[xind]);
break;
case KEY_BACK_SPACE:
writeSpecial(BackSpace[xind]);
if (localecho) {
if (BackSpace[xind] == "\b") {
putString("\b \b"); // make the last char 'deleted'
} else {
putString(BackSpace[xind]); // echo it
}
}
break;
case KEY_HOME:
writeSpecial(KeyHome[xind]);
break;
case KEY_END:
writeSpecial(KeyEnd[xind]);
break;
case KEY_NUM_LOCK:
if (vms && control) {
writeSpecial(PF1);
}
if (!control)
numlock = !numlock;
break;
case KEY_CAPS_LOCK:
capslock = !capslock;
return;
case KEY_SHIFT:
case KEY_CONTROL:
case KEY_ALT:
return;
default:
break;
}
}
/*
public void keyReleased(KeyEvent evt) {
if (debug > 1) debug("keyReleased("+evt+")");
// ignore
}
*/
/**
* Handle key Typed events for the terminal, this will get
* all normal key types, but no shift/alt/control/numlock.
*/
public void keyTyped(int keyCode, char keyChar, int modifiers) {
boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0;
boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0;
boolean alt = (modifiers & VDUInput.KEY_ALT) != 0;
if (debug > 1) debug("keyTyped("+keyCode+", "+(int)keyChar+", "+modifiers+")");
if (keyChar == '\t') {
if (shift) {
write(TabKey[1], false);
} else {
if (control) {
write(TabKey[2], false);
} else {
if (alt) {
write(TabKey[3], false);
} else {
write(TabKey[0], false);
}
}
}
return;
}
if (alt) {
write(((char) (keyChar | 0x80)));
return;
}
if (((keyCode == KEY_ENTER) || (keyChar == 10))
&& !control) {
write('\r');
if (localecho) putString("\r\n"); // bad hack
return;
}
if ((keyCode == 10) && !control) {
debug("Sending \\r");
write('\r');
return;
}
// FIXME: on german PC keyboards you have to use Alt-Ctrl-q to get an @,
// so we can't just use it here... will probably break some other VMS
// codes. -Marcus
// if(((!vms && keyChar == '2') || keyChar == '@' || keyChar == ' ')
// && control)
if (((!vms && keyChar == '2') || keyChar == ' ') && control)
write(0);
if (vms) {
if (keyChar == 127 && !control) {
if (shift)
writeSpecial(Insert[0]); // VMS shift delete = insert
else
writeSpecial(Remove[0]); // VMS delete = remove
return;
} else if (control)
switch (keyChar) {
case '0':
writeSpecial(Numpad[0]);
return;
case '1':
writeSpecial(Numpad[1]);
return;
case '2':
writeSpecial(Numpad[2]);
return;
case '3':
writeSpecial(Numpad[3]);
return;
case '4':
writeSpecial(Numpad[4]);
return;
case '5':
writeSpecial(Numpad[5]);
return;
case '6':
writeSpecial(Numpad[6]);
return;
case '7':
writeSpecial(Numpad[7]);
return;
case '8':
writeSpecial(Numpad[8]);
return;
case '9':
writeSpecial(Numpad[9]);
return;
case '.':
writeSpecial(KPPeriod);
return;
case '-':
case 31:
writeSpecial(KPMinus);
return;
case '+':
writeSpecial(KPComma);
return;
case 10:
writeSpecial(KPEnter);
return;
case '/':
writeSpecial(PF2);
return;
case '*':
writeSpecial(PF3);
return;
/* NUMLOCK handled in keyPressed */
default:
break;
}
/* Now what does this do and how did it get here. -Marcus
if (shift && keyChar < 32) {
write(PF1+(char)(keyChar + 64));
return;
}
*/
}
// FIXME: not used?
//String fmap[];
int xind;
xind = 0;
//fmap = FunctionKey;
if (shift) {
//fmap = FunctionKeyShift;
xind = 1;
}
if (control) {
//fmap = FunctionKeyCtrl;
xind = 2;
}
if (alt) {
//fmap = FunctionKeyAlt;
xind = 3;
}
if (keyCode == KEY_ESCAPE) {
writeSpecial(Escape[xind]);
return;
}
if ((modifiers & VDUInput.KEY_ACTION) != 0)
switch (keyCode) {
case KEY_NUMPAD0:
writeSpecial(Numpad[0]);
return;
case KEY_NUMPAD1:
writeSpecial(Numpad[1]);
return;
case KEY_NUMPAD2:
writeSpecial(Numpad[2]);
return;
case KEY_NUMPAD3:
writeSpecial(Numpad[3]);
return;
case KEY_NUMPAD4:
writeSpecial(Numpad[4]);
return;
case KEY_NUMPAD5:
writeSpecial(Numpad[5]);
return;
case KEY_NUMPAD6:
writeSpecial(Numpad[6]);
return;
case KEY_NUMPAD7:
writeSpecial(Numpad[7]);
return;
case KEY_NUMPAD8:
writeSpecial(Numpad[8]);
return;
case KEY_NUMPAD9:
writeSpecial(Numpad[9]);
return;
case KEY_DECIMAL:
writeSpecial(NUMDot[xind]);
return;
case KEY_ADD:
writeSpecial(NUMPlus[xind]);
return;
}
if (!((keyChar == 8) || (keyChar == 127) || (keyChar == '\r') || (keyChar == '\n'))) {
write(keyChar);
return;
}
}
private void handle_dcs(String dcs) {
debugStr.append("DCS: ")
.append(dcs);
debug(debugStr.toString());
debugStr.setLength(0);
}
private void handle_osc(String osc) {
if (osc.length() > 2 && osc.substring(0, 2).equals("4;")) {
// Define color palette
String[] colorData = osc.split(";");
try {
int colorIndex = Integer.parseInt(colorData[1]);
if ("rgb:".equals(colorData[2].substring(0, 4))) {
String[] rgb = colorData[2].substring(4).split("/");
int red = Integer.parseInt(rgb[0].substring(0, 2), 16) & 0xFF;
int green = Integer.parseInt(rgb[1].substring(0, 2), 16) & 0xFF;
int blue = Integer.parseInt(rgb[2].substring(0, 2), 16) & 0xFF;
display.setColor(colorIndex, red, green, blue);
}
} catch (Exception e) {
debugStr.append("OSC: invalid color sequence encountered: ")
.append(osc);
debug(debugStr.toString());
debugStr.setLength(0);
}
} else
debug("OSC: " + osc);
}
private final static char unimap[] = {
//#
//# Name: cp437_DOSLatinUS to Unicode table
//# Unicode version: 1.1
//# Table version: 1.1
//# Table format: Format A
//# Date: 03/31/95
//# Authors: Michel Suignard <michelsu@microsoft.com>
//# Lori Hoerth <lorih@microsoft.com>
//# General notes: none
//#
//# Format: Three tab-separated columns
//# Column #1 is the cp1255_WinHebrew code (in hex)
//# Column #2 is the Unicode (in hex as 0xXXXX)
//# Column #3 is the Unicode name (follows a comment sign, '#')
//#
//# The entries are in cp437_DOSLatinUS order
//#
0x0000, // #NULL
0x0001, // #START OF HEADING
0x0002, // #START OF TEXT
0x0003, // #END OF TEXT
0x0004, // #END OF TRANSMISSION
0x0005, // #ENQUIRY
0x0006, // #ACKNOWLEDGE
0x0007, // #BELL
0x0008, // #BACKSPACE
0x0009, // #HORIZONTAL TABULATION
0x000a, // #LINE FEED
0x000b, // #VERTICAL TABULATION
0x000c, // #FORM FEED
0x000d, // #CARRIAGE RETURN
0x000e, // #SHIFT OUT
0x000f, // #SHIFT IN
0x0010, // #DATA LINK ESCAPE
0x0011, // #DEVICE CONTROL ONE
0x0012, // #DEVICE CONTROL TWO
0x0013, // #DEVICE CONTROL THREE
0x0014, // #DEVICE CONTROL FOUR
0x0015, // #NEGATIVE ACKNOWLEDGE
0x0016, // #SYNCHRONOUS IDLE
0x0017, // #END OF TRANSMISSION BLOCK
0x0018, // #CANCEL
0x0019, // #END OF MEDIUM
0x001a, // #SUBSTITUTE
0x001b, // #ESCAPE
0x001c, // #FILE SEPARATOR
0x001d, // #GROUP SEPARATOR
0x001e, // #RECORD SEPARATOR
0x001f, // #UNIT SEPARATOR
0x0020, // #SPACE
0x0021, // #EXCLAMATION MARK
0x0022, // #QUOTATION MARK
0x0023, // #NUMBER SIGN
0x0024, // #DOLLAR SIGN
0x0025, // #PERCENT SIGN
0x0026, // #AMPERSAND
0x0027, // #APOSTROPHE
0x0028, // #LEFT PARENTHESIS
0x0029, // #RIGHT PARENTHESIS
0x002a, // #ASTERISK
0x002b, // #PLUS SIGN
0x002c, // #COMMA
0x002d, // #HYPHEN-MINUS
0x002e, // #FULL STOP
0x002f, // #SOLIDUS
0x0030, // #DIGIT ZERO
0x0031, // #DIGIT ONE
0x0032, // #DIGIT TWO
0x0033, // #DIGIT THREE
0x0034, // #DIGIT FOUR
0x0035, // #DIGIT FIVE
0x0036, // #DIGIT SIX
0x0037, // #DIGIT SEVEN
0x0038, // #DIGIT EIGHT
0x0039, // #DIGIT NINE
0x003a, // #COLON
0x003b, // #SEMICOLON
0x003c, // #LESS-THAN SIGN
0x003d, // #EQUALS SIGN
0x003e, // #GREATER-THAN SIGN
0x003f, // #QUESTION MARK
0x0040, // #COMMERCIAL AT
0x0041, // #LATIN CAPITAL LETTER A
0x0042, // #LATIN CAPITAL LETTER B
0x0043, // #LATIN CAPITAL LETTER C
0x0044, // #LATIN CAPITAL LETTER D
0x0045, // #LATIN CAPITAL LETTER E
0x0046, // #LATIN CAPITAL LETTER F
0x0047, // #LATIN CAPITAL LETTER G
0x0048, // #LATIN CAPITAL LETTER H
0x0049, // #LATIN CAPITAL LETTER I
0x004a, // #LATIN CAPITAL LETTER J
0x004b, // #LATIN CAPITAL LETTER K
0x004c, // #LATIN CAPITAL LETTER L
0x004d, // #LATIN CAPITAL LETTER M
0x004e, // #LATIN CAPITAL LETTER N
0x004f, // #LATIN CAPITAL LETTER O
0x0050, // #LATIN CAPITAL LETTER P
0x0051, // #LATIN CAPITAL LETTER Q
0x0052, // #LATIN CAPITAL LETTER R
0x0053, // #LATIN CAPITAL LETTER S
0x0054, // #LATIN CAPITAL LETTER T
0x0055, // #LATIN CAPITAL LETTER U
0x0056, // #LATIN CAPITAL LETTER V
0x0057, // #LATIN CAPITAL LETTER W
0x0058, // #LATIN CAPITAL LETTER X
0x0059, // #LATIN CAPITAL LETTER Y
0x005a, // #LATIN CAPITAL LETTER Z
0x005b, // #LEFT SQUARE BRACKET
0x005c, // #REVERSE SOLIDUS
0x005d, // #RIGHT SQUARE BRACKET
0x005e, // #CIRCUMFLEX ACCENT
0x005f, // #LOW LINE
0x0060, // #GRAVE ACCENT
0x0061, // #LATIN SMALL LETTER A
0x0062, // #LATIN SMALL LETTER B
0x0063, // #LATIN SMALL LETTER C
0x0064, // #LATIN SMALL LETTER D
0x0065, // #LATIN SMALL LETTER E
0x0066, // #LATIN SMALL LETTER F
0x0067, // #LATIN SMALL LETTER G
0x0068, // #LATIN SMALL LETTER H
0x0069, // #LATIN SMALL LETTER I
0x006a, // #LATIN SMALL LETTER J
0x006b, // #LATIN SMALL LETTER K
0x006c, // #LATIN SMALL LETTER L
0x006d, // #LATIN SMALL LETTER M
0x006e, // #LATIN SMALL LETTER N
0x006f, // #LATIN SMALL LETTER O
0x0070, // #LATIN SMALL LETTER P
0x0071, // #LATIN SMALL LETTER Q
0x0072, // #LATIN SMALL LETTER R
0x0073, // #LATIN SMALL LETTER S
0x0074, // #LATIN SMALL LETTER T
0x0075, // #LATIN SMALL LETTER U
0x0076, // #LATIN SMALL LETTER V
0x0077, // #LATIN SMALL LETTER W
0x0078, // #LATIN SMALL LETTER X
0x0079, // #LATIN SMALL LETTER Y
0x007a, // #LATIN SMALL LETTER Z
0x007b, // #LEFT CURLY BRACKET
0x007c, // #VERTICAL LINE
0x007d, // #RIGHT CURLY BRACKET
0x007e, // #TILDE
0x007f, // #DELETE
0x00c7, // #LATIN CAPITAL LETTER C WITH CEDILLA
0x00fc, // #LATIN SMALL LETTER U WITH DIAERESIS
0x00e9, // #LATIN SMALL LETTER E WITH ACUTE
0x00e2, // #LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4, // #LATIN SMALL LETTER A WITH DIAERESIS
0x00e0, // #LATIN SMALL LETTER A WITH GRAVE
0x00e5, // #LATIN SMALL LETTER A WITH RING ABOVE
0x00e7, // #LATIN SMALL LETTER C WITH CEDILLA
0x00ea, // #LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb, // #LATIN SMALL LETTER E WITH DIAERESIS
0x00e8, // #LATIN SMALL LETTER E WITH GRAVE
0x00ef, // #LATIN SMALL LETTER I WITH DIAERESIS
0x00ee, // #LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ec, // #LATIN SMALL LETTER I WITH GRAVE
0x00c4, // #LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5, // #LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c9, // #LATIN CAPITAL LETTER E WITH ACUTE
0x00e6, // #LATIN SMALL LIGATURE AE
0x00c6, // #LATIN CAPITAL LIGATURE AE
0x00f4, // #LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6, // #LATIN SMALL LETTER O WITH DIAERESIS
0x00f2, // #LATIN SMALL LETTER O WITH GRAVE
0x00fb, // #LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00f9, // #LATIN SMALL LETTER U WITH GRAVE
0x00ff, // #LATIN SMALL LETTER Y WITH DIAERESIS
0x00d6, // #LATIN CAPITAL LETTER O WITH DIAERESIS
0x00dc, // #LATIN CAPITAL LETTER U WITH DIAERESIS
0x00a2, // #CENT SIGN
0x00a3, // #POUND SIGN
0x00a5, // #YEN SIGN
0x20a7, // #PESETA SIGN
0x0192, // #LATIN SMALL LETTER F WITH HOOK
0x00e1, // #LATIN SMALL LETTER A WITH ACUTE
0x00ed, // #LATIN SMALL LETTER I WITH ACUTE
0x00f3, // #LATIN SMALL LETTER O WITH ACUTE
0x00fa, // #LATIN SMALL LETTER U WITH ACUTE
0x00f1, // #LATIN SMALL LETTER N WITH TILDE
0x00d1, // #LATIN CAPITAL LETTER N WITH TILDE
0x00aa, // #FEMININE ORDINAL INDICATOR
0x00ba, // #MASCULINE ORDINAL INDICATOR
0x00bf, // #INVERTED QUESTION MARK
0x2310, // #REVERSED NOT SIGN
0x00ac, // #NOT SIGN
0x00bd, // #VULGAR FRACTION ONE HALF
0x00bc, // #VULGAR FRACTION ONE QUARTER
0x00a1, // #INVERTED EXCLAMATION MARK
0x00ab, // #LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bb, // #RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x2591, // #LIGHT SHADE
0x2592, // #MEDIUM SHADE
0x2593, // #DARK SHADE
0x2502, // #BOX DRAWINGS LIGHT VERTICAL
0x2524, // #BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x2561, // #BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562, // #BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2556, // #BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2555, // #BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2563, // #BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2551, // #BOX DRAWINGS DOUBLE VERTICAL
0x2557, // #BOX DRAWINGS DOUBLE DOWN AND LEFT
0x255d, // #BOX DRAWINGS DOUBLE UP AND LEFT
0x255c, // #BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255b, // #BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x2510, // #BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514, // #BOX DRAWINGS LIGHT UP AND RIGHT
0x2534, // #BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x252c, // #BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x251c, // #BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2500, // #BOX DRAWINGS LIGHT HORIZONTAL
0x253c, // #BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x255e, // #BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f, // #BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x255a, // #BOX DRAWINGS DOUBLE UP AND RIGHT
0x2554, // #BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2569, // #BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x2566, // #BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2560, // #BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2550, // #BOX DRAWINGS DOUBLE HORIZONTAL
0x256c, // #BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2567, // #BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568, // #BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2564, // #BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565, // #BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2559, // #BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x2558, // #BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2552, // #BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553, // #BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x256b, // #BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256a, // #BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x2518, // #BOX DRAWINGS LIGHT UP AND LEFT
0x250c, // #BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2588, // #FULL BLOCK
0x2584, // #LOWER HALF BLOCK
0x258c, // #LEFT HALF BLOCK
0x2590, // #RIGHT HALF BLOCK
0x2580, // #UPPER HALF BLOCK
0x03b1, // #GREEK SMALL LETTER ALPHA
0x00df, // #LATIN SMALL LETTER SHARP S
0x0393, // #GREEK CAPITAL LETTER GAMMA
0x03c0, // #GREEK SMALL LETTER PI
0x03a3, // #GREEK CAPITAL LETTER SIGMA
0x03c3, // #GREEK SMALL LETTER SIGMA
0x00b5, // #MICRO SIGN
0x03c4, // #GREEK SMALL LETTER TAU
0x03a6, // #GREEK CAPITAL LETTER PHI
0x0398, // #GREEK CAPITAL LETTER THETA
0x03a9, // #GREEK CAPITAL LETTER OMEGA
0x03b4, // #GREEK SMALL LETTER DELTA
0x221e, // #INFINITY
0x03c6, // #GREEK SMALL LETTER PHI
0x03b5, // #GREEK SMALL LETTER EPSILON
0x2229, // #INTERSECTION
0x2261, // #IDENTICAL TO
0x00b1, // #PLUS-MINUS SIGN
0x2265, // #GREATER-THAN OR EQUAL TO
0x2264, // #LESS-THAN OR EQUAL TO
0x2320, // #TOP HALF INTEGRAL
0x2321, // #BOTTOM HALF INTEGRAL
0x00f7, // #DIVISION SIGN
0x2248, // #ALMOST EQUAL TO
0x00b0, // #DEGREE SIGN
0x2219, // #BULLET OPERATOR
0x00b7, // #MIDDLE DOT
0x221a, // #SQUARE ROOT
0x207f, // #SUPERSCRIPT LATIN SMALL LETTER N
0x00b2, // #SUPERSCRIPT TWO
0x25a0, // #BLACK SQUARE
0x00a0, // #NO-BREAK SPACE
};
public char map_cp850_unicode(char x) {
if (x >= 0x100)
return x;
return unimap[x];
}
private void _SetCursor(int row, int col) {
int maxr = height - 1;
int tm = getTopMargin();
R = (row < 0)?0: row;
C = (col < 0)?0: (col >= width) ? width - 1 : col;
if (!moveoutsidemargins) {
R += tm;
maxr = getBottomMargin();
}
if (R > maxr) R = maxr;
}
private void putChar(char c, boolean isWide, boolean doshowcursor) {
int rows = this.height; //statusline
int columns = this.width;
// byte msg[];
// if (debug > 4) {
// debugStr.append("putChar(")
// .append(c)
// .append(" [")
// .append((int) c)
// .append("]) at R=")
// .append(R)
// .append(" , C=")
// .append(C)
// .append(", columns=")
// .append(columns)
// .append(", rows=")
// .append(rows);
// debug(debugStr.toString());
// debugStr.setLength(0);
// }
// markLine(R, 1);
// if (c > 255) {
// if (debug > 0)
// debug("char > 255:" + (int) c);
// //return;
// }
switch (term_state) {
case TSTATE_DATA:
/* FIXME: we shouldn't use chars with bit 8 set if ibmcharset.
* probably... but some BBS do anyway...
*/
if (!useibmcharset) {
boolean doneflag = true;
switch (c) {
case OSC:
osc = "";
term_state = TSTATE_OSC;
break;
case RI:
if (R > getTopMargin())
R--;
else
insertLine(R, 1, SCROLL_DOWN);
if (debug > 1)
debug("RI");
break;
case IND:
if (debug > 2) {
debugStr.append("IND at ")
.append(R)
.append(", tm is ")
.append(getTopMargin())
.append(", bm is ")
.append(getBottomMargin());
debug(debugStr.toString());
debugStr.setLength(0);
}
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
if (debug > 1)
debug("IND (at " + R + " )");
break;
case NEL:
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
C = 0;
if (debug > 1)
debug("NEL (at " + R + " )");
break;
case HTS:
Tabs[C] = 1;
if (debug > 1)
debug("HTS");
break;
case DCS:
dcs = "";
term_state = TSTATE_DCS;
break;
default:
doneflag = false;
break;
}
if (doneflag) break;
}
switch (c) {
case SS3:
onegl = 3;
break;
case SS2:
onegl = 2;
break;
case CSI: // should be in the 8bit section, but some BBS use this
DCEvar = 0;
DCEvars[0] = 0;
DCEvars[1] = 0;
DCEvars[2] = 0;
DCEvars[3] = 0;
term_state = TSTATE_CSI;
break;
case ESC:
term_state = TSTATE_ESC;
lastwaslf = 0;
break;
case 5: /* ENQ */
write(answerBack, false);
break;
case 12:
/* FormFeed, Home for the BBS world */
deleteArea(0, 0, columns, rows, attributes);
C = R = 0;
break;
case '\b': /* 8 */
C--;
if (C < 0)
C = 0;
lastwaslf = 0;
break;
case '\t':
do {
// Don't overwrite or insert! TABS are not destructive, but movement!
C++;
} while (C < columns && (Tabs[C] == 0));
lastwaslf = 0;
break;
case '\r': // 13 CR
C = 0;
break;
case '\n': // 10 LF
if (debug > 3)
debug("R= " + R + ", bm " + getBottomMargin() + ", tm=" + getTopMargin() + ", rows=" + rows);
if (!vms) {
if (lastwaslf != 0 && lastwaslf != c) // Ray: I do not understand this logic.
break;
lastwaslf = c;
/*C = 0;*/
}
if (R == getBottomMargin() || R >= rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
break;
case 7:
beep();
break;
case '\016': /* SMACS , as */
/* ^N, Shift out - Put G1 into GL */
gl = 1;
usedcharsets = true;
break;
case '\017': /* RMACS , ae */
/* ^O, Shift in - Put G0 into GL */
gl = 0;
usedcharsets = true;
break;
default:
{
int thisgl = gl;
if (onegl >= 0) {
thisgl = onegl;
onegl = -1;
}
lastwaslf = 0;
if (c < 32) {
if (c != 0)
if (debug > 0)
debug("TSTATE_DATA char: " + ((int) c));
/*break; some BBS really want those characters, like hearst etc. */
if (c == 0) /* print 0 ... you bet */
break;
}
if (C >= columns) {
if (wraparound) {
int bot = rows;
// If we're in the scroll region, check against the bottom margin
if (R <= getBottomMargin() && R >= getTopMargin())
bot = getBottomMargin() + 1;
if (R < bot - 1)
R++;
else {
if (debug > 3) debug("scrolling due to wrap at " + R);
insertLine(R, 1, SCROLL_UP);
}
C = 0;
} else {
// cursor stays on last character.
C = columns - 1;
}
}
boolean mapped = false;
// Mapping if DEC Special is chosen charset
if (usedcharsets) {
if (c >= '\u0020' && c <= '\u007f') {
switch (gx[thisgl]) {
case '0':
// Remap SCOANSI line drawing to VT100 line drawing chars
// for our SCO using customers.
if (terminalID.equals("scoansi") || terminalID.equals("ansi")) {
for (int i = 0; i < scoansi_acs.length(); i += 2) {
if (c == scoansi_acs.charAt(i)) {
c = scoansi_acs.charAt(i + 1);
break;
}
}
}
if (c >= '\u005f' && c <= '\u007e') {
c = DECSPECIAL[(short) c - 0x5f];
mapped = true;
}
break;
case '<': // 'user preferred' is currently 'ISO Latin-1 suppl
c = (char) ((c & 0x7f) | 0x80);
mapped = true;
break;
case 'A':
case 'B': // Latin-1 , ASCII -> fall through
mapped = true;
break;
default:
debug("Unsupported GL mapping: " + gx[thisgl]);
break;
}
}
if (!mapped && (c >= '\u0080' && c <= '\u00ff')) {
switch (gx[gr]) {
case '0':
if (c >= '\u00df' && c <= '\u00fe') {
c = DECSPECIAL[c - '\u00df'];
mapped = true;
}
break;
case '<':
case 'A':
case 'B':
mapped = true;
break;
default:
debug("Unsupported GR mapping: " + gx[gr]);
break;
}
}
}
if (!mapped && useibmcharset)
c = map_cp850_unicode(c);
/*if(true || (statusmode == 0)) { */
if (isWide) {
if (C >= columns - 1) {
if (wraparound) {
int bot = rows;
// If we're in the scroll region, check against the bottom margin
if (R <= getBottomMargin() && R >= getTopMargin())
bot = getBottomMargin() + 1;
if (R < bot - 1)
R++;
else {
if (debug > 3) debug("scrolling due to wrap at " + R);
insertLine(R, 1, SCROLL_UP);
}
C = 0;
} else {
// cursor stays on last wide character.
C = columns - 2;
}
}
}
if (insertmode == 1) {
if (isWide) {
insertChar(C++, R, c, attributes | FULLWIDTH);
insertChar(C, R, ' ', attributes | FULLWIDTH);
} else
insertChar(C, R, c, attributes);
} else {
if (isWide) {
putChar(C++, R, c, attributes | FULLWIDTH);
putChar(C, R, ' ', attributes | FULLWIDTH);
} else
putChar(C, R, c, attributes);
}
/*
} else {
if (insertmode==1) {
insertChar(C, rows, c, attributes);
} else {
putChar(C, rows, c, attributes);
}
}
*/
C++;
break;
}
} /* switch(c) */
break;
case TSTATE_OSC:
if ((c < 0x20) && (c != ESC)) {// NP - No printing character
handle_osc(osc);
term_state = TSTATE_DATA;
break;
}
//but check for vt102 ESC \
if (c == '\\' && osc.charAt(osc.length() - 1) == ESC) {
handle_osc(osc);
term_state = TSTATE_DATA;
break;
}
osc = osc + c;
break;
case TSTATE_ESCSPACE:
term_state = TSTATE_DATA;
switch (c) {
case 'F': /* S7C1T, Disable output of 8-bit controls, use 7-bit */
output8bit = false;
break;
case 'G': /* S8C1T, Enable output of 8-bit control codes*/
output8bit = true;
break;
default:
debug("ESC <space> " + c + " unhandled.");
}
break;
case TSTATE_ESC:
term_state = TSTATE_DATA;
switch (c) {
case ' ':
term_state = TSTATE_ESCSPACE;
break;
case '#':
term_state = TSTATE_ESCSQUARE;
break;
case 'c':
/* Hard terminal reset */
reset();
break;
case '[':
DCEvar = 0;
DCEvars[0] = 0;
DCEvars[1] = 0;
DCEvars[2] = 0;
DCEvars[3] = 0;
term_state = TSTATE_CSI;
break;
case ']':
osc = "";
term_state = TSTATE_OSC;
break;
case 'P':
dcs = "";
term_state = TSTATE_DCS;
break;
case 'A': /* CUU */
R--;
if (R < 0) R = 0;
break;
case 'B': /* CUD */
R++;
if (R >= rows) R = rows - 1;
break;
case 'C':
C++;
if (C >= columns) C = columns - 1;
break;
case 'I': // RI
insertLine(R, 1, SCROLL_DOWN);
break;
case 'E': /* NEL */
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
C = 0;
if (debug > 1)
debug("ESC E (at " + R + ")");
break;
case 'D': /* IND */
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
if (debug > 1)
debug("ESC D (at " + R + " )");
break;
case 'J': /* erase to end of screen */
if (R < rows - 1)
deleteArea(0, R + 1, columns, rows - R - 1, attributes);
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 'K':
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 'M': // RI
debug("ESC M : R is "+R+", tm is "+getTopMargin()+", bm is "+getBottomMargin());
if (R > getTopMargin()) { // just go up 1 line.
R--;
} else { // scroll down
insertLine(R, 1, SCROLL_DOWN);
}
/* else do nothing ; */
if (debug > 2)
debug("ESC M ");
break;
case 'H':
if (debug > 1)
debug("ESC H at " + C);
/* right border probably ...*/
if (C >= columns)
C = columns - 1;
Tabs[C] = 1;
break;
case 'N': // SS2
onegl = 2;
break;
case 'O': // SS3
onegl = 3;
break;
case '=':
/*application keypad*/
if (debug > 0)
debug("ESC =");
keypadmode = true;
break;
case '<': /* vt52 mode off */
vt52mode = false;
break;
case '>': /*normal keypad*/
if (debug > 0)
debug("ESC >");
keypadmode = false;
break;
case '7': /* DECSC: save cursor, attributes */
Sc = C;
Sr = R;
Sgl = gl;
Sgr = gr;
Sa = attributes;
Sgx = new char[4];
for (int i = 0; i < 4; i++) Sgx[i] = gx[i];
if (debug > 1)
debug("ESC 7");
break;
case '8': /* DECRC: restore cursor, attributes */
C = Sc;
R = Sr;
gl = Sgl;
gr = Sgr;
if (Sgx != null)
for (int i = 0; i < 4; i++) gx[i] = Sgx[i];
attributes = Sa;
if (debug > 1)
debug("ESC 8");
break;
case '(': /* Designate G0 Character set (ISO 2022) */
term_state = TSTATE_SETG0;
usedcharsets = true;
break;
case ')': /* Designate G1 character set (ISO 2022) */
term_state = TSTATE_SETG1;
usedcharsets = true;
break;
case '*': /* Designate G2 Character set (ISO 2022) */
term_state = TSTATE_SETG2;
usedcharsets = true;
break;
case '+': /* Designate G3 Character set (ISO 2022) */
term_state = TSTATE_SETG3;
usedcharsets = true;
break;
case '~': /* Locking Shift 1, right */
gr = 1;
usedcharsets = true;
break;
case 'n': /* Locking Shift 2 */
gl = 2;
usedcharsets = true;
break;
case '}': /* Locking Shift 2, right */
gr = 2;
usedcharsets = true;
break;
case 'o': /* Locking Shift 3 */
gl = 3;
usedcharsets = true;
break;
case '|': /* Locking Shift 3, right */
gr = 3;
usedcharsets = true;
break;
case 'Y': /* vt52 cursor address mode , next chars are x,y */
term_state = TSTATE_VT52Y;
break;
case '_':
term_state = TSTATE_TITLE;
break;
case '\\':
// TODO save title
term_state = TSTATE_DATA;
break;
default:
debug("ESC unknown letter: " + c + " (" + ((int) c) + ")");
break;
}
break;
case TSTATE_VT52X:
C = c - 37;
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
term_state = TSTATE_VT52Y;
break;
case TSTATE_VT52Y:
R = c - 37;
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
term_state = TSTATE_DATA;
break;
case TSTATE_SETG0:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC ( " + c + ": G0 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC ( : G0 char set (" + c + " " + ((int) c) + ")");
gx[0] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG1:
if (c != '0' && c != 'A' && c != 'B' && c != '<') {
debug("ESC ) " + c + " (" + ((int) c) + ") :G1 char set?");
} else {
if (debug > 2) debug("ESC ) :G1 char set (" + c + " " + ((int) c) + ")");
gx[1] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG2:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC*:G2 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC*:G2 char set (" + c + " " + ((int) c) + ")");
gx[2] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG3:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC+:G3 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC+:G3 char set (" + c + " " + ((int) c) + ")");
gx[3] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_ESCSQUARE:
switch (c) {
case '8':
for (int i = 0; i < columns; i++)
for (int j = 0; j < rows; j++)
putChar(i, j, 'E', 0);
break;
default:
debug("ESC # " + c + " not supported.");
break;
}
term_state = TSTATE_DATA;
break;
case TSTATE_DCS:
if (c == '\\' && dcs.charAt(dcs.length() - 1) == ESC) {
handle_dcs(dcs);
term_state = TSTATE_DATA;
break;
}
dcs = dcs + c;
break;
case TSTATE_DCEQ:
term_state = TSTATE_DATA;
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_DCEQ;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_DCEQ;
break;
case 's': // XTERM_SAVE missing!
if (true || debug > 1)
debug("ESC [ ? " + DCEvars[0] + " s unimplemented!");
break;
case 'r': // XTERM_RESTORE
if (true || debug > 1)
debug("ESC [ ? " + DCEvars[0] + " r");
/* DEC Mode reset */
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 3: /* 80 columns*/
setScreenSize(80, height, true);
break;
case 4: /* scrolling mode, smooth */
break;
case 5: /* light background */
break;
case 6: /* DECOM (Origin Mode) move inside margins. */
moveoutsidemargins = true;
break;
case 7: /* DECAWM: Autowrap Mode */
wraparound = false;
break;
case 12:/* local echo off */
break;
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report on */
case 1001:
case 1002:
case 1003:
mouserpt = DCEvars[i];
break;
default:
debug("ESC [ ? " + DCEvars[0] + " r, unimplemented!");
}
}
break;
case 'h': // DECSET
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " h");
/* DEC Mode set */
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 1: /* Application cursor keys */
KeyUp[0] = "\u001bOA";
KeyDown[0] = "\u001bOB";
KeyRight[0] = "\u001bOC";
KeyLeft[0] = "\u001bOD";
break;
case 2: /* DECANM */
vt52mode = false;
break;
case 3: /* 132 columns*/
setScreenSize(132, height, true);
break;
case 6: /* DECOM: move inside margins. */
moveoutsidemargins = false;
break;
case 7: /* DECAWM: Autowrap Mode */
wraparound = true;
break;
case 25: /* turn cursor on */
showCursor(true);
break;
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report on */
case 1001:
case 1002:
case 1003:
mouserpt = DCEvars[i];
break;
/* unimplemented stuff, fall through */
/* 4 - scrolling mode, smooth */
/* 5 - light background */
/* 12 - local echo off */
/* 18 - DECPFF - Printer Form Feed Mode -> On */
/* 19 - DECPEX - Printer Extent Mode -> Screen */
default:
debug("ESC [ ? " + DCEvars[0] + " h, unsupported.");
break;
}
}
break;
case 'i': // DEC Printer Control, autoprint, echo screenchars to printer
// This is different to CSI i!
// Also: "Autoprint prints a final display line only when the
// cursor is moved off the line by an autowrap or LF, FF, or
// VT (otherwise do not print the line)."
switch (DCEvars[0]) {
case 1:
if (debug > 1)
debug("CSI ? 1 i : Print line containing cursor");
break;
case 4:
if (debug > 1)
debug("CSI ? 4 i : Start passthrough printing");
break;
case 5:
if (debug > 1)
debug("CSI ? 4 i : Stop passthrough printing");
break;
}
break;
case 'l': //DECRST
/* DEC Mode reset */
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " l");
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 1: /* Application cursor keys */
KeyUp[0] = "\u001b[A";
KeyDown[0] = "\u001b[B";
KeyRight[0] = "\u001b[C";
KeyLeft[0] = "\u001b[D";
break;
case 2: /* DECANM */
vt52mode = true;
break;
case 3: /* 80 columns*/
setScreenSize(80, height, true);
break;
case 6: /* DECOM: move outside margins. */
moveoutsidemargins = true;
break;
case 7: /* DECAWM: Autowrap Mode OFF */
wraparound = false;
break;
case 25: /* turn cursor off */
showCursor(false);
break;
/* Unimplemented stuff: */
/* 4 - scrolling mode, jump */
/* 5 - dark background */
/* 7 - DECAWM - no wrap around mode */
/* 12 - local echo on */
/* 18 - DECPFF - Printer Form Feed Mode -> Off*/
/* 19 - DECPEX - Printer Extent Mode -> Scrolling Region */
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report OFF */
case 1001:
case 1002:
case 1003:
mouserpt = 0;
break;
default:
debug("ESC [ ? " + DCEvars[0] + " l, unsupported.");
break;
}
}
break;
case 'n':
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " n");
switch (DCEvars[0]) {
case 15:
/* printer? no printer. */
write((ESC) + "[?13n", false);
debug("ESC[5n");
break;
default:
debug("ESC [ ? " + DCEvars[0] + " n, unsupported.");
break;
}
break;
default:
debug("ESC [ ? " + DCEvars[0] + " " + c + ", unsupported.");
break;
}
break;
case TSTATE_CSI_EX:
term_state = TSTATE_DATA;
switch (c) {
case ESC:
term_state = TSTATE_ESC;
break;
default:
debug("Unknown character ESC[! character is " + (int) c);
break;
}
break;
case TSTATE_CSI_TICKS:
term_state = TSTATE_DATA;
switch (c) {
case 'p':
debug("Conformance level: " + DCEvars[0] + " (unsupported)," + DCEvars[1]);
if (DCEvars[0] == 61) {
output8bit = false;
break;
}
if (DCEvars[1] == 1) {
output8bit = false;
} else {
output8bit = true; /* 0 or 2 */
}
break;
default:
debug("Unknown ESC [... \"" + c);
break;
}
break;
case TSTATE_CSI_EQUAL:
term_state = TSTATE_DATA;
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_CSI_EQUAL;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_CSI_EQUAL;
break;
case 'F': /* SCO ANSI foreground */
{
int newcolor;
debug("ESC [ = "+DCEvars[0]+" F");
attributes &= ~COLOR_FG;
newcolor = ((DCEvars[0] & 1) << 2) |
(DCEvars[0] & 2) |
((DCEvars[0] & 4) >> 2) ;
attributes |= (newcolor+1) << COLOR_FG_SHIFT;
break;
}
case 'G': /* SCO ANSI background */
{
int newcolor;
debug("ESC [ = "+DCEvars[0]+" G");
attributes &= ~COLOR_BG;
newcolor = ((DCEvars[0] & 1) << 2) |
(DCEvars[0] & 2) |
((DCEvars[0] & 4) >> 2) ;
attributes |= (newcolor+1) << COLOR_BG_SHIFT;
break;
}
default:
debugStr.append("Unknown ESC [ = ");
for (int i=0;i<=DCEvar;i++) {
debugStr.append(DCEvars[i])
.append(',');
}
debugStr.append(c);
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
break;
case TSTATE_CSI_DOLLAR:
term_state = TSTATE_DATA;
switch (c) {
case '}':
debug("Active Status Display now " + DCEvars[0]);
statusmode = DCEvars[0];
break;
/* bad documentation?
case '-':
debug("Set Status Display now "+DCEvars[0]);
break;
*/
case '~':
debug("Status Line mode now " + DCEvars[0]);
break;
default:
debug("UNKNOWN Status Display code " + c + ", with Pn=" + DCEvars[0]);
break;
}
break;
case TSTATE_CSI:
term_state = TSTATE_DATA;
switch (c) {
case '"':
term_state = TSTATE_CSI_TICKS;
break;
case '$':
term_state = TSTATE_CSI_DOLLAR;
break;
case '=':
term_state = TSTATE_CSI_EQUAL;
break;
case '!':
term_state = TSTATE_CSI_EX;
break;
case '?':
DCEvar = 0;
DCEvars[0] = 0;
term_state = TSTATE_DCEQ;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_CSI;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_CSI;
break;
case 'c':/* send primary device attributes */
/* send (ESC[?61c) */
String subcode = "";
if (terminalID.equals("vt320")) subcode = "63;";
if (terminalID.equals("vt220")) subcode = "62;";
if (terminalID.equals("vt100")) subcode = "61;";
write((ESC) + "[?" + subcode + "1;2c", false);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " c");
break;
case 'q':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " q");
break;
case 'g':
/* used for tabsets */
switch (DCEvars[0]) {
case 3:/* clear them */
Tabs = new byte[width];
break;
case 0:
Tabs[C] = 0;
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " g");
break;
case 'h':
switch (DCEvars[0]) {
case 4:
insertmode = 1;
break;
case 20:
debug("Setting CRLF to TRUE");
sendcrlf = true;
break;
default:
debug("unsupported: ESC [ " + DCEvars[0] + " h");
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " h");
break;
case 'i': // Printer Controller mode.
// "Transparent printing sends all output, except the CSI 4 i
// termination string, to the printer and not the screen,
// uses an 8-bit channel if no parity so NUL and DEL will be
// seen by the printer and by the termination recognizer code,
// and all translation and character set selections are
// bypassed."
switch (DCEvars[0]) {
case 0:
if (debug > 1)
debug("CSI 0 i: Print Screen, not implemented.");
break;
case 4:
if (debug > 1)
debug("CSI 4 i: Enable Transparent Printing, not implemented.");
break;
case 5:
if (debug > 1)
debug("CSI 4/5 i: Disable Transparent Printing, not implemented.");
break;
default:
debug("ESC [ " + DCEvars[0] + " i, unimplemented!");
}
break;
case 'l':
switch (DCEvars[0]) {
case 4:
insertmode = 0;
break;
case 20:
debug("Setting CRLF to FALSE");
sendcrlf = false;
break;
default:
debug("ESC [ " + DCEvars[0] + " l, unimplemented!");
break;
}
break;
case 'A': // CUU
{
int limit;
/* FIXME: xterm only cares about 0 and topmargin */
if (R >= getTopMargin()) {
limit = getTopMargin();
} else
limit = 0;
if (DCEvars[0] == 0)
R--;
else
R -= DCEvars[0];
if (R < limit)
R = limit;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " A");
break;
}
case 'B': // CUD
/* cursor down n (1) times */
{
int limit;
if (R <= getBottomMargin()) {
limit = getBottomMargin();
} else
limit = rows - 1;
if (DCEvars[0] == 0)
R++;
else
R += DCEvars[0];
if (R > limit)
R = limit;
else {
if (debug > 2) debug("Not limited.");
}
if (debug > 2) debug("to: " + R);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " B (at C=" + C + ")");
break;
}
case 'C':
if (DCEvars[0] == 0)
DCEvars[0] = 1;
while (DCEvars[0]-- > 0) {
C++;
}
if (C >= columns)
C = columns - 1;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " C");
break;
case 'd': // CVA
R = DCEvars[0];
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " d");
break;
case 'D':
if (DCEvars[0] == 0)
DCEvars[0] = 1;
while (DCEvars[0]-- > 0) {
C--;
}
if (C < 0) C = 0;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " D");
break;
case 'r': // DECSTBM
if (DCEvar > 0) // Ray: Any argument is optional
{
R = DCEvars[1] - 1;
if (R < 0)
R = rows - 1;
else if (R >= rows) {
R = rows - 1;
}
} else
R = rows - 1;
int bot = R;
if (R >= DCEvars[0]) {
R = DCEvars[0] - 1;
if (R < 0)
R = 0;
}
setMargins(R, bot);
_SetCursor(0, 0);
if (debug > 1)
debug("ESC [" + DCEvars[0] + " ; " + DCEvars[1] + " r");
break;
case 'G': /* CUP / cursor absolute column */
C = DCEvars[0];
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
if (debug > 1) debug("ESC [ " + DCEvars[0] + " G");
break;
case 'H': /* CUP / cursor position */
/* gets 2 arguments */
_SetCursor(DCEvars[0] - 1, DCEvars[1] - 1);
if (debug > 2) {
debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " H, moveoutsidemargins " + moveoutsidemargins);
debug(" -> R now " + R + ", C now " + C);
}
break;
case 'f': /* move cursor 2 */
/* gets 2 arguments */
R = DCEvars[0] - 1;
C = DCEvars[1] - 1;
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
if (debug > 2)
debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " f");
break;
case 'S': /* ind aka 'scroll forward' */
if (DCEvars[0] == 0)
insertLine(rows - 1, SCROLL_UP);
else
insertLine(rows - 1, DCEvars[0], SCROLL_UP);
break;
case 'L':
/* insert n lines */
if (DCEvars[0] == 0)
insertLine(R, SCROLL_DOWN);
else
insertLine(R, DCEvars[0], SCROLL_DOWN);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + "" + (c) + " (at R " + R + ")");
break;
case 'T': /* 'ri' aka scroll backward */
if (DCEvars[0] == 0)
insertLine(0, SCROLL_DOWN);
else
insertLine(0, DCEvars[0], SCROLL_DOWN);
break;
case 'M':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + "" + (c) + " at R=" + R);
if (DCEvars[0] == 0)
deleteLine(R);
else
for (int i = 0; i < DCEvars[0]; i++)
deleteLine(R);
break;
case 'K':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " K");
/* clear in line */
switch (DCEvars[0]) {
case 6: /* 97801 uses ESC[6K for delete to end of line */
case 0:/*clear to right*/
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 1:/*clear to the left, including this */
if (C > 0)
deleteArea(0, R, C + 1, 1, attributes);
break;
case 2:/*clear whole line */
deleteArea(0, R, columns, 1, attributes);
break;
}
break;
case 'J':
/* clear below current line */
switch (DCEvars[0]) {
case 0:
if (R < rows - 1)
deleteArea(0, R + 1, columns, rows - R - 1, attributes);
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 1:
if (R > 0)
deleteArea(0, 0, columns, R, attributes);
if (C > 0)
deleteArea(0, R, C + 1, 1, attributes);// include up to and including current
break;
case 2:
deleteArea(0, 0, columns, rows, attributes);
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " J");
break;
case '@':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " @");
for (int i = 0; i < DCEvars[0]; i++)
insertChar(C, R, ' ', attributes);
break;
case 'X':
{
int toerase = DCEvars[0];
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " X, C=" + C + ",R=" + R);
if (toerase == 0)
toerase = 1;
if (toerase + C > columns)
toerase = columns - C;
deleteArea(C, R, toerase, 1, attributes);
// does not change cursor position
break;
}
case 'P':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " P, C=" + C + ",R=" + R);
if (DCEvars[0] == 0) DCEvars[0] = 1;
for (int i = 0; i < DCEvars[0]; i++)
deleteChar(C, R);
break;
case 'n':
switch (DCEvars[0]) {
case 5: /* malfunction? No malfunction. */
writeSpecial((ESC) + "[0n");
if (debug > 1)
debug("ESC[5n");
break;
case 6:
// DO NOT offset R and C by 1! (checked against /usr/X11R6/bin/resize
// FIXME check again.
// FIXME: but vttest thinks different???
writeSpecial((ESC) + "[" + R + ";" + C + "R");
if (debug > 1)
debug("ESC[6n");
break;
default:
if (debug > 0)
debug("ESC [ " + DCEvars[0] + " n??");
break;
}
break;
case 's': /* DECSC - save cursor */
Sc = C;
Sr = R;
Sa = attributes;
if (debug > 3)
debug("ESC[s");
break;
case 'u': /* DECRC - restore cursor */
C = Sc;
R = Sr;
attributes = Sa;
if (debug > 3)
debug("ESC[u");
break;
case 'm': /* attributes as color, bold , blink,*/
if (debug > 3)
debug("ESC [ ");
if (DCEvar == 0 && DCEvars[0] == 0)
attributes = 0;
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 0:
if (DCEvar > 0) {
if (terminalID.equals("scoansi")) {
attributes &= COLOR; /* Keeps color. Strange but true. */
} else {
attributes = 0;
}
}
break;
case 1:
attributes |= BOLD;
attributes &= ~LOW;
break;
case 2:
/* SCO color hack mode */
if (terminalID.equals("scoansi") && ((DCEvar - i) >= 2)) {
int ncolor;
attributes &= ~(COLOR | BOLD);
ncolor = DCEvars[i + 1];
if ((ncolor & 8) == 8)
attributes |= BOLD;
ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2);
attributes |= ((ncolor) + 1) << COLOR_FG_SHIFT;
ncolor = DCEvars[i + 2];
ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2);
attributes |= ((ncolor) + 1) << COLOR_BG_SHIFT;
i += 2;
} else {
attributes |= LOW;
}
break;
case 3: /* italics */
attributes |= INVERT;
break;
case 4:
attributes |= UNDERLINE;
break;
case 7:
attributes |= INVERT;
break;
case 8:
attributes |= INVISIBLE;
break;
case 5: /* blink on */
break;
/* 10 - ANSI X3.64-1979, select primary font, don't display control
* chars, don't set bit 8 on output */
case 10:
gl = 0;
usedcharsets = true;
break;
/* 11 - ANSI X3.64-1979, select second alt. font, display control
* chars, set bit 8 on output */
case 11: /* SMACS , as */
case 12:
gl = 1;
usedcharsets = true;
break;
case 21: /* normal intensity */
attributes &= ~(LOW | BOLD);
break;
case 23: /* italics off */
attributes &= ~INVERT;
break;
case 25: /* blinking off */
break;
case 27:
attributes &= ~INVERT;
break;
case 28:
attributes &= ~INVISIBLE;
break;
case 24:
attributes &= ~UNDERLINE;
break;
case 22:
attributes &= ~BOLD;
break;
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i] - 30) + 1)<< COLOR_FG_SHIFT;
break;
case 38:
if (DCEvars[i+1] == 5) {
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i + 2]) + 1) << COLOR_FG_SHIFT;
i += 2;
}
break;
case 39:
attributes &= ~COLOR_FG;
break;
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
attributes &= ~COLOR_BG;
attributes |= ((DCEvars[i] - 40) + 1) << COLOR_BG_SHIFT;
break;
case 48:
if (DCEvars[i+1] == 5) {
attributes &= ~COLOR_BG;
attributes |= (DCEvars[i + 2] + 1) << COLOR_BG_SHIFT;
i += 2;
}
break;
case 49:
attributes &= ~COLOR_BG;
break;
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i] - 82) + 1) << COLOR_FG_SHIFT;
break;
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 106:
case 107:
attributes &= ~COLOR_BG;
attributes |= ((DCEvars[i] - 92) + 1) << COLOR_BG_SHIFT;
break;
default:
debugStr.append("ESC [ ")
.append(DCEvars[i])
.append(" m unknown...");
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
if (debug > 3) {
debugStr.append(DCEvars[i])
.append(';');
debug(debugStr.toString());
debugStr.setLength(0);
}
}
if (debug > 3) {
debugStr.append(" (attributes = ")
.append(attributes)
.append(")m");
debug(debugStr.toString());
debugStr.setLength(0);
}
break;
default:
debugStr.append("ESC [ unknown letter: ")
.append(c)
.append(" (")
.append((int)c)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
break;
case TSTATE_TITLE:
switch (c) {
case ESC:
term_state = TSTATE_ESC;
break;
default:
// TODO save title
break;
}
break;
default:
term_state = TSTATE_DATA;
break;
}
setCursorPosition(C, R);
}
/* hard reset the terminal */
public void reset() {
gx[0] = 'B';
gx[1] = 'B';
gx[2] = 'B';
gx[3] = 'B';
gl = 0; // default GL to G0
gr = 2; // default GR to G2
onegl = -1; // Single shift override
/* reset tabs */
int nw = width;
if (nw < 132) nw = 132;
Tabs = new byte[nw];
for (int i = 0; i < nw; i += 8) {
Tabs[i] = 1;
}
deleteArea(0, 0, width, height, attributes);
setMargins(0, height);
C = R = 0;
_SetCursor(0, 0);
if (display != null)
display.resetColors();
showCursor(true);
/*FIXME:*/
term_state = TSTATE_DATA;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.mud.terminal;
/**
* @author Kenny Root
* This data was taken from xterm's precompose.c
*/
public class Precomposer {
public final static char precompositions[][] = {
{ 0x226E, 0x003C, 0x0338},
{ 0x2260, 0x003D, 0x0338},
{ 0x226F, 0x003E, 0x0338},
{ 0x00C0, 0x0041, 0x0300},
{ 0x00C1, 0x0041, 0x0301},
{ 0x00C2, 0x0041, 0x0302},
{ 0x00C3, 0x0041, 0x0303},
{ 0x0100, 0x0041, 0x0304},
{ 0x0102, 0x0041, 0x0306},
{ 0x0226, 0x0041, 0x0307},
{ 0x00C4, 0x0041, 0x0308},
{ 0x1EA2, 0x0041, 0x0309},
{ 0x00C5, 0x0041, 0x030A},
{ 0x01CD, 0x0041, 0x030C},
{ 0x0200, 0x0041, 0x030F},
{ 0x0202, 0x0041, 0x0311},
{ 0x1EA0, 0x0041, 0x0323},
{ 0x1E00, 0x0041, 0x0325},
{ 0x0104, 0x0041, 0x0328},
{ 0x1E02, 0x0042, 0x0307},
{ 0x1E04, 0x0042, 0x0323},
{ 0x1E06, 0x0042, 0x0331},
{ 0x0106, 0x0043, 0x0301},
{ 0x0108, 0x0043, 0x0302},
{ 0x010A, 0x0043, 0x0307},
{ 0x010C, 0x0043, 0x030C},
{ 0x00C7, 0x0043, 0x0327},
{ 0x1E0A, 0x0044, 0x0307},
{ 0x010E, 0x0044, 0x030C},
{ 0x1E0C, 0x0044, 0x0323},
{ 0x1E10, 0x0044, 0x0327},
{ 0x1E12, 0x0044, 0x032D},
{ 0x1E0E, 0x0044, 0x0331},
{ 0x00C8, 0x0045, 0x0300},
{ 0x00C9, 0x0045, 0x0301},
{ 0x00CA, 0x0045, 0x0302},
{ 0x1EBC, 0x0045, 0x0303},
{ 0x0112, 0x0045, 0x0304},
{ 0x0114, 0x0045, 0x0306},
{ 0x0116, 0x0045, 0x0307},
{ 0x00CB, 0x0045, 0x0308},
{ 0x1EBA, 0x0045, 0x0309},
{ 0x011A, 0x0045, 0x030C},
{ 0x0204, 0x0045, 0x030F},
{ 0x0206, 0x0045, 0x0311},
{ 0x1EB8, 0x0045, 0x0323},
{ 0x0228, 0x0045, 0x0327},
{ 0x0118, 0x0045, 0x0328},
{ 0x1E18, 0x0045, 0x032D},
{ 0x1E1A, 0x0045, 0x0330},
{ 0x1E1E, 0x0046, 0x0307},
{ 0x01F4, 0x0047, 0x0301},
{ 0x011C, 0x0047, 0x0302},
{ 0x1E20, 0x0047, 0x0304},
{ 0x011E, 0x0047, 0x0306},
{ 0x0120, 0x0047, 0x0307},
{ 0x01E6, 0x0047, 0x030C},
{ 0x0122, 0x0047, 0x0327},
{ 0x0124, 0x0048, 0x0302},
{ 0x1E22, 0x0048, 0x0307},
{ 0x1E26, 0x0048, 0x0308},
{ 0x021E, 0x0048, 0x030C},
{ 0x1E24, 0x0048, 0x0323},
{ 0x1E28, 0x0048, 0x0327},
{ 0x1E2A, 0x0048, 0x032E},
{ 0x00CC, 0x0049, 0x0300},
{ 0x00CD, 0x0049, 0x0301},
{ 0x00CE, 0x0049, 0x0302},
{ 0x0128, 0x0049, 0x0303},
{ 0x012A, 0x0049, 0x0304},
{ 0x012C, 0x0049, 0x0306},
{ 0x0130, 0x0049, 0x0307},
{ 0x00CF, 0x0049, 0x0308},
{ 0x1EC8, 0x0049, 0x0309},
{ 0x01CF, 0x0049, 0x030C},
{ 0x0208, 0x0049, 0x030F},
{ 0x020A, 0x0049, 0x0311},
{ 0x1ECA, 0x0049, 0x0323},
{ 0x012E, 0x0049, 0x0328},
{ 0x1E2C, 0x0049, 0x0330},
{ 0x0134, 0x004A, 0x0302},
{ 0x1E30, 0x004B, 0x0301},
{ 0x01E8, 0x004B, 0x030C},
{ 0x1E32, 0x004B, 0x0323},
{ 0x0136, 0x004B, 0x0327},
{ 0x1E34, 0x004B, 0x0331},
{ 0x0139, 0x004C, 0x0301},
{ 0x013D, 0x004C, 0x030C},
{ 0x1E36, 0x004C, 0x0323},
{ 0x013B, 0x004C, 0x0327},
{ 0x1E3C, 0x004C, 0x032D},
{ 0x1E3A, 0x004C, 0x0331},
{ 0x1E3E, 0x004D, 0x0301},
{ 0x1E40, 0x004D, 0x0307},
{ 0x1E42, 0x004D, 0x0323},
{ 0x01F8, 0x004E, 0x0300},
{ 0x0143, 0x004E, 0x0301},
{ 0x00D1, 0x004E, 0x0303},
{ 0x1E44, 0x004E, 0x0307},
{ 0x0147, 0x004E, 0x030C},
{ 0x1E46, 0x004E, 0x0323},
{ 0x0145, 0x004E, 0x0327},
{ 0x1E4A, 0x004E, 0x032D},
{ 0x1E48, 0x004E, 0x0331},
{ 0x00D2, 0x004F, 0x0300},
{ 0x00D3, 0x004F, 0x0301},
{ 0x00D4, 0x004F, 0x0302},
{ 0x00D5, 0x004F, 0x0303},
{ 0x014C, 0x004F, 0x0304},
{ 0x014E, 0x004F, 0x0306},
{ 0x022E, 0x004F, 0x0307},
{ 0x00D6, 0x004F, 0x0308},
{ 0x1ECE, 0x004F, 0x0309},
{ 0x0150, 0x004F, 0x030B},
{ 0x01D1, 0x004F, 0x030C},
{ 0x020C, 0x004F, 0x030F},
{ 0x020E, 0x004F, 0x0311},
{ 0x01A0, 0x004F, 0x031B},
{ 0x1ECC, 0x004F, 0x0323},
{ 0x01EA, 0x004F, 0x0328},
{ 0x1E54, 0x0050, 0x0301},
{ 0x1E56, 0x0050, 0x0307},
{ 0x0154, 0x0052, 0x0301},
{ 0x1E58, 0x0052, 0x0307},
{ 0x0158, 0x0052, 0x030C},
{ 0x0210, 0x0052, 0x030F},
{ 0x0212, 0x0052, 0x0311},
{ 0x1E5A, 0x0052, 0x0323},
{ 0x0156, 0x0052, 0x0327},
{ 0x1E5E, 0x0052, 0x0331},
{ 0x015A, 0x0053, 0x0301},
{ 0x015C, 0x0053, 0x0302},
{ 0x1E60, 0x0053, 0x0307},
{ 0x0160, 0x0053, 0x030C},
{ 0x1E62, 0x0053, 0x0323},
{ 0x0218, 0x0053, 0x0326},
{ 0x015E, 0x0053, 0x0327},
{ 0x1E6A, 0x0054, 0x0307},
{ 0x0164, 0x0054, 0x030C},
{ 0x1E6C, 0x0054, 0x0323},
{ 0x021A, 0x0054, 0x0326},
{ 0x0162, 0x0054, 0x0327},
{ 0x1E70, 0x0054, 0x032D},
{ 0x1E6E, 0x0054, 0x0331},
{ 0x00D9, 0x0055, 0x0300},
{ 0x00DA, 0x0055, 0x0301},
{ 0x00DB, 0x0055, 0x0302},
{ 0x0168, 0x0055, 0x0303},
{ 0x016A, 0x0055, 0x0304},
{ 0x016C, 0x0055, 0x0306},
{ 0x00DC, 0x0055, 0x0308},
{ 0x1EE6, 0x0055, 0x0309},
{ 0x016E, 0x0055, 0x030A},
{ 0x0170, 0x0055, 0x030B},
{ 0x01D3, 0x0055, 0x030C},
{ 0x0214, 0x0055, 0x030F},
{ 0x0216, 0x0055, 0x0311},
{ 0x01AF, 0x0055, 0x031B},
{ 0x1EE4, 0x0055, 0x0323},
{ 0x1E72, 0x0055, 0x0324},
{ 0x0172, 0x0055, 0x0328},
{ 0x1E76, 0x0055, 0x032D},
{ 0x1E74, 0x0055, 0x0330},
{ 0x1E7C, 0x0056, 0x0303},
{ 0x1E7E, 0x0056, 0x0323},
{ 0x1E80, 0x0057, 0x0300},
{ 0x1E82, 0x0057, 0x0301},
{ 0x0174, 0x0057, 0x0302},
{ 0x1E86, 0x0057, 0x0307},
{ 0x1E84, 0x0057, 0x0308},
{ 0x1E88, 0x0057, 0x0323},
{ 0x1E8A, 0x0058, 0x0307},
{ 0x1E8C, 0x0058, 0x0308},
{ 0x1EF2, 0x0059, 0x0300},
{ 0x00DD, 0x0059, 0x0301},
{ 0x0176, 0x0059, 0x0302},
{ 0x1EF8, 0x0059, 0x0303},
{ 0x0232, 0x0059, 0x0304},
{ 0x1E8E, 0x0059, 0x0307},
{ 0x0178, 0x0059, 0x0308},
{ 0x1EF6, 0x0059, 0x0309},
{ 0x1EF4, 0x0059, 0x0323},
{ 0x0179, 0x005A, 0x0301},
{ 0x1E90, 0x005A, 0x0302},
{ 0x017B, 0x005A, 0x0307},
{ 0x017D, 0x005A, 0x030C},
{ 0x1E92, 0x005A, 0x0323},
{ 0x1E94, 0x005A, 0x0331},
{ 0x00E0, 0x0061, 0x0300},
{ 0x00E1, 0x0061, 0x0301},
{ 0x00E2, 0x0061, 0x0302},
{ 0x00E3, 0x0061, 0x0303},
{ 0x0101, 0x0061, 0x0304},
{ 0x0103, 0x0061, 0x0306},
{ 0x0227, 0x0061, 0x0307},
{ 0x00E4, 0x0061, 0x0308},
{ 0x1EA3, 0x0061, 0x0309},
{ 0x00E5, 0x0061, 0x030A},
{ 0x01CE, 0x0061, 0x030C},
{ 0x0201, 0x0061, 0x030F},
{ 0x0203, 0x0061, 0x0311},
{ 0x1EA1, 0x0061, 0x0323},
{ 0x1E01, 0x0061, 0x0325},
{ 0x0105, 0x0061, 0x0328},
{ 0x1E03, 0x0062, 0x0307},
{ 0x1E05, 0x0062, 0x0323},
{ 0x1E07, 0x0062, 0x0331},
{ 0x0107, 0x0063, 0x0301},
{ 0x0109, 0x0063, 0x0302},
{ 0x010B, 0x0063, 0x0307},
{ 0x010D, 0x0063, 0x030C},
{ 0x00E7, 0x0063, 0x0327},
{ 0x1E0B, 0x0064, 0x0307},
{ 0x010F, 0x0064, 0x030C},
{ 0x1E0D, 0x0064, 0x0323},
{ 0x1E11, 0x0064, 0x0327},
{ 0x1E13, 0x0064, 0x032D},
{ 0x1E0F, 0x0064, 0x0331},
{ 0x00E8, 0x0065, 0x0300},
{ 0x00E9, 0x0065, 0x0301},
{ 0x00EA, 0x0065, 0x0302},
{ 0x1EBD, 0x0065, 0x0303},
{ 0x0113, 0x0065, 0x0304},
{ 0x0115, 0x0065, 0x0306},
{ 0x0117, 0x0065, 0x0307},
{ 0x00EB, 0x0065, 0x0308},
{ 0x1EBB, 0x0065, 0x0309},
{ 0x011B, 0x0065, 0x030C},
{ 0x0205, 0x0065, 0x030F},
{ 0x0207, 0x0065, 0x0311},
{ 0x1EB9, 0x0065, 0x0323},
{ 0x0229, 0x0065, 0x0327},
{ 0x0119, 0x0065, 0x0328},
{ 0x1E19, 0x0065, 0x032D},
{ 0x1E1B, 0x0065, 0x0330},
{ 0x1E1F, 0x0066, 0x0307},
{ 0x01F5, 0x0067, 0x0301},
{ 0x011D, 0x0067, 0x0302},
{ 0x1E21, 0x0067, 0x0304},
{ 0x011F, 0x0067, 0x0306},
{ 0x0121, 0x0067, 0x0307},
{ 0x01E7, 0x0067, 0x030C},
{ 0x0123, 0x0067, 0x0327},
{ 0x0125, 0x0068, 0x0302},
{ 0x1E23, 0x0068, 0x0307},
{ 0x1E27, 0x0068, 0x0308},
{ 0x021F, 0x0068, 0x030C},
{ 0x1E25, 0x0068, 0x0323},
{ 0x1E29, 0x0068, 0x0327},
{ 0x1E2B, 0x0068, 0x032E},
{ 0x1E96, 0x0068, 0x0331},
{ 0x00EC, 0x0069, 0x0300},
{ 0x00ED, 0x0069, 0x0301},
{ 0x00EE, 0x0069, 0x0302},
{ 0x0129, 0x0069, 0x0303},
{ 0x012B, 0x0069, 0x0304},
{ 0x012D, 0x0069, 0x0306},
{ 0x00EF, 0x0069, 0x0308},
{ 0x1EC9, 0x0069, 0x0309},
{ 0x01D0, 0x0069, 0x030C},
{ 0x0209, 0x0069, 0x030F},
{ 0x020B, 0x0069, 0x0311},
{ 0x1ECB, 0x0069, 0x0323},
{ 0x012F, 0x0069, 0x0328},
{ 0x1E2D, 0x0069, 0x0330},
{ 0x0135, 0x006A, 0x0302},
{ 0x01F0, 0x006A, 0x030C},
{ 0x1E31, 0x006B, 0x0301},
{ 0x01E9, 0x006B, 0x030C},
{ 0x1E33, 0x006B, 0x0323},
{ 0x0137, 0x006B, 0x0327},
{ 0x1E35, 0x006B, 0x0331},
{ 0x013A, 0x006C, 0x0301},
{ 0x013E, 0x006C, 0x030C},
{ 0x1E37, 0x006C, 0x0323},
{ 0x013C, 0x006C, 0x0327},
{ 0x1E3D, 0x006C, 0x032D},
{ 0x1E3B, 0x006C, 0x0331},
{ 0x1E3F, 0x006D, 0x0301},
{ 0x1E41, 0x006D, 0x0307},
{ 0x1E43, 0x006D, 0x0323},
{ 0x01F9, 0x006E, 0x0300},
{ 0x0144, 0x006E, 0x0301},
{ 0x00F1, 0x006E, 0x0303},
{ 0x1E45, 0x006E, 0x0307},
{ 0x0148, 0x006E, 0x030C},
{ 0x1E47, 0x006E, 0x0323},
{ 0x0146, 0x006E, 0x0327},
{ 0x1E4B, 0x006E, 0x032D},
{ 0x1E49, 0x006E, 0x0331},
{ 0x00F2, 0x006F, 0x0300},
{ 0x00F3, 0x006F, 0x0301},
{ 0x00F4, 0x006F, 0x0302},
{ 0x00F5, 0x006F, 0x0303},
{ 0x014D, 0x006F, 0x0304},
{ 0x014F, 0x006F, 0x0306},
{ 0x022F, 0x006F, 0x0307},
{ 0x00F6, 0x006F, 0x0308},
{ 0x1ECF, 0x006F, 0x0309},
{ 0x0151, 0x006F, 0x030B},
{ 0x01D2, 0x006F, 0x030C},
{ 0x020D, 0x006F, 0x030F},
{ 0x020F, 0x006F, 0x0311},
{ 0x01A1, 0x006F, 0x031B},
{ 0x1ECD, 0x006F, 0x0323},
{ 0x01EB, 0x006F, 0x0328},
{ 0x1E55, 0x0070, 0x0301},
{ 0x1E57, 0x0070, 0x0307},
{ 0x0155, 0x0072, 0x0301},
{ 0x1E59, 0x0072, 0x0307},
{ 0x0159, 0x0072, 0x030C},
{ 0x0211, 0x0072, 0x030F},
{ 0x0213, 0x0072, 0x0311},
{ 0x1E5B, 0x0072, 0x0323},
{ 0x0157, 0x0072, 0x0327},
{ 0x1E5F, 0x0072, 0x0331},
{ 0x015B, 0x0073, 0x0301},
{ 0x015D, 0x0073, 0x0302},
{ 0x1E61, 0x0073, 0x0307},
{ 0x0161, 0x0073, 0x030C},
{ 0x1E63, 0x0073, 0x0323},
{ 0x0219, 0x0073, 0x0326},
{ 0x015F, 0x0073, 0x0327},
{ 0x1E6B, 0x0074, 0x0307},
{ 0x1E97, 0x0074, 0x0308},
{ 0x0165, 0x0074, 0x030C},
{ 0x1E6D, 0x0074, 0x0323},
{ 0x021B, 0x0074, 0x0326},
{ 0x0163, 0x0074, 0x0327},
{ 0x1E71, 0x0074, 0x032D},
{ 0x1E6F, 0x0074, 0x0331},
{ 0x00F9, 0x0075, 0x0300},
{ 0x00FA, 0x0075, 0x0301},
{ 0x00FB, 0x0075, 0x0302},
{ 0x0169, 0x0075, 0x0303},
{ 0x016B, 0x0075, 0x0304},
{ 0x016D, 0x0075, 0x0306},
{ 0x00FC, 0x0075, 0x0308},
{ 0x1EE7, 0x0075, 0x0309},
{ 0x016F, 0x0075, 0x030A},
{ 0x0171, 0x0075, 0x030B},
{ 0x01D4, 0x0075, 0x030C},
{ 0x0215, 0x0075, 0x030F},
{ 0x0217, 0x0075, 0x0311},
{ 0x01B0, 0x0075, 0x031B},
{ 0x1EE5, 0x0075, 0x0323},
{ 0x1E73, 0x0075, 0x0324},
{ 0x0173, 0x0075, 0x0328},
{ 0x1E77, 0x0075, 0x032D},
{ 0x1E75, 0x0075, 0x0330},
{ 0x1E7D, 0x0076, 0x0303},
{ 0x1E7F, 0x0076, 0x0323},
{ 0x1E81, 0x0077, 0x0300},
{ 0x1E83, 0x0077, 0x0301},
{ 0x0175, 0x0077, 0x0302},
{ 0x1E87, 0x0077, 0x0307},
{ 0x1E85, 0x0077, 0x0308},
{ 0x1E98, 0x0077, 0x030A},
{ 0x1E89, 0x0077, 0x0323},
{ 0x1E8B, 0x0078, 0x0307},
{ 0x1E8D, 0x0078, 0x0308},
{ 0x1EF3, 0x0079, 0x0300},
{ 0x00FD, 0x0079, 0x0301},
{ 0x0177, 0x0079, 0x0302},
{ 0x1EF9, 0x0079, 0x0303},
{ 0x0233, 0x0079, 0x0304},
{ 0x1E8F, 0x0079, 0x0307},
{ 0x00FF, 0x0079, 0x0308},
{ 0x1EF7, 0x0079, 0x0309},
{ 0x1E99, 0x0079, 0x030A},
{ 0x1EF5, 0x0079, 0x0323},
{ 0x017A, 0x007A, 0x0301},
{ 0x1E91, 0x007A, 0x0302},
{ 0x017C, 0x007A, 0x0307},
{ 0x017E, 0x007A, 0x030C},
{ 0x1E93, 0x007A, 0x0323},
{ 0x1E95, 0x007A, 0x0331},
{ 0x1FED, 0x00A8, 0x0300},
{ 0x0385, 0x00A8, 0x0301},
{ 0x1FC1, 0x00A8, 0x0342},
{ 0x1EA6, 0x00C2, 0x0300},
{ 0x1EA4, 0x00C2, 0x0301},
{ 0x1EAA, 0x00C2, 0x0303},
{ 0x1EA8, 0x00C2, 0x0309},
{ 0x01DE, 0x00C4, 0x0304},
{ 0x01FA, 0x00C5, 0x0301},
{ 0x01FC, 0x00C6, 0x0301},
{ 0x01E2, 0x00C6, 0x0304},
{ 0x1E08, 0x00C7, 0x0301},
{ 0x1EC0, 0x00CA, 0x0300},
{ 0x1EBE, 0x00CA, 0x0301},
{ 0x1EC4, 0x00CA, 0x0303},
{ 0x1EC2, 0x00CA, 0x0309},
{ 0x1E2E, 0x00CF, 0x0301},
{ 0x1ED2, 0x00D4, 0x0300},
{ 0x1ED0, 0x00D4, 0x0301},
{ 0x1ED6, 0x00D4, 0x0303},
{ 0x1ED4, 0x00D4, 0x0309},
{ 0x1E4C, 0x00D5, 0x0301},
{ 0x022C, 0x00D5, 0x0304},
{ 0x1E4E, 0x00D5, 0x0308},
{ 0x022A, 0x00D6, 0x0304},
{ 0x01FE, 0x00D8, 0x0301},
{ 0x01DB, 0x00DC, 0x0300},
{ 0x01D7, 0x00DC, 0x0301},
{ 0x01D5, 0x00DC, 0x0304},
{ 0x01D9, 0x00DC, 0x030C},
{ 0x1EA7, 0x00E2, 0x0300},
{ 0x1EA5, 0x00E2, 0x0301},
{ 0x1EAB, 0x00E2, 0x0303},
{ 0x1EA9, 0x00E2, 0x0309},
{ 0x01DF, 0x00E4, 0x0304},
{ 0x01FB, 0x00E5, 0x0301},
{ 0x01FD, 0x00E6, 0x0301},
{ 0x01E3, 0x00E6, 0x0304},
{ 0x1E09, 0x00E7, 0x0301},
{ 0x1EC1, 0x00EA, 0x0300},
{ 0x1EBF, 0x00EA, 0x0301},
{ 0x1EC5, 0x00EA, 0x0303},
{ 0x1EC3, 0x00EA, 0x0309},
{ 0x1E2F, 0x00EF, 0x0301},
{ 0x1ED3, 0x00F4, 0x0300},
{ 0x1ED1, 0x00F4, 0x0301},
{ 0x1ED7, 0x00F4, 0x0303},
{ 0x1ED5, 0x00F4, 0x0309},
{ 0x1E4D, 0x00F5, 0x0301},
{ 0x022D, 0x00F5, 0x0304},
{ 0x1E4F, 0x00F5, 0x0308},
{ 0x022B, 0x00F6, 0x0304},
{ 0x01FF, 0x00F8, 0x0301},
{ 0x01DC, 0x00FC, 0x0300},
{ 0x01D8, 0x00FC, 0x0301},
{ 0x01D6, 0x00FC, 0x0304},
{ 0x01DA, 0x00FC, 0x030C},
{ 0x1EB0, 0x0102, 0x0300},
{ 0x1EAE, 0x0102, 0x0301},
{ 0x1EB4, 0x0102, 0x0303},
{ 0x1EB2, 0x0102, 0x0309},
{ 0x1EB1, 0x0103, 0x0300},
{ 0x1EAF, 0x0103, 0x0301},
{ 0x1EB5, 0x0103, 0x0303},
{ 0x1EB3, 0x0103, 0x0309},
{ 0x1E14, 0x0112, 0x0300},
{ 0x1E16, 0x0112, 0x0301},
{ 0x1E15, 0x0113, 0x0300},
{ 0x1E17, 0x0113, 0x0301},
{ 0x1E50, 0x014C, 0x0300},
{ 0x1E52, 0x014C, 0x0301},
{ 0x1E51, 0x014D, 0x0300},
{ 0x1E53, 0x014D, 0x0301},
{ 0x1E64, 0x015A, 0x0307},
{ 0x1E65, 0x015B, 0x0307},
{ 0x1E66, 0x0160, 0x0307},
{ 0x1E67, 0x0161, 0x0307},
{ 0x1E78, 0x0168, 0x0301},
{ 0x1E79, 0x0169, 0x0301},
{ 0x1E7A, 0x016A, 0x0308},
{ 0x1E7B, 0x016B, 0x0308},
{ 0x1E9B, 0x017F, 0x0307},
{ 0x1EDC, 0x01A0, 0x0300},
{ 0x1EDA, 0x01A0, 0x0301},
{ 0x1EE0, 0x01A0, 0x0303},
{ 0x1EDE, 0x01A0, 0x0309},
{ 0x1EE2, 0x01A0, 0x0323},
{ 0x1EDD, 0x01A1, 0x0300},
{ 0x1EDB, 0x01A1, 0x0301},
{ 0x1EE1, 0x01A1, 0x0303},
{ 0x1EDF, 0x01A1, 0x0309},
{ 0x1EE3, 0x01A1, 0x0323},
{ 0x1EEA, 0x01AF, 0x0300},
{ 0x1EE8, 0x01AF, 0x0301},
{ 0x1EEE, 0x01AF, 0x0303},
{ 0x1EEC, 0x01AF, 0x0309},
{ 0x1EF0, 0x01AF, 0x0323},
{ 0x1EEB, 0x01B0, 0x0300},
{ 0x1EE9, 0x01B0, 0x0301},
{ 0x1EEF, 0x01B0, 0x0303},
{ 0x1EED, 0x01B0, 0x0309},
{ 0x1EF1, 0x01B0, 0x0323},
{ 0x01EE, 0x01B7, 0x030C},
{ 0x01EC, 0x01EA, 0x0304},
{ 0x01ED, 0x01EB, 0x0304},
{ 0x01E0, 0x0226, 0x0304},
{ 0x01E1, 0x0227, 0x0304},
{ 0x1E1C, 0x0228, 0x0306},
{ 0x1E1D, 0x0229, 0x0306},
{ 0x0230, 0x022E, 0x0304},
{ 0x0231, 0x022F, 0x0304},
{ 0x01EF, 0x0292, 0x030C},
{ 0x0344, 0x0308, 0x0301},
{ 0x1FBA, 0x0391, 0x0300},
{ 0x0386, 0x0391, 0x0301},
{ 0x1FB9, 0x0391, 0x0304},
{ 0x1FB8, 0x0391, 0x0306},
{ 0x1F08, 0x0391, 0x0313},
{ 0x1F09, 0x0391, 0x0314},
{ 0x1FBC, 0x0391, 0x0345},
{ 0x1FC8, 0x0395, 0x0300},
{ 0x0388, 0x0395, 0x0301},
{ 0x1F18, 0x0395, 0x0313},
{ 0x1F19, 0x0395, 0x0314},
{ 0x1FCA, 0x0397, 0x0300},
{ 0x0389, 0x0397, 0x0301},
{ 0x1F28, 0x0397, 0x0313},
{ 0x1F29, 0x0397, 0x0314},
{ 0x1FCC, 0x0397, 0x0345},
{ 0x1FDA, 0x0399, 0x0300},
{ 0x038A, 0x0399, 0x0301},
{ 0x1FD9, 0x0399, 0x0304},
{ 0x1FD8, 0x0399, 0x0306},
{ 0x03AA, 0x0399, 0x0308},
{ 0x1F38, 0x0399, 0x0313},
{ 0x1F39, 0x0399, 0x0314},
{ 0x1FF8, 0x039F, 0x0300},
{ 0x038C, 0x039F, 0x0301},
{ 0x1F48, 0x039F, 0x0313},
{ 0x1F49, 0x039F, 0x0314},
{ 0x1FEC, 0x03A1, 0x0314},
{ 0x1FEA, 0x03A5, 0x0300},
{ 0x038E, 0x03A5, 0x0301},
{ 0x1FE9, 0x03A5, 0x0304},
{ 0x1FE8, 0x03A5, 0x0306},
{ 0x03AB, 0x03A5, 0x0308},
{ 0x1F59, 0x03A5, 0x0314},
{ 0x1FFA, 0x03A9, 0x0300},
{ 0x038F, 0x03A9, 0x0301},
{ 0x1F68, 0x03A9, 0x0313},
{ 0x1F69, 0x03A9, 0x0314},
{ 0x1FFC, 0x03A9, 0x0345},
{ 0x1FB4, 0x03AC, 0x0345},
{ 0x1FC4, 0x03AE, 0x0345},
{ 0x1F70, 0x03B1, 0x0300},
{ 0x03AC, 0x03B1, 0x0301},
{ 0x1FB1, 0x03B1, 0x0304},
{ 0x1FB0, 0x03B1, 0x0306},
{ 0x1F00, 0x03B1, 0x0313},
{ 0x1F01, 0x03B1, 0x0314},
{ 0x1FB6, 0x03B1, 0x0342},
{ 0x1FB3, 0x03B1, 0x0345},
{ 0x1F72, 0x03B5, 0x0300},
{ 0x03AD, 0x03B5, 0x0301},
{ 0x1F10, 0x03B5, 0x0313},
{ 0x1F11, 0x03B5, 0x0314},
{ 0x1F74, 0x03B7, 0x0300},
{ 0x03AE, 0x03B7, 0x0301},
{ 0x1F20, 0x03B7, 0x0313},
{ 0x1F21, 0x03B7, 0x0314},
{ 0x1FC6, 0x03B7, 0x0342},
{ 0x1FC3, 0x03B7, 0x0345},
{ 0x1F76, 0x03B9, 0x0300},
{ 0x03AF, 0x03B9, 0x0301},
{ 0x1FD1, 0x03B9, 0x0304},
{ 0x1FD0, 0x03B9, 0x0306},
{ 0x03CA, 0x03B9, 0x0308},
{ 0x1F30, 0x03B9, 0x0313},
{ 0x1F31, 0x03B9, 0x0314},
{ 0x1FD6, 0x03B9, 0x0342},
{ 0x1F78, 0x03BF, 0x0300},
{ 0x03CC, 0x03BF, 0x0301},
{ 0x1F40, 0x03BF, 0x0313},
{ 0x1F41, 0x03BF, 0x0314},
{ 0x1FE4, 0x03C1, 0x0313},
{ 0x1FE5, 0x03C1, 0x0314},
{ 0x1F7A, 0x03C5, 0x0300},
{ 0x03CD, 0x03C5, 0x0301},
{ 0x1FE1, 0x03C5, 0x0304},
{ 0x1FE0, 0x03C5, 0x0306},
{ 0x03CB, 0x03C5, 0x0308},
{ 0x1F50, 0x03C5, 0x0313},
{ 0x1F51, 0x03C5, 0x0314},
{ 0x1FE6, 0x03C5, 0x0342},
{ 0x1F7C, 0x03C9, 0x0300},
{ 0x03CE, 0x03C9, 0x0301},
{ 0x1F60, 0x03C9, 0x0313},
{ 0x1F61, 0x03C9, 0x0314},
{ 0x1FF6, 0x03C9, 0x0342},
{ 0x1FF3, 0x03C9, 0x0345},
{ 0x1FD2, 0x03CA, 0x0300},
{ 0x0390, 0x03CA, 0x0301},
{ 0x1FD7, 0x03CA, 0x0342},
{ 0x1FE2, 0x03CB, 0x0300},
{ 0x03B0, 0x03CB, 0x0301},
{ 0x1FE7, 0x03CB, 0x0342},
{ 0x1FF4, 0x03CE, 0x0345},
{ 0x03D3, 0x03D2, 0x0301},
{ 0x03D4, 0x03D2, 0x0308},
{ 0x0407, 0x0406, 0x0308},
{ 0x04D0, 0x0410, 0x0306},
{ 0x04D2, 0x0410, 0x0308},
{ 0x0403, 0x0413, 0x0301},
{ 0x0400, 0x0415, 0x0300},
{ 0x04D6, 0x0415, 0x0306},
{ 0x0401, 0x0415, 0x0308},
{ 0x04C1, 0x0416, 0x0306},
{ 0x04DC, 0x0416, 0x0308},
{ 0x04DE, 0x0417, 0x0308},
{ 0x040D, 0x0418, 0x0300},
{ 0x04E2, 0x0418, 0x0304},
{ 0x0419, 0x0418, 0x0306},
{ 0x04E4, 0x0418, 0x0308},
{ 0x040C, 0x041A, 0x0301},
{ 0x04E6, 0x041E, 0x0308},
{ 0x04EE, 0x0423, 0x0304},
{ 0x040E, 0x0423, 0x0306},
{ 0x04F0, 0x0423, 0x0308},
{ 0x04F2, 0x0423, 0x030B},
{ 0x04F4, 0x0427, 0x0308},
{ 0x04F8, 0x042B, 0x0308},
{ 0x04EC, 0x042D, 0x0308},
{ 0x04D1, 0x0430, 0x0306},
{ 0x04D3, 0x0430, 0x0308},
{ 0x0453, 0x0433, 0x0301},
{ 0x0450, 0x0435, 0x0300},
{ 0x04D7, 0x0435, 0x0306},
{ 0x0451, 0x0435, 0x0308},
{ 0x04C2, 0x0436, 0x0306},
{ 0x04DD, 0x0436, 0x0308},
{ 0x04DF, 0x0437, 0x0308},
{ 0x045D, 0x0438, 0x0300},
{ 0x04E3, 0x0438, 0x0304},
{ 0x0439, 0x0438, 0x0306},
{ 0x04E5, 0x0438, 0x0308},
{ 0x045C, 0x043A, 0x0301},
{ 0x04E7, 0x043E, 0x0308},
{ 0x04EF, 0x0443, 0x0304},
{ 0x045E, 0x0443, 0x0306},
{ 0x04F1, 0x0443, 0x0308},
{ 0x04F3, 0x0443, 0x030B},
{ 0x04F5, 0x0447, 0x0308},
{ 0x04F9, 0x044B, 0x0308},
{ 0x04ED, 0x044D, 0x0308},
{ 0x0457, 0x0456, 0x0308},
{ 0x0476, 0x0474, 0x030F},
{ 0x0477, 0x0475, 0x030F},
{ 0x04DA, 0x04D8, 0x0308},
{ 0x04DB, 0x04D9, 0x0308},
{ 0x04EA, 0x04E8, 0x0308},
{ 0x04EB, 0x04E9, 0x0308},
{ 0xFB2E, 0x05D0, 0x05B7},
{ 0xFB2F, 0x05D0, 0x05B8},
{ 0xFB30, 0x05D0, 0x05BC},
{ 0xFB31, 0x05D1, 0x05BC},
{ 0xFB4C, 0x05D1, 0x05BF},
{ 0xFB32, 0x05D2, 0x05BC},
{ 0xFB33, 0x05D3, 0x05BC},
{ 0xFB34, 0x05D4, 0x05BC},
{ 0xFB4B, 0x05D5, 0x05B9},
{ 0xFB35, 0x05D5, 0x05BC},
{ 0xFB36, 0x05D6, 0x05BC},
{ 0xFB38, 0x05D8, 0x05BC},
{ 0xFB1D, 0x05D9, 0x05B4},
{ 0xFB39, 0x05D9, 0x05BC},
{ 0xFB3A, 0x05DA, 0x05BC},
{ 0xFB3B, 0x05DB, 0x05BC},
{ 0xFB4D, 0x05DB, 0x05BF},
{ 0xFB3C, 0x05DC, 0x05BC},
{ 0xFB3E, 0x05DE, 0x05BC},
{ 0xFB40, 0x05E0, 0x05BC},
{ 0xFB41, 0x05E1, 0x05BC},
{ 0xFB43, 0x05E3, 0x05BC},
{ 0xFB44, 0x05E4, 0x05BC},
{ 0xFB4E, 0x05E4, 0x05BF},
{ 0xFB46, 0x05E6, 0x05BC},
{ 0xFB47, 0x05E7, 0x05BC},
{ 0xFB48, 0x05E8, 0x05BC},
{ 0xFB49, 0x05E9, 0x05BC},
{ 0xFB2A, 0x05E9, 0x05C1},
{ 0xFB2B, 0x05E9, 0x05C2},
{ 0xFB4A, 0x05EA, 0x05BC},
{ 0xFB1F, 0x05F2, 0x05B7},
{ 0x0622, 0x0627, 0x0653},
{ 0x0623, 0x0627, 0x0654},
{ 0x0625, 0x0627, 0x0655},
{ 0x0624, 0x0648, 0x0654},
{ 0x0626, 0x064A, 0x0654},
{ 0x06C2, 0x06C1, 0x0654},
{ 0x06D3, 0x06D2, 0x0654},
{ 0x06C0, 0x06D5, 0x0654},
{ 0x0958, 0x0915, 0x093C},
{ 0x0959, 0x0916, 0x093C},
{ 0x095A, 0x0917, 0x093C},
{ 0x095B, 0x091C, 0x093C},
{ 0x095C, 0x0921, 0x093C},
{ 0x095D, 0x0922, 0x093C},
{ 0x0929, 0x0928, 0x093C},
{ 0x095E, 0x092B, 0x093C},
{ 0x095F, 0x092F, 0x093C},
{ 0x0931, 0x0930, 0x093C},
{ 0x0934, 0x0933, 0x093C},
{ 0x09DC, 0x09A1, 0x09BC},
{ 0x09DD, 0x09A2, 0x09BC},
{ 0x09DF, 0x09AF, 0x09BC},
{ 0x09CB, 0x09C7, 0x09BE},
{ 0x09CC, 0x09C7, 0x09D7},
{ 0x0A59, 0x0A16, 0x0A3C},
{ 0x0A5A, 0x0A17, 0x0A3C},
{ 0x0A5B, 0x0A1C, 0x0A3C},
{ 0x0A5E, 0x0A2B, 0x0A3C},
{ 0x0A33, 0x0A32, 0x0A3C},
{ 0x0A36, 0x0A38, 0x0A3C},
{ 0x0B5C, 0x0B21, 0x0B3C},
{ 0x0B5D, 0x0B22, 0x0B3C},
{ 0x0B4B, 0x0B47, 0x0B3E},
{ 0x0B48, 0x0B47, 0x0B56},
{ 0x0B4C, 0x0B47, 0x0B57},
{ 0x0B94, 0x0B92, 0x0BD7},
{ 0x0BCA, 0x0BC6, 0x0BBE},
{ 0x0BCC, 0x0BC6, 0x0BD7},
{ 0x0BCB, 0x0BC7, 0x0BBE},
{ 0x0C48, 0x0C46, 0x0C56},
{ 0x0CC0, 0x0CBF, 0x0CD5},
{ 0x0CCA, 0x0CC6, 0x0CC2},
{ 0x0CC7, 0x0CC6, 0x0CD5},
{ 0x0CC8, 0x0CC6, 0x0CD6},
{ 0x0CCB, 0x0CCA, 0x0CD5},
{ 0x0D4A, 0x0D46, 0x0D3E},
{ 0x0D4C, 0x0D46, 0x0D57},
{ 0x0D4B, 0x0D47, 0x0D3E},
{ 0x0DDA, 0x0DD9, 0x0DCA},
{ 0x0DDC, 0x0DD9, 0x0DCF},
{ 0x0DDE, 0x0DD9, 0x0DDF},
{ 0x0DDD, 0x0DDC, 0x0DCA},
{ 0x0F69, 0x0F40, 0x0FB5},
{ 0x0F43, 0x0F42, 0x0FB7},
{ 0x0F4D, 0x0F4C, 0x0FB7},
{ 0x0F52, 0x0F51, 0x0FB7},
{ 0x0F57, 0x0F56, 0x0FB7},
{ 0x0F5C, 0x0F5B, 0x0FB7},
{ 0x0F73, 0x0F71, 0x0F72},
{ 0x0F75, 0x0F71, 0x0F74},
{ 0x0F81, 0x0F71, 0x0F80},
{ 0x0FB9, 0x0F90, 0x0FB5},
{ 0x0F93, 0x0F92, 0x0FB7},
{ 0x0F9D, 0x0F9C, 0x0FB7},
{ 0x0FA2, 0x0FA1, 0x0FB7},
{ 0x0FA7, 0x0FA6, 0x0FB7},
{ 0x0FAC, 0x0FAB, 0x0FB7},
{ 0x0F76, 0x0FB2, 0x0F80},
{ 0x0F78, 0x0FB3, 0x0F80},
{ 0x1026, 0x1025, 0x102E},
{ 0x1B06, 0x1B05, 0x1B35},
{ 0x1B08, 0x1B07, 0x1B35},
{ 0x1B0A, 0x1B09, 0x1B35},
{ 0x1B0C, 0x1B0B, 0x1B35},
{ 0x1B0E, 0x1B0D, 0x1B35},
{ 0x1B12, 0x1B11, 0x1B35},
{ 0x1B3B, 0x1B3A, 0x1B35},
{ 0x1B3D, 0x1B3C, 0x1B35},
{ 0x1B40, 0x1B3E, 0x1B35},
{ 0x1B41, 0x1B3F, 0x1B35},
{ 0x1B43, 0x1B42, 0x1B35},
{ 0x1E38, 0x1E36, 0x0304},
{ 0x1E39, 0x1E37, 0x0304},
{ 0x1E5C, 0x1E5A, 0x0304},
{ 0x1E5D, 0x1E5B, 0x0304},
{ 0x1E68, 0x1E62, 0x0307},
{ 0x1E69, 0x1E63, 0x0307},
{ 0x1EAC, 0x1EA0, 0x0302},
{ 0x1EB6, 0x1EA0, 0x0306},
{ 0x1EAD, 0x1EA1, 0x0302},
{ 0x1EB7, 0x1EA1, 0x0306},
{ 0x1EC6, 0x1EB8, 0x0302},
{ 0x1EC7, 0x1EB9, 0x0302},
{ 0x1ED8, 0x1ECC, 0x0302},
{ 0x1ED9, 0x1ECD, 0x0302},
{ 0x1F02, 0x1F00, 0x0300},
{ 0x1F04, 0x1F00, 0x0301},
{ 0x1F06, 0x1F00, 0x0342},
{ 0x1F80, 0x1F00, 0x0345},
{ 0x1F03, 0x1F01, 0x0300},
{ 0x1F05, 0x1F01, 0x0301},
{ 0x1F07, 0x1F01, 0x0342},
{ 0x1F81, 0x1F01, 0x0345},
{ 0x1F82, 0x1F02, 0x0345},
{ 0x1F83, 0x1F03, 0x0345},
{ 0x1F84, 0x1F04, 0x0345},
{ 0x1F85, 0x1F05, 0x0345},
{ 0x1F86, 0x1F06, 0x0345},
{ 0x1F87, 0x1F07, 0x0345},
{ 0x1F0A, 0x1F08, 0x0300},
{ 0x1F0C, 0x1F08, 0x0301},
{ 0x1F0E, 0x1F08, 0x0342},
{ 0x1F88, 0x1F08, 0x0345},
{ 0x1F0B, 0x1F09, 0x0300},
{ 0x1F0D, 0x1F09, 0x0301},
{ 0x1F0F, 0x1F09, 0x0342},
{ 0x1F89, 0x1F09, 0x0345},
{ 0x1F8A, 0x1F0A, 0x0345},
{ 0x1F8B, 0x1F0B, 0x0345},
{ 0x1F8C, 0x1F0C, 0x0345},
{ 0x1F8D, 0x1F0D, 0x0345},
{ 0x1F8E, 0x1F0E, 0x0345},
{ 0x1F8F, 0x1F0F, 0x0345},
{ 0x1F12, 0x1F10, 0x0300},
{ 0x1F14, 0x1F10, 0x0301},
{ 0x1F13, 0x1F11, 0x0300},
{ 0x1F15, 0x1F11, 0x0301},
{ 0x1F1A, 0x1F18, 0x0300},
{ 0x1F1C, 0x1F18, 0x0301},
{ 0x1F1B, 0x1F19, 0x0300},
{ 0x1F1D, 0x1F19, 0x0301},
{ 0x1F22, 0x1F20, 0x0300},
{ 0x1F24, 0x1F20, 0x0301},
{ 0x1F26, 0x1F20, 0x0342},
{ 0x1F90, 0x1F20, 0x0345},
{ 0x1F23, 0x1F21, 0x0300},
{ 0x1F25, 0x1F21, 0x0301},
{ 0x1F27, 0x1F21, 0x0342},
{ 0x1F91, 0x1F21, 0x0345},
{ 0x1F92, 0x1F22, 0x0345},
{ 0x1F93, 0x1F23, 0x0345},
{ 0x1F94, 0x1F24, 0x0345},
{ 0x1F95, 0x1F25, 0x0345},
{ 0x1F96, 0x1F26, 0x0345},
{ 0x1F97, 0x1F27, 0x0345},
{ 0x1F2A, 0x1F28, 0x0300},
{ 0x1F2C, 0x1F28, 0x0301},
{ 0x1F2E, 0x1F28, 0x0342},
{ 0x1F98, 0x1F28, 0x0345},
{ 0x1F2B, 0x1F29, 0x0300},
{ 0x1F2D, 0x1F29, 0x0301},
{ 0x1F2F, 0x1F29, 0x0342},
{ 0x1F99, 0x1F29, 0x0345},
{ 0x1F9A, 0x1F2A, 0x0345},
{ 0x1F9B, 0x1F2B, 0x0345},
{ 0x1F9C, 0x1F2C, 0x0345},
{ 0x1F9D, 0x1F2D, 0x0345},
{ 0x1F9E, 0x1F2E, 0x0345},
{ 0x1F9F, 0x1F2F, 0x0345},
{ 0x1F32, 0x1F30, 0x0300},
{ 0x1F34, 0x1F30, 0x0301},
{ 0x1F36, 0x1F30, 0x0342},
{ 0x1F33, 0x1F31, 0x0300},
{ 0x1F35, 0x1F31, 0x0301},
{ 0x1F37, 0x1F31, 0x0342},
{ 0x1F3A, 0x1F38, 0x0300},
{ 0x1F3C, 0x1F38, 0x0301},
{ 0x1F3E, 0x1F38, 0x0342},
{ 0x1F3B, 0x1F39, 0x0300},
{ 0x1F3D, 0x1F39, 0x0301},
{ 0x1F3F, 0x1F39, 0x0342},
{ 0x1F42, 0x1F40, 0x0300},
{ 0x1F44, 0x1F40, 0x0301},
{ 0x1F43, 0x1F41, 0x0300},
{ 0x1F45, 0x1F41, 0x0301},
{ 0x1F4A, 0x1F48, 0x0300},
{ 0x1F4C, 0x1F48, 0x0301},
{ 0x1F4B, 0x1F49, 0x0300},
{ 0x1F4D, 0x1F49, 0x0301},
{ 0x1F52, 0x1F50, 0x0300},
{ 0x1F54, 0x1F50, 0x0301},
{ 0x1F56, 0x1F50, 0x0342},
{ 0x1F53, 0x1F51, 0x0300},
{ 0x1F55, 0x1F51, 0x0301},
{ 0x1F57, 0x1F51, 0x0342},
{ 0x1F5B, 0x1F59, 0x0300},
{ 0x1F5D, 0x1F59, 0x0301},
{ 0x1F5F, 0x1F59, 0x0342},
{ 0x1F62, 0x1F60, 0x0300},
{ 0x1F64, 0x1F60, 0x0301},
{ 0x1F66, 0x1F60, 0x0342},
{ 0x1FA0, 0x1F60, 0x0345},
{ 0x1F63, 0x1F61, 0x0300},
{ 0x1F65, 0x1F61, 0x0301},
{ 0x1F67, 0x1F61, 0x0342},
{ 0x1FA1, 0x1F61, 0x0345},
{ 0x1FA2, 0x1F62, 0x0345},
{ 0x1FA3, 0x1F63, 0x0345},
{ 0x1FA4, 0x1F64, 0x0345},
{ 0x1FA5, 0x1F65, 0x0345},
{ 0x1FA6, 0x1F66, 0x0345},
{ 0x1FA7, 0x1F67, 0x0345},
{ 0x1F6A, 0x1F68, 0x0300},
{ 0x1F6C, 0x1F68, 0x0301},
{ 0x1F6E, 0x1F68, 0x0342},
{ 0x1FA8, 0x1F68, 0x0345},
{ 0x1F6B, 0x1F69, 0x0300},
{ 0x1F6D, 0x1F69, 0x0301},
{ 0x1F6F, 0x1F69, 0x0342},
{ 0x1FA9, 0x1F69, 0x0345},
{ 0x1FAA, 0x1F6A, 0x0345},
{ 0x1FAB, 0x1F6B, 0x0345},
{ 0x1FAC, 0x1F6C, 0x0345},
{ 0x1FAD, 0x1F6D, 0x0345},
{ 0x1FAE, 0x1F6E, 0x0345},
{ 0x1FAF, 0x1F6F, 0x0345},
{ 0x1FB2, 0x1F70, 0x0345},
{ 0x1FC2, 0x1F74, 0x0345},
{ 0x1FF2, 0x1F7C, 0x0345},
{ 0x1FB7, 0x1FB6, 0x0345},
{ 0x1FCD, 0x1FBF, 0x0300},
{ 0x1FCE, 0x1FBF, 0x0301},
{ 0x1FCF, 0x1FBF, 0x0342},
{ 0x1FC7, 0x1FC6, 0x0345},
{ 0x1FF7, 0x1FF6, 0x0345},
{ 0x1FDD, 0x1FFE, 0x0300},
{ 0x1FDE, 0x1FFE, 0x0301},
{ 0x1FDF, 0x1FFE, 0x0342},
{ 0x219A, 0x2190, 0x0338},
{ 0x219B, 0x2192, 0x0338},
{ 0x21AE, 0x2194, 0x0338},
{ 0x21CD, 0x21D0, 0x0338},
{ 0x21CF, 0x21D2, 0x0338},
{ 0x21CE, 0x21D4, 0x0338},
{ 0x2204, 0x2203, 0x0338},
{ 0x2209, 0x2208, 0x0338},
{ 0x220C, 0x220B, 0x0338},
{ 0x2224, 0x2223, 0x0338},
{ 0x2226, 0x2225, 0x0338},
{ 0x2241, 0x223C, 0x0338},
{ 0x2244, 0x2243, 0x0338},
{ 0x2247, 0x2245, 0x0338},
{ 0x2249, 0x2248, 0x0338},
{ 0x226D, 0x224D, 0x0338},
{ 0x2262, 0x2261, 0x0338},
{ 0x2270, 0x2264, 0x0338},
{ 0x2271, 0x2265, 0x0338},
{ 0x2274, 0x2272, 0x0338},
{ 0x2275, 0x2273, 0x0338},
{ 0x2278, 0x2276, 0x0338},
{ 0x2279, 0x2277, 0x0338},
{ 0x2280, 0x227A, 0x0338},
{ 0x2281, 0x227B, 0x0338},
{ 0x22E0, 0x227C, 0x0338},
{ 0x22E1, 0x227D, 0x0338},
{ 0x2284, 0x2282, 0x0338},
{ 0x2285, 0x2283, 0x0338},
{ 0x2288, 0x2286, 0x0338},
{ 0x2289, 0x2287, 0x0338},
{ 0x22E2, 0x2291, 0x0338},
{ 0x22E3, 0x2292, 0x0338},
{ 0x22AC, 0x22A2, 0x0338},
{ 0x22AD, 0x22A8, 0x0338},
{ 0x22AE, 0x22A9, 0x0338},
{ 0x22AF, 0x22AB, 0x0338},
{ 0x22EA, 0x22B2, 0x0338},
{ 0x22EB, 0x22B3, 0x0338},
{ 0x22EC, 0x22B4, 0x0338},
{ 0x22ED, 0x22B5, 0x0338},
{ 0x2ADC, 0x2ADD, 0x0338},
{ 0x3094, 0x3046, 0x3099},
{ 0x304C, 0x304B, 0x3099},
{ 0x304E, 0x304D, 0x3099},
{ 0x3050, 0x304F, 0x3099},
{ 0x3052, 0x3051, 0x3099},
{ 0x3054, 0x3053, 0x3099},
{ 0x3056, 0x3055, 0x3099},
{ 0x3058, 0x3057, 0x3099},
{ 0x305A, 0x3059, 0x3099},
{ 0x305C, 0x305B, 0x3099},
{ 0x305E, 0x305D, 0x3099},
{ 0x3060, 0x305F, 0x3099},
{ 0x3062, 0x3061, 0x3099},
{ 0x3065, 0x3064, 0x3099},
{ 0x3067, 0x3066, 0x3099},
{ 0x3069, 0x3068, 0x3099},
{ 0x3070, 0x306F, 0x3099},
{ 0x3071, 0x306F, 0x309A},
{ 0x3073, 0x3072, 0x3099},
{ 0x3074, 0x3072, 0x309A},
{ 0x3076, 0x3075, 0x3099},
{ 0x3077, 0x3075, 0x309A},
{ 0x3079, 0x3078, 0x3099},
{ 0x307A, 0x3078, 0x309A},
{ 0x307C, 0x307B, 0x3099},
{ 0x307D, 0x307B, 0x309A},
{ 0x309E, 0x309D, 0x3099},
{ 0x30F4, 0x30A6, 0x3099},
{ 0x30AC, 0x30AB, 0x3099},
{ 0x30AE, 0x30AD, 0x3099},
{ 0x30B0, 0x30AF, 0x3099},
{ 0x30B2, 0x30B1, 0x3099},
{ 0x30B4, 0x30B3, 0x3099},
{ 0x30B6, 0x30B5, 0x3099},
{ 0x30B8, 0x30B7, 0x3099},
{ 0x30BA, 0x30B9, 0x3099},
{ 0x30BC, 0x30BB, 0x3099},
{ 0x30BE, 0x30BD, 0x3099},
{ 0x30C0, 0x30BF, 0x3099},
{ 0x30C2, 0x30C1, 0x3099},
{ 0x30C5, 0x30C4, 0x3099},
{ 0x30C7, 0x30C6, 0x3099},
{ 0x30C9, 0x30C8, 0x3099},
{ 0x30D0, 0x30CF, 0x3099},
{ 0x30D1, 0x30CF, 0x309A},
{ 0x30D3, 0x30D2, 0x3099},
{ 0x30D4, 0x30D2, 0x309A},
{ 0x30D6, 0x30D5, 0x3099},
{ 0x30D7, 0x30D5, 0x309A},
{ 0x30D9, 0x30D8, 0x3099},
{ 0x30DA, 0x30D8, 0x309A},
{ 0x30DC, 0x30DB, 0x3099},
{ 0x30DD, 0x30DB, 0x309A},
{ 0x30F7, 0x30EF, 0x3099},
{ 0x30F8, 0x30F0, 0x3099},
{ 0x30F9, 0x30F1, 0x3099},
{ 0x30FA, 0x30F2, 0x3099},
{ 0x30FE, 0x30FD, 0x3099},
{ 0xFB2C, 0xFB49, 0x05C1},
{ 0xFB2D, 0xFB49, 0x05C2},
};
private static final int UNICODE_SHIFT = 21;
public static char precompose(char base, char comb) {
int min = 0;
int max = precompositions.length - 1;
int mid;
long sought = base << UNICODE_SHIFT | comb;
long that;
while (max >= min) {
mid = (min + max) / 2;
that = precompositions[mid][1] << UNICODE_SHIFT | precompositions[mid][2];
if (that < sought)
min = mid + 1;
else if (that > sought)
max = mid - 1;
else
return precompositions[mid][0];
}
// No match; return character without combiner
return base;
}
}
|
Java
|
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import java.util.Properties;
/**
* An interface for a terminal that accepts input from keyboard and mouse.
*
* @author Matthias L. Jugel, Marcus Meißner
* @version $Id: VDUInput.java 499 2005-09-29 08:24:54Z leo $
*/
public interface VDUInput {
public final static int KEY_CONTROL = 0x01;
public final static int KEY_SHIFT = 0x02;
public final static int KEY_ALT = 0x04;
public final static int KEY_ACTION = 0x08;
/**
* Direct access to writing data ...
* @param b
*/
void write(byte b[]);
/**
* Terminal is mouse-aware and requires (x,y) coordinates of
* on the terminal (character coordinates) and the button clicked.
* @param x
* @param y
* @param modifiers
*/
void mousePressed(int x, int y, int modifiers);
/**
* Terminal is mouse-aware and requires the coordinates and button
* of the release.
* @param x
* @param y
* @param modifiers
*/
void mouseReleased(int x, int y, int modifiers);
/**
* Override the standard key codes used by the terminal emulation.
* @param codes a properties object containing key code definitions
*/
void setKeyCodes(Properties codes);
/**
* main keytyping event handler...
* @param keyCode the key code
* @param keyChar the character represented by the key
* @param modifiers shift/alt/control modifiers
*/
void keyPressed(int keyCode, char keyChar, int modifiers);
/**
* Handle key Typed events for the terminal, this will get
* all normal key types, but no shift/alt/control/numlock.
* @param keyCode the key code
* @param keyChar the character represented by the key
* @param modifiers shift/alt/control modifiers
*/
void keyTyped(int keyCode, char keyChar, int modifiers);
}
|
Java
|
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.telnet;
import java.io.IOException;
/**
* This is a telnet protocol handler. The handler needs implementations
* for several methods to handle the telnet options and to be able to
* read and write the buffer.
* <P>
* <B>Maintainer:</B> Marcus Meissner
*
* @version $Id: TelnetProtocolHandler.java 503 2005-10-24 07:34:13Z marcus $
* @author Matthias L. Jugel, Marcus Meissner
*/
public abstract class TelnetProtocolHandler {
/** contains the current revision id */
public final static String ID = "$Id: TelnetProtocolHandler.java 503 2005-10-24 07:34:13Z marcus $";
/** debug level */
private final static int debug = 0;
/** temporary buffer for data-telnetstuff-data transformation */
private byte[] tempbuf = new byte[0];
/** the data sent on pressing <RETURN> \n */
private byte[] crlf = new byte[2];
/** the data sent on pressing <LineFeed> \r */
private byte[] cr = new byte[2];
/**
* Create a new telnet protocol handler.
*/
public TelnetProtocolHandler() {
reset();
crlf[0] = 13; crlf[1] = 10;
cr[0] = 13; cr[1] = 0;
}
/**
* Get the current terminal type for TTYPE telnet option.
* @return the string id of the terminal
*/
protected abstract String getTerminalType();
/**
* Get the current window size of the terminal for the
* NAWS telnet option.
* @return the size of the terminal as Dimension
*/
protected abstract int[] getWindowSize();
/**
* Set the local echo option of telnet.
* @param echo true for local echo, false for no local echo
*/
protected abstract void setLocalEcho(boolean echo);
/**
* Generate an EOR (end of record) request. For use by prompt displaying.
*/
protected abstract void notifyEndOfRecord();
/**
* Send data to the remote host.
* @param b array of bytes to send
*/
protected abstract void write(byte[] b) throws IOException;
/**
* Read the charset name from terminal.
*/
protected abstract String getCharsetName();
/**
* Send one byte to the remote host.
* @param b the byte to be sent
* @see #write(byte[] b)
*/
private static byte[] one = new byte[1];
private void write(byte b) throws IOException {
one[0] = b;
write(one);
}
/**
* Reset the protocol handler. This may be necessary after the
* connection was closed or some other problem occured.
*/
public void reset() {
neg_state = 0;
receivedDX = new byte[256];
sentDX = new byte[256];
receivedWX = new byte[256];
sentWX = new byte[256];
}
// ===================================================================
// the actual negotiation handling for the telnet protocol follows:
// ===================================================================
/** state variable for telnet negotiation reader */
private byte neg_state = 0;
/** constants for the negotiation state */
private final static byte STATE_DATA = 0;
private final static byte STATE_IAC = 1;
private final static byte STATE_IACSB = 2;
private final static byte STATE_IACWILL = 3;
private final static byte STATE_IACDO = 4;
private final static byte STATE_IACWONT = 5;
private final static byte STATE_IACDONT = 6;
private final static byte STATE_IACSBIAC = 7;
private final static byte STATE_IACSBDATA = 8;
private final static byte STATE_IACSBDATAIAC = 9;
/** What IAC SB <xx> we are handling right now */
private byte current_sb;
/** current SB negotiation buffer */
private byte[] sbbuf;
/** IAC - init sequence for telnet negotiation. */
private final static byte IAC = (byte)255;
/** [IAC] End Of Record */
private final static byte EOR = (byte)239;
/** [IAC] WILL */
private final static byte WILL = (byte)251;
/** [IAC] WONT */
private final static byte WONT = (byte)252;
/** [IAC] DO */
private final static byte DO = (byte)253;
/** [IAC] DONT */
private final static byte DONT = (byte)254;
/** [IAC] Sub Begin */
private final static byte SB = (byte)250;
/** [IAC] Sub End */
private final static byte SE = (byte)240;
/** Telnet option: binary mode */
private final static byte TELOPT_BINARY= (byte)0; /* binary mode */
/** Telnet option: echo text */
private final static byte TELOPT_ECHO = (byte)1; /* echo on/off */
/** Telnet option: sga */
private final static byte TELOPT_SGA = (byte)3; /* supress go ahead */
/** Telnet option: End Of Record */
private final static byte TELOPT_EOR = (byte)25; /* end of record */
/** Telnet option: Negotiate About Window Size */
private final static byte TELOPT_NAWS = (byte)31; /* NA-WindowSize*/
/** Telnet option: Terminal Type */
private final static byte TELOPT_TTYPE = (byte)24; /* terminal type */
/** Telnet option: CHARSET */
private final static byte TELOPT_CHARSET= (byte)42; /* charset */
private final static byte[] IACWILL = { IAC, WILL };
private final static byte[] IACWONT = { IAC, WONT };
private final static byte[] IACDO = { IAC, DO };
private final static byte[] IACDONT = { IAC, DONT };
private final static byte[] IACSB = { IAC, SB };
private final static byte[] IACSE = { IAC, SE };
private final static byte CHARSET_ACCEPTED = (byte)2;
private final static byte CHARSET_REJECTED = (byte)3;
/** Telnet option qualifier 'IS' */
private final static byte TELQUAL_IS = (byte)0;
/** Telnet option qualifier 'SEND' */
private final static byte TELQUAL_SEND = (byte)1;
/** What IAC DO(NT) request do we have received already ? */
private byte[] receivedDX;
/** What IAC WILL/WONT request do we have received already ? */
private byte[] receivedWX;
/** What IAC DO/DONT request do we have sent already ? */
private byte[] sentDX;
/** What IAC WILL/WONT request do we have sent already ? */
private byte[] sentWX;
/**
* Send a Telnet Escape character (IAC <code>)
*/
public void sendTelnetControl(byte code)
throws IOException {
byte[] b = new byte[2];
b[0] = IAC;
b[1] = code;
write(b);
}
/**
* Send the new Window Size (via NAWS)
*/
public void setWindowSize(int columns,int rows)
throws IOException {
if(debug > 2) System.err.println("sending NAWS");
if (receivedDX[TELOPT_NAWS] != DO) {
System.err.println("not allowed to send NAWS? (DONT NAWS)");
return;
}
write(IAC);write(SB);write(TELOPT_NAWS);
write((byte) (columns >> 8));
write((byte) (columns & 0xff));
write((byte) (rows >> 8));
write((byte) (rows & 0xff));
write(IAC);write(SE);
}
/**
* Handle an incoming IAC SB <type> <bytes> IAC SE
* @param type type of SB
* @param sbata byte array as <bytes>
*/
private void handle_sb(byte type, byte[] sbdata)
throws IOException {
if(debug > 1)
System.err.println("TelnetIO.handle_sb("+type+")");
switch (type) {
case TELOPT_TTYPE:
if (sbdata.length>0 && sbdata[0]==TELQUAL_SEND) {
write(IACSB);write(TELOPT_TTYPE);write(TELQUAL_IS);
/* FIXME: need more logic here if we use
* more than one terminal type
*/
String ttype = getTerminalType();
if(ttype == null) ttype = "dumb";
write(ttype.getBytes());
write(IACSE);
}
break;
case TELOPT_CHARSET:
System.out.println("Got SB CHARSET");
String charsetStr = new String(sbdata, "US-ASCII");
if (charsetStr.startsWith("TTABLE ")) {
charsetStr = charsetStr.substring(7);
}
String[] charsets = charsetStr.split(charsetStr.substring(0,0));
String myCharset = getCharsetName();
for (String charset : charsets) {
if (charset.equals(myCharset)) {
write(IACSB);write(TELOPT_CHARSET);write(CHARSET_ACCEPTED);
write(charset.getBytes());
write(IACSE);
System.out.println("Sent our charset!");
return;
}
}
write(IACSB);write(TELOPT_CHARSET);write(CHARSET_REJECTED);
write(IACSE);
break;
}
}
/**
* Do not send any notifications at startup. We do not know,
* whether the remote client understands telnet protocol handling,
* so we are silent.
* (This used to send IAC WILL SGA, but this is false for a compliant
* client.)
*/
public void startup() throws IOException {
}
/**
* Transpose special telnet codes like 0xff or newlines to values
* that are compliant to the protocol. This method will also send
* the buffer immediately after transposing the data.
* @param buf the data buffer to be sent
*/
public void transpose(byte[] buf) throws IOException {
int i;
byte[] nbuf,xbuf;
int nbufptr=0;
nbuf = new byte[buf.length*2]; // FIXME: buffer overflows possible
for (i = 0; i < buf.length ; i++) {
switch (buf[i]) {
// Escape IAC twice in stream ... to be telnet protocol compliant
// this is there in binary and non-binary mode.
case IAC:
nbuf[nbufptr++]=IAC;
nbuf[nbufptr++]=IAC;
break;
// We need to heed RFC 854. LF (\n) is 10, CR (\r) is 13
// we assume that the Terminal sends \n for lf+cr and \r for just cr
// linefeed+carriage return is CR LF */
case 10: // \n
if (receivedDX[TELOPT_BINARY + 128 ] != DO) {
while (nbuf.length - nbufptr < crlf.length) {
xbuf = new byte[nbuf.length*2];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
nbuf = xbuf;
}
for (int j=0;j<crlf.length;j++)
nbuf[nbufptr++]=crlf[j];
break;
} else {
// copy verbatim in binary mode.
nbuf[nbufptr++]=buf[i];
}
break;
// carriage return is CR NUL */
case 13: // \r
if (receivedDX[TELOPT_BINARY + 128 ] != DO) {
while (nbuf.length - nbufptr < cr.length) {
xbuf = new byte[nbuf.length*2];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
nbuf = xbuf;
}
for (int j=0;j<cr.length;j++)
nbuf[nbufptr++]=cr[j];
} else {
// copy verbatim in binary mode.
nbuf[nbufptr++]=buf[i];
}
break;
// all other characters are just copied
default:
nbuf[nbufptr++]=buf[i];
break;
}
}
xbuf = new byte[nbufptr];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
write(xbuf);
}
public void setCRLF(String xcrlf) { crlf = xcrlf.getBytes(); }
public void setCR(String xcr) { cr = xcr.getBytes(); }
/**
* Handle telnet protocol negotiation. The buffer will be parsed
* and necessary actions are taken according to the telnet protocol.
* See <A HREF="RFC-Telnet-URL">RFC-Telnet</A>
* @param nbuf the byte buffer put out after negotiation
* @return number of bytes processed, 0 for none, and -1 for end of buffer.
*/
public int negotiate(byte nbuf[], int offset)
throws IOException
{
int count = tempbuf.length;
byte[] buf = tempbuf;
byte sendbuf[] = new byte[3];
byte b,reply;
int boffset = 0, noffset = offset;
boolean dobreak = false;
if (count == 0) // buffer is empty.
return -1;
while(!dobreak && (boffset < count) && (noffset < nbuf.length)) {
b=buf[boffset++];
// of course, byte is a signed entity (-128 -> 127)
// but apparently the SGI Netscape 3.0 doesn't seem
// to care and provides happily values up to 255
if (b>=128)
b=(byte)(b-256);
if(debug > 2) {
Byte B = new Byte(b);
System.err.print("byte: " + B.intValue()+ " ");
}
switch (neg_state) {
case STATE_DATA:
if (b==IAC) {
neg_state = STATE_IAC;
dobreak = true; // leave the loop so we can sync.
} else
nbuf[noffset++]=b;
break;
case STATE_IAC:
switch (b) {
case IAC:
if(debug > 2) System.err.print("IAC ");
neg_state = STATE_DATA;
nbuf[noffset++]=IAC;
break;
case WILL:
if(debug > 2) System.err.print("WILL ");
neg_state = STATE_IACWILL;
break;
case WONT:
if(debug > 2) System.err.print("WONT ");
neg_state = STATE_IACWONT;
break;
case DONT:
if(debug > 2) System.err.print("DONT ");
neg_state = STATE_IACDONT;
break;
case DO:
if(debug > 2) System.err.print("DO ");
neg_state = STATE_IACDO;
break;
case EOR:
if(debug > 1) System.err.print("EOR ");
notifyEndOfRecord();
dobreak = true; // leave the loop so we can sync.
neg_state = STATE_DATA;
break;
case SB:
if(debug > 2) System.err.print("SB ");
neg_state = STATE_IACSB;
break;
default:
if(debug > 2) System.err.print("<UNKNOWN "+b+" > ");
neg_state = STATE_DATA;
break;
}
break;
case STATE_IACWILL:
switch(b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = DO;
setLocalEcho(false);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = DO;
break;
case TELOPT_EOR:
if(debug > 2) System.err.println("EOR");
reply = DO;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = DO;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = DONT;
break;
}
if(debug > 1) System.err.println("<"+b+", WILL ="+WILL+">");
if (reply != sentDX[b+128] || WILL != receivedWX[b+128]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentDX[b+128] = reply;
receivedWX[b+128] = WILL;
}
neg_state = STATE_DATA;
break;
case STATE_IACWONT:
switch(b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
setLocalEcho(true);
reply = DONT;
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = DONT;
break;
case TELOPT_EOR:
if(debug > 2) System.err.println("EOR");
reply = DONT;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = DONT;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = DONT;
break;
}
if(reply != sentDX[b+128] || WONT != receivedWX[b+128]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentDX[b+128] = reply;
receivedWX[b+128] = WILL;
}
neg_state = STATE_DATA;
break;
case STATE_IACDO:
switch (b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = WILL;
setLocalEcho(true);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = WILL;
break;
case TELOPT_TTYPE:
if(debug > 2) System.err.println("TTYPE");
reply = WILL;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = WILL;
break;
case TELOPT_NAWS:
if(debug > 2) System.err.println("NAWS");
int[] size = getWindowSize();
receivedDX[b] = DO;
if(size == null) {
// this shouldn't happen
write(IAC);
write(WONT);
write(TELOPT_NAWS);
reply = WONT;
sentWX[b] = WONT;
break;
}
reply = WILL;
sentWX[b] = WILL;
sendbuf[0]=IAC;
sendbuf[1]=WILL;
sendbuf[2]=TELOPT_NAWS;
write(sendbuf);
write(IAC);write(SB);write(TELOPT_NAWS);
write((byte) (size[0] >> 8));
write((byte) (size[0] & 0xff));
write((byte) (size[1] >> 8));
write((byte) (size[1] & 0xff));
write(IAC);write(SE);
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = WONT;
break;
}
if(reply != sentWX[128+b] || DO != receivedDX[128+b]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentWX[b+128] = reply;
receivedDX[b+128] = DO;
}
neg_state = STATE_DATA;
break;
case STATE_IACDONT:
switch (b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = WONT;
setLocalEcho(false);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = WONT;
break;
case TELOPT_NAWS:
if(debug > 2) System.err.println("NAWS");
reply = WONT;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = WONT;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = WONT;
break;
}
if(reply != sentWX[b+128] || DONT != receivedDX[b+128]) {
write(IAC);write(reply);write(b);
sentWX[b+128] = reply;
receivedDX[b+128] = DONT;
}
neg_state = STATE_DATA;
break;
case STATE_IACSBIAC:
if(debug > 2) System.err.println(""+b+" ");
if (b == IAC) {
sbbuf = new byte[0];
current_sb = b;
neg_state = STATE_IACSBDATA;
} else {
System.err.println("(bad) "+b+" ");
neg_state = STATE_DATA;
}
break;
case STATE_IACSB:
if(debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBIAC;
break;
default:
current_sb = b;
sbbuf = new byte[0];
neg_state = STATE_IACSBDATA;
break;
}
break;
case STATE_IACSBDATA:
if (debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBDATAIAC;
break;
default:
byte[] xsb = new byte[sbbuf.length+1];
System.arraycopy(sbbuf,0,xsb,0,sbbuf.length);
sbbuf = xsb;
sbbuf[sbbuf.length-1] = b;
break;
}
break;
case STATE_IACSBDATAIAC:
if (debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBDATA;
byte[] xsb = new byte[sbbuf.length+1];
System.arraycopy(sbbuf,0,xsb,0,sbbuf.length);
sbbuf = xsb;
sbbuf[sbbuf.length-1] = IAC;
break;
case SE:
handle_sb(current_sb,sbbuf);
current_sb = 0;
neg_state = STATE_DATA;
break;
case SB:
handle_sb(current_sb,sbbuf);
neg_state = STATE_IACSB;
break;
default:
neg_state = STATE_DATA;
break;
}
break;
default:
if (debug > 1)
System.err.println("This should not happen: "+neg_state+" ");
neg_state = STATE_DATA;
break;
}
}
// shrink tempbuf to new processed size.
byte[] xb = new byte[count-boffset];
System.arraycopy(tempbuf,boffset,xb,0,count-boffset);
tempbuf = xb;
return noffset - offset;
}
public void inputfeed(byte[] b, int offset, int len) {
byte[] xb = new byte[tempbuf.length+len];
System.arraycopy(tempbuf,0,xb,0,tempbuf.length);
System.arraycopy(b,offset,xb,tempbuf.length,len);
tempbuf = xb;
}
}
|
Java
|
/*
* Copyright (C) 2008 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.intents;
// Version Dec 9, 2008
/**
* Provides OpenIntents actions, extras, and categories used by providers.
* <p>These specifiers extend the standard Android specifiers.</p>
*/
public final class FileManagerIntents {
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
*
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
/**
* Activity Action: Pick a directory through the file manager, or let user
* specify a custom file name.
* Data is the current directory name or directory name suggestion.
* Returns a new directory name as file URI in data.
*
* <p>Constant Value: "org.openintents.action.PICK_DIRECTORY"</p>
*/
public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
/**
* The title to display.
*
* <p>This is shown in the title bar of the file manager.</p>
*
* <p>Constant Value: "org.openintents.extra.TITLE"</p>
*/
public static final String EXTRA_TITLE = "org.openintents.extra.TITLE";
/**
* The text on the button to display.
*
* <p>Depending on the use, it makes sense to set this to "Open" or "Save".</p>
*
* <p>Constant Value: "org.openintents.extra.BUTTON_TEXT"</p>
*/
public static final String EXTRA_BUTTON_TEXT = "org.openintents.extra.BUTTON_TEXT";
}
|
Java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.niochar.charset.additional;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
/* TODO: support direct byte buffers
import org.apache.harmony.nio.AddressUtil;
import org.apache.harmony.niochar.CharsetProviderImpl;
*/
public class IBM437 extends Charset {
public IBM437(String csName, String[] aliases) {
super(csName, aliases);
}
public boolean contains(Charset cs) {
return cs.name().equalsIgnoreCase("IBM367") || cs.name().equalsIgnoreCase("IBM437") || cs.name().equalsIgnoreCase("US-ASCII") ;
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public CharsetEncoder newEncoder() {
return new Encoder(this);
}
private static final class Decoder extends CharsetDecoder{
private Decoder(Charset cs){
super(cs, 1, 1);
}
private native int nDecode(char[] array, int arrPosition, int remaining, long outAddr, int absolutePos);
protected CoderResult decodeLoop(ByteBuffer bb, CharBuffer cb){
int cbRemaining = cb.remaining();
/* TODO: support direct byte buffers
if(CharsetProviderImpl.hasLoadedNatives() && bb.isDirect() && bb.hasRemaining() && cb.hasArray()){
int toProceed = bb.remaining();
int cbPos = cb.position();
int bbPos = bb.position();
boolean throwOverflow = false;
if( cbRemaining < toProceed ) {
toProceed = cbRemaining;
throwOverflow = true;
}
int res = nDecode(cb.array(), cb.arrayOffset()+cbPos, toProceed, AddressUtil.getDirectBufferAddress(bb), bbPos);
bb.position(bbPos+res);
cb.position(cbPos+res);
if(throwOverflow) return CoderResult.OVERFLOW;
}else{
*/
if(bb.hasArray() && cb.hasArray()) {
int rem = bb.remaining();
rem = cbRemaining >= rem ? rem : cbRemaining;
byte[] bArr = bb.array();
char[] cArr = cb.array();
int bStart = bb.position();
int cStart = cb.position();
int i;
for(i=bStart; i<bStart+rem; i++) {
char in = (char)(bArr[i] & 0xFF);
if(in >= 26){
int index = (int)in - 26;
cArr[cStart++] = (char)arr[index];
}else {
cArr[cStart++] = (char)(in & 0xFF);
}
}
bb.position(i);
cb.position(cStart);
if(rem == cbRemaining && bb.hasRemaining()) return CoderResult.OVERFLOW;
} else {
while(bb.hasRemaining()){
if( cbRemaining == 0 ) return CoderResult.OVERFLOW;
char in = (char)(bb.get() & 0xFF);
if(in >= 26){
int index = (int)in - 26;
cb.put(arr[index]);
}else {
cb.put((char)(in & 0xFF));
}
cbRemaining--;
}
/*
}
*/
}
return CoderResult.UNDERFLOW;
}
final static char[] arr = {
0x001C,0x001B,0x007F,0x001D,0x001E,0x001F,
0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027,
0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F,
0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,
0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F,
0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047,
0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F,
0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057,
0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F,
0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067,
0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F,
0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077,
0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x001A,
0x00C7,0x00FC,0x00E9,0x00E2,0x00E4,0x00E0,0x00E5,0x00E7,
0x00EA,0x00EB,0x00E8,0x00EF,0x00EE,0x00EC,0x00C4,0x00C5,
0x00C9,0x00E6,0x00C6,0x00F4,0x00F6,0x00F2,0x00FB,0x00F9,
0x00FF,0x00D6,0x00DC,0x00A2,0x00A3,0x00A5,0x20A7,0x0192,
0x00E1,0x00ED,0x00F3,0x00FA,0x00F1,0x00D1,0x00AA,0x00BA,
0x00BF,0x2310,0x00AC,0x00BD,0x00BC,0x00A1,0x00AB,0x00BB,
0x2591,0x2592,0x2593,0x2502,0x2524,0x2561,0x2562,0x2556,
0x2555,0x2563,0x2551,0x2557,0x255D,0x255C,0x255B,0x2510,
0x2514,0x2534,0x252C,0x251C,0x2500,0x253C,0x255E,0x255F,
0x255A,0x2554,0x2569,0x2566,0x2560,0x2550,0x256C,0x2567,
0x2568,0x2564,0x2565,0x2559,0x2558,0x2552,0x2553,0x256B,
0x256A,0x2518,0x250C,0x2588,0x2584,0x258C,0x2590,0x2580,
0x03B1,0x00DF,0x0393,0x03C0,0x03A3,0x03C3,0x03BC,0x03C4,
0x03A6,0x0398,0x03A9,0x03B4,0x221E,0x03C6,0x03B5,0x2229,
0x2261,0x00B1,0x2265,0x2264,0x2320,0x2321,0x00F7,0x2248,
0x00B0,0x2219,0x00B7,0x221A,0x207F,0x00B2,0x25A0,0x00A0
};
}
private static final class Encoder extends CharsetEncoder{
private Encoder(Charset cs){
super(cs, 1, 1);
}
private native void nEncode(long outAddr, int absolutePos, char[] array, int arrPosition, int[] res);
protected CoderResult encodeLoop(CharBuffer cb, ByteBuffer bb){
int bbRemaining = bb.remaining();
/* TODO: support direct byte buffers
if(CharsetProviderImpl.hasLoadedNatives() && bb.isDirect() && cb.hasRemaining() && cb.hasArray()){
int toProceed = cb.remaining();
int cbPos = cb.position();
int bbPos = bb.position();
boolean throwOverflow = false;
if( bbRemaining < toProceed ) {
toProceed = bbRemaining;
throwOverflow = true;
}
int[] res = {toProceed, 0};
nEncode(AddressUtil.getDirectBufferAddress(bb), bbPos, cb.array(), cb.arrayOffset()+cbPos, res);
if( res[0] <= 0 ) {
bb.position(bbPos-res[0]);
cb.position(cbPos-res[0]);
if(res[1]!=0) {
if(res[1] < 0)
return CoderResult.malformedForLength(-res[1]);
else
return CoderResult.unmappableForLength(res[1]);
}
}else{
bb.position(bbPos+res[0]);
cb.position(cbPos+res[0]);
if(throwOverflow) return CoderResult.OVERFLOW;
}
}else{
*/
if(bb.hasArray() && cb.hasArray()) {
byte[] byteArr = bb.array();
char[] charArr = cb.array();
int rem = cb.remaining();
int byteArrStart = bb.position();
rem = bbRemaining <= rem ? bbRemaining : rem;
int x;
for(x = cb.position(); x < cb.position()+rem; x++) {
char c = charArr[x];
if(c > (char)0x25A0){
if (c >= 0xD800 && c <= 0xDFFF) {
if(x+1 < cb.limit()) {
char c1 = charArr[x+1];
if(c1 >= 0xD800 && c1 <= 0xDFFF) {
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(2);
}
} else {
cb.position(x); bb.position(byteArrStart);
return CoderResult.UNDERFLOW;
}
cb.position(x); bb.position(byteArrStart);
return CoderResult.malformedForLength(1);
}
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}else{
if(c < 0x1A) {
byteArr[byteArrStart++] = (byte)c;
} else {
int index = (int)c >> 8;
index = encodeIndex[index];
if(index < 0) {
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}
index <<= 8;
index += (int)c & 0xFF;
if((byte)arr[index] != 0){
byteArr[byteArrStart++] = (byte)arr[index];
}else{
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}
}
}
}
cb.position(x);
bb.position(byteArrStart);
if(rem == bbRemaining && cb.hasRemaining()) {
return CoderResult.OVERFLOW;
}
} else {
while(cb.hasRemaining()){
if( bbRemaining == 0 ) return CoderResult.OVERFLOW;
char c = cb.get();
if(c > (char)0x25A0){
if (c >= 0xD800 && c <= 0xDFFF) {
if(cb.hasRemaining()) {
char c1 = cb.get();
if(c1 >= 0xD800 && c1 <= 0xDFFF) {
cb.position(cb.position()-2);
return CoderResult.unmappableForLength(2);
} else {
cb.position(cb.position()-1);
}
} else {
cb.position(cb.position()-1);
return CoderResult.UNDERFLOW;
}
cb.position(cb.position()-1);
return CoderResult.malformedForLength(1);
}
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}else{
if(c < 0x1A) {
bb.put((byte)c);
} else {
int index = (int)c >> 8;
index = encodeIndex[index];
if(index < 0) {
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}
index <<= 8;
index += (int)c & 0xFF;
if((byte)arr[index] != 0){
bb.put((byte)arr[index]);
}else{
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}
}
bbRemaining--;
}
}
/* TODO: support direct byte buffers
}
*/
}
return CoderResult.UNDERFLOW;
}
final static char arr[] = {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,
0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x7F,0x1B,0x1A,0x1D,0x1E,0x1F,
0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F,
0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,
0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,
0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,
0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x1C,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xFF,0xAD,0x9B,0x9C,0x00,0x9D,0x00,0x00,0x00,0x00,0xA6,0xAE,0xAA,0x00,0x00,0x00,
0xF8,0xF1,0xFD,0x00,0x00,0x00,0x00,0xFA,0x00,0x00,0xA7,0xAF,0xAC,0xAB,0x00,0xA8,
0x00,0x00,0x00,0x00,0x8E,0x8F,0x92,0x80,0x00,0x90,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xA5,0x00,0x00,0x00,0x00,0x99,0x00,0x00,0x00,0x00,0x00,0x9A,0x00,0x00,0xE1,
0x85,0xA0,0x83,0x00,0x84,0x86,0x91,0x87,0x8A,0x82,0x88,0x89,0x8D,0xA1,0x8C,0x8B,
0x00,0xA4,0x95,0xA2,0x93,0x00,0x94,0xF6,0x00,0x97,0xA3,0x96,0x81,0x00,0x00,0x98,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x9F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xE2,0x00,0x00,0x00,0x00,0xE9,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xE4,0x00,0x00,0xE8,0x00,0x00,0xEA,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xE0,0x00,0x00,0xEB,0xEE,0x00,0x00,0x00,0x00,0x00,0x00,0xE6,0x00,0x00,0x00,
0xE3,0x00,0x00,0xE5,0xE7,0x00,0xED,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFC,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x9E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF9,0xFB,0x00,0x00,0x00,0xEC,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xEF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF7,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xF0,0x00,0x00,0xF3,0xF2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xA9,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xF4,0xF5,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xC4,0x00,0xB3,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDA,0x00,0x00,0x00,
0xBF,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0xD9,0x00,0x00,0x00,0xC3,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC2,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xC1,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC5,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xCD,0xBA,0xD5,0xD6,0xC9,0xB8,0xB7,0xBB,0xD4,0xD3,0xC8,0xBE,0xBD,0xBC,0xC6,0xC7,
0xCC,0xB5,0xB6,0xB9,0xD1,0xD2,0xCB,0xCF,0xD0,0xCA,0xD8,0xD7,0xCE,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xDF,0x00,0x00,0x00,0xDC,0x00,0x00,0x00,0xDB,0x00,0x00,0x00,0xDD,0x00,0x00,0x00,
0xDE,0xB0,0xB1,0xB2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xFE,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
final static int[] encodeIndex = {
0,1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
3,-1,4,5,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.util.Arrays;
import java.util.List;
import org.connectbot.util.Colors;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.UberColorPickerDialog;
import org.connectbot.util.UberColorPickerDialog.OnColorChangedListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* @author Kenny Root
*
*/
public class ColorsActivity extends Activity implements OnItemClickListener, OnColorChangedListener, OnItemSelectedListener {
private GridView mColorGrid;
private Spinner mFgSpinner;
private Spinner mBgSpinner;
private int mColorScheme;
private List<Integer> mColorList;
private HostDatabase hostdb;
private int mCurrentColor = 0;
private int[] mDefaultColors;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_colors);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_colors)));
mColorScheme = HostDatabase.DEFAULT_COLOR_SCHEME;
hostdb = new HostDatabase(this);
mColorList = Arrays.asList(hostdb.getColorsForScheme(mColorScheme));
mDefaultColors = hostdb.getDefaultColorsForScheme(mColorScheme);
mColorGrid = (GridView) findViewById(R.id.color_grid);
mColorGrid.setAdapter(new ColorsAdapter(true));
mColorGrid.setOnItemClickListener(this);
mColorGrid.setSelection(0);
mFgSpinner = (Spinner) findViewById(R.id.fg);
mFgSpinner.setAdapter(new ColorsAdapter(false));
mFgSpinner.setSelection(mDefaultColors[0]);
mFgSpinner.setOnItemSelectedListener(this);
mBgSpinner = (Spinner) findViewById(R.id.bg);
mBgSpinner.setAdapter(new ColorsAdapter(false));
mBgSpinner.setSelection(mDefaultColors[1]);
mBgSpinner.setOnItemSelectedListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (hostdb != null) {
hostdb.close();
hostdb = null;
}
}
@Override
protected void onResume() {
super.onResume();
if (hostdb == null)
hostdb = new HostDatabase(this);
}
private class ColorsAdapter extends BaseAdapter {
private boolean mSquareViews;
public ColorsAdapter(boolean squareViews) {
mSquareViews = squareViews;
}
public View getView(int position, View convertView, ViewGroup parent) {
ColorView c;
if (convertView == null) {
c = new ColorView(ColorsActivity.this, mSquareViews);
} else {
c = (ColorView) convertView;
}
c.setColor(mColorList.get(position));
c.setNumber(position + 1);
return c;
}
public int getCount() {
return mColorList.size();
}
public Object getItem(int position) {
return mColorList.get(position);
}
public long getItemId(int position) {
return position;
}
}
private class ColorView extends View {
private boolean mSquare;
private Paint mTextPaint;
private Paint mShadowPaint;
// Things we paint
private int mBackgroundColor;
private String mText;
private int mAscent;
private int mWidthCenter;
private int mHeightCenter;
public ColorView(Context context, boolean square) {
super(context);
mSquare = square;
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16);
mTextPaint.setColor(0xFFFFFFFF);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mShadowPaint = new Paint(mTextPaint);
mShadowPaint.setStyle(Paint.Style.STROKE);
mShadowPaint.setStrokeCap(Paint.Cap.ROUND);
mShadowPaint.setStrokeJoin(Paint.Join.ROUND);
mShadowPaint.setStrokeWidth(4f);
mShadowPaint.setColor(0xFF000000);
setPadding(10, 10, 10, 10);
}
public void setColor(int color) {
mBackgroundColor = color;
}
public void setNumber(int number) {
mText = Integer.toString(number);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height;
if (mSquare)
height = width;
else
height = measureHeight(heightMeasureSpec);
mAscent = (int) mTextPaint.ascent();
mWidthCenter = width / 2;
mHeightCenter = height / 2 - mAscent / 2;
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
+ getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = (int) (-mAscent + mTextPaint.descent())
+ getPaddingTop() + getPaddingBottom();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(mBackgroundColor);
canvas.drawText(mText, mWidthCenter, mHeightCenter, mShadowPaint);
canvas.drawText(mText, mWidthCenter, mHeightCenter, mTextPaint);
}
}
private void editColor(int colorNumber) {
mCurrentColor = colorNumber;
new UberColorPickerDialog(this, this, mColorList.get(colorNumber)).show();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
editColor(position);
}
public void onNothingSelected(AdapterView<?> arg0) { }
public void colorChanged(int value) {
hostdb.setGlobalColor(mCurrentColor, value);
mColorList.set(mCurrentColor, value);
mColorGrid.invalidateViews();
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
boolean needUpdate = false;
if (parent == mFgSpinner) {
if (position != mDefaultColors[0]) {
mDefaultColors[0] = position;
needUpdate = true;
}
} else if (parent == mBgSpinner) {
if (position != mDefaultColors[1]) {
mDefaultColors[1] = position;
needUpdate = true;
}
}
if (needUpdate)
hostdb.setDefaultColorsForScheme(mColorScheme, mDefaultColors[0], mDefaultColors[1]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem reset = menu.add(R.string.menu_colors_reset);
reset.setAlphabeticShortcut('r');
reset.setNumericShortcut('1');
reset.setIcon(android.R.drawable.ic_menu_revert);
reset.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem arg0) {
// Reset each individual color to defaults.
for (int i = 0; i < Colors.defaults.length; i++) {
if (mColorList.get(i) != Colors.defaults[i]) {
hostdb.setGlobalColor(i, Colors.defaults[i]);
mColorList.set(i, Colors.defaults[i]);
}
}
mColorGrid.invalidateViews();
// Reset the default FG/BG colors as well.
mFgSpinner.setSelection(HostDatabase.DEFAULT_FG_COLOR);
mBgSpinner.setSelection(HostDatabase.DEFAULT_BG_COLOR);
hostdb.setDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME,
HostDatabase.DEFAULT_FG_COLOR, HostDatabase.DEFAULT_BG_COLOR);
return true;
}
});
return true;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
public interface BridgeDisconnectedListener {
public void onDisconnected(TerminalBridge bridge);
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import org.connectbot.util.PreferenceConstants;
import android.app.backup.BackupManager;
import android.content.Context;
/**
* @author kroot
*
*/
public abstract class BackupWrapper {
public static BackupWrapper getInstance() {
if (PreferenceConstants.PRE_FROYO)
return PreFroyo.Holder.sInstance;
else
return FroyoAndBeyond.Holder.sInstance;
}
public abstract void onDataChanged(Context context);
private static class PreFroyo extends BackupWrapper {
private static class Holder {
private static final PreFroyo sInstance = new PreFroyo();
}
@Override
public void onDataChanged(Context context) {
// do nothing for now
}
}
private static class FroyoAndBeyond extends BackupWrapper {
private static class Holder {
private static final FroyoAndBeyond sInstance = new FroyoAndBeyond();
}
private static BackupManager mBackupManager;
@Override
public void onDataChanged(Context context) {
checkBackupManager(context);
if (mBackupManager != null) {
mBackupManager.dataChanged();
}
}
private void checkBackupManager(Context context) {
if (mBackupManager == null) {
mBackupManager = new BackupManager(context);
}
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import org.apache.harmony.niochar.charset.additional.IBM437;
import org.connectbot.transport.AbsTransport;
import org.connectbot.util.EastAsianWidth;
import android.util.Log;
import de.mud.terminal.vt320;
/**
* @author Kenny Root
*/
public class Relay implements Runnable {
private static final String TAG = "ConnectBot.Relay";
private static final int BUFFER_SIZE = 4096;
private TerminalBridge bridge;
private Charset currentCharset;
private CharsetDecoder decoder;
private AbsTransport transport;
private vt320 buffer;
private ByteBuffer byteBuffer;
private CharBuffer charBuffer;
private byte[] byteArray;
private char[] charArray;
public Relay(TerminalBridge bridge, AbsTransport transport, vt320 buffer, String encoding) {
setCharset(encoding);
this.bridge = bridge;
this.transport = transport;
this.buffer = buffer;
}
public void setCharset(String encoding) {
Log.d("ConnectBot.Relay", "changing charset to " + encoding);
Charset charset;
if (encoding.equals("CP437"))
charset = new IBM437("IBM437",
new String[] { "IBM437", "CP437" });
else
charset = Charset.forName(encoding);
if (charset == currentCharset || charset == null)
return;
CharsetDecoder newCd = charset.newDecoder();
newCd.onUnmappableCharacter(CodingErrorAction.REPLACE);
newCd.onMalformedInput(CodingErrorAction.REPLACE);
currentCharset = charset;
synchronized (this) {
decoder = newCd;
}
}
public Charset getCharset() {
return currentCharset;
}
public void run() {
byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
charBuffer = CharBuffer.allocate(BUFFER_SIZE);
/* for East Asian character widths */
byte[] wideAttribute = new byte[BUFFER_SIZE];
byteArray = byteBuffer.array();
charArray = charBuffer.array();
CoderResult result;
int bytesRead = 0;
byteBuffer.limit(0);
int bytesToRead;
int offset;
int charWidth;
EastAsianWidth measurer = EastAsianWidth.getInstance();
try {
while (true) {
charWidth = bridge.charWidth;
bytesToRead = byteBuffer.capacity() - byteBuffer.limit();
offset = byteBuffer.arrayOffset() + byteBuffer.limit();
bytesRead = transport.read(byteArray, offset, bytesToRead);
if (bytesRead > 0) {
byteBuffer.limit(byteBuffer.limit() + bytesRead);
synchronized (this) {
result = decoder.decode(byteBuffer, charBuffer, false);
}
if (result.isUnderflow() &&
byteBuffer.limit() == byteBuffer.capacity()) {
byteBuffer.compact();
byteBuffer.limit(byteBuffer.position());
byteBuffer.position(0);
}
offset = charBuffer.position();
measurer.measure(charArray, 0, offset, wideAttribute, bridge.defaultPaint, charWidth);
buffer.putString(charArray, wideAttribute, 0, charBuffer.position());
bridge.propagateConsoleText(charArray, charBuffer.position());
charBuffer.clear();
bridge.redraw();
}
}
} catch (IOException e) {
Log.e(TAG, "Problem while handling incoming data in relay thread", e);
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.io.IOException;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import org.connectbot.util.PubkeyDatabase;
import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.app.backup.FileBackupHelper;
import android.app.backup.SharedPreferencesBackupHelper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
/**
* @author kroot
*
*/
public class BackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
Log.d("ConnectBot.BackupAgent", "onCreate called");
SharedPreferencesBackupHelper prefs = new SharedPreferencesBackupHelper(this, getPackageName() + "_preferences");
addHelper(PreferenceConstants.BACKUP_PREF_KEY, prefs);
FileBackupHelper hosts = new FileBackupHelper(this, "../databases/" + HostDatabase.DB_NAME);
addHelper(HostDatabase.DB_NAME, hosts);
FileBackupHelper pubkeys = new FileBackupHelper(this, "../databases/" + PubkeyDatabase.DB_NAME);
addHelper(PubkeyDatabase.DB_NAME, pubkeys);
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) throws IOException {
synchronized (HostDatabase.dbLock) {
super.onBackup(oldState, data, newState);
}
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
Log.d("ConnectBot.BackupAgent", "onRestore called");
synchronized (HostDatabase.dbLock) {
Log.d("ConnectBot.BackupAgent", "onRestore in-lock");
super.onRestore(data, appVersionCode, newState);
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
/**
* @author Kenny Root
*
*/
public interface FontSizeChangedListener {
/**
* @param size
* new font size
*/
void onFontSizeChanged(float size);
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.util.concurrent.Semaphore;
import android.os.Handler;
import android.os.Message;
/**
* Helps provide a relay for prompts and responses between a possible user
* interface and some underlying service.
*
* @author jsharkey
*/
public class PromptHelper {
private final Object tag;
private Handler handler = null;
private Semaphore promptToken;
private Semaphore promptResponse;
public String promptInstructions = null;
public String promptHint = null;
public Object promptRequested = null;
private Object response = null;
public PromptHelper(Object tag) {
this.tag = tag;
// Threads must acquire this before they can send a prompt.
promptToken = new Semaphore(1);
// Responses will release this semaphore.
promptResponse = new Semaphore(0);
}
/**
* Register a user interface handler, if available.
*/
public void setHandler(Handler handler) {
this.handler = handler;
}
/**
* Set an incoming value from an above user interface. Will automatically
* notify any waiting requests.
*/
public void setResponse(Object value) {
response = value;
promptRequested = null;
promptInstructions = null;
promptHint = null;
promptResponse.release();
}
/**
* Return the internal response value just before erasing and returning it.
*/
protected Object popResponse() {
Object value = response;
response = null;
return value;
}
/**
* Request a prompt response from parent. This is a blocking call until user
* interface returns a value.
* Only one thread can call this at a time. cancelPrompt() will force this to
* immediately return.
*/
private Object requestPrompt(String instructions, String hint, Object type) throws InterruptedException {
Object response = null;
promptToken.acquire();
try {
promptInstructions = instructions;
promptHint = hint;
promptRequested = type;
// notify any parent watching for live events
if (handler != null)
Message.obtain(handler, -1, tag).sendToTarget();
// acquire lock until user passes back value
promptResponse.acquire();
response = popResponse();
} finally {
promptToken.release();
}
return response;
}
/**
* Request a string response from parent. This is a blocking call until user
* interface returns a value.
* @param hint prompt hint for user to answer
* @return string user has entered
*/
public String requestStringPrompt(String instructions, String hint) {
String value = null;
try {
value = (String)this.requestPrompt(instructions, hint, String.class);
} catch(Exception e) {
}
return value;
}
/**
* Request a boolean response from parent. This is a blocking call until user
* interface returns a value.
* @param hint prompt hint for user to answer
* @return choice user has made (yes/no)
*/
public Boolean requestBooleanPrompt(String instructions, String hint) {
Boolean value = null;
try {
value = (Boolean)this.requestPrompt(instructions, hint, Boolean.class);
} catch(Exception e) {
}
return value;
}
/**
* Cancel an in-progress prompt.
*/
public void cancelPrompt() {
if (!promptToken.tryAcquire()) {
// A thread has the token, so try to interrupt it
response = null;
promptResponse.release();
} else {
// No threads have acquired the token
promptToken.release();
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.io.IOException;
import org.connectbot.TerminalView;
import org.connectbot.bean.SelectionArea;
import org.connectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.vt320;
/**
* @author kenny
*
*/
@SuppressWarnings("deprecation") // for ClipboardManager
public class TerminalKeyListener implements OnKeyListener, OnSharedPreferenceChangeListener {
private static final String TAG = "ConnectBot.OnKeyListener";
public final static int META_CTRL_ON = 0x01;
public final static int META_CTRL_LOCK = 0x02;
public final static int META_ALT_ON = 0x04;
public final static int META_ALT_LOCK = 0x08;
public final static int META_SHIFT_ON = 0x10;
public final static int META_SHIFT_LOCK = 0x20;
public final static int META_SLASH = 0x40;
public final static int META_TAB = 0x80;
// The bit mask of momentary and lock states for each
public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK;
public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK;
public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK;
// backport constants from api level 11
public final static int KEYCODE_ESCAPE = 111;
public final static int HC_META_CTRL_ON = 4096;
// All the transient key codes
public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON
| META_SHIFT_ON;
private final TerminalManager manager;
private final TerminalBridge bridge;
private final VDUBuffer buffer;
private String keymode = null;
private boolean hardKeyboard = false;
private int metaState = 0;
private int mDeadKey = 0;
// TODO add support for the new API.
private ClipboardManager clipboard = null;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
private String encoding;
private final SharedPreferences prefs;
public TerminalKeyListener(TerminalManager manager,
TerminalBridge bridge,
VDUBuffer buffer,
String encoding) {
this.manager = manager;
this.bridge = bridge;
this.buffer = buffer;
this.encoding = encoding;
selectionArea = new SelectionArea();
prefs = PreferenceManager.getDefaultSharedPreferences(manager);
prefs.registerOnSharedPreferenceChangeListener(this);
hardKeyboard = (manager.res.getConfiguration().keyboard
== Configuration.KEYBOARD_QWERTY);
updateKeymode();
}
/**
* Handle onKey() events coming down from a {@link TerminalView} above us.
* Modify the keys to make more sense to a host then pass it to the transport.
*/
public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN &&
event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
int curMetaState = event.getMetaState();
final int orgMetaState = curMetaState;
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
}
int key = event.getUnicodeChar(curMetaState);
// no hard keyboard? ALT-k should pass through to below
if ((orgMetaState & KeyEvent.META_ALT_ON) != 0 &&
(!hardKeyboard || hardKeyboardHidden)) {
key = 0;
}
if ((key & KeyCharacterMap.COMBINING_ACCENT) != 0) {
mDeadKey = key & KeyCharacterMap.COMBINING_ACCENT_MASK;
return true;
}
if (mDeadKey != 0) {
key = KeyCharacterMap.getDeadChar(mDeadKey, keyCode);
mDeadKey = 0;
}
final boolean printing = (key != 0);
// otherwise pass through to existing session
// print normal keys
if (printing) {
metaState &= ~(META_SLASH | META_TAB);
// Remove shift and alt modifiers
final int lastMetaState = metaState;
metaState &= ~(META_SHIFT_ON | META_ALT_ON);
if (metaState != lastMetaState) {
bridge.redraw();
}
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
// If there is no hard keyboard or there is a hard keyboard currently hidden,
// CTRL-1 through CTRL-9 will send F1 through F9
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
key = keyAsControl(key);
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80)
bridge.transport.write(key);
else
// TODO write encoding routine that doesn't allocate each time
bridge.transport.write(new String(Character.toChars(key))
.getBytes(encoding));
return true;
}
// send ctrl and meta-keys as appropriate
if (!hardKeyboard || hardKeyboardHidden) {
int k = event.getUnicodeChar(0);
int k0 = k;
boolean sendCtrl = false;
boolean sendMeta = false;
if (k != 0) {
if ((orgMetaState & HC_META_CTRL_ON) != 0) {
k = keyAsControl(k);
if (k != k0)
sendCtrl = true;
// send F1-F10 via CTRL-1 through CTRL-0
if (!sendCtrl && sendFunctionKey(keyCode))
return true;
} else if ((orgMetaState & KeyEvent.META_ALT_ON) != 0) {
sendMeta = true;
sendEscape();
}
if (sendMeta || sendCtrl) {
bridge.transport.write(k);
return true;
}
}
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KEYCODE_ESCAPE:
sendEscape();
return true;
case KeyEvent.KEYCODE_TAB:
bridge.transport.write(0x09);
return true;
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
public int keyAsControl(int key) {
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
// CTRL-space sends NULL
else if (key == 0x20)
key = 0x00;
// CTRL-? sends DEL
else if (key == 0x3F)
key = 0x7F;
return key;
}
public void sendEscape() {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
}
/**
* @param key
* @return successful
*/
private boolean sendFunctionKey(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_1:
((vt320) buffer).keyPressed(vt320.KEY_F1, ' ', 0);
return true;
case KeyEvent.KEYCODE_2:
((vt320) buffer).keyPressed(vt320.KEY_F2, ' ', 0);
return true;
case KeyEvent.KEYCODE_3:
((vt320) buffer).keyPressed(vt320.KEY_F3, ' ', 0);
return true;
case KeyEvent.KEYCODE_4:
((vt320) buffer).keyPressed(vt320.KEY_F4, ' ', 0);
return true;
case KeyEvent.KEYCODE_5:
((vt320) buffer).keyPressed(vt320.KEY_F5, ' ', 0);
return true;
case KeyEvent.KEYCODE_6:
((vt320) buffer).keyPressed(vt320.KEY_F6, ' ', 0);
return true;
case KeyEvent.KEYCODE_7:
((vt320) buffer).keyPressed(vt320.KEY_F7, ' ', 0);
return true;
case KeyEvent.KEYCODE_8:
((vt320) buffer).keyPressed(vt320.KEY_F8, ' ', 0);
return true;
case KeyEvent.KEYCODE_9:
((vt320) buffer).keyPressed(vt320.KEY_F9, ' ', 0);
return true;
case KeyEvent.KEYCODE_0:
((vt320) buffer).keyPressed(vt320.KEY_F10, ' ', 0);
return true;
default:
return false;
}
}
/**
* Handle meta key presses where the key can be locked on.
* <p>
* 1st press: next key to have meta state<br />
* 2nd press: meta state is locked on<br />
* 3rd press: disable meta state
*
* @param code
*/
public void metaPress(int code) {
if ((metaState & (code << 1)) != 0) {
metaState &= ~(code << 1);
} else if ((metaState & code) != 0) {
metaState &= ~code;
metaState |= code << 1;
} else
metaState |= code;
bridge.redraw();
}
public void setTerminalKeyMode(String keymode) {
this.keymode = keymode;
}
private int getStateForBuffer() {
int bufferState = 0;
if ((metaState & META_CTRL_MASK) != 0)
bufferState |= vt320.KEY_CONTROL;
if ((metaState & META_SHIFT_MASK) != 0)
bufferState |= vt320.KEY_SHIFT;
if ((metaState & META_ALT_MASK) != 0)
bufferState |= vt320.KEY_ALT;
return bufferState;
}
public int getMetaState() {
return metaState;
}
public int getDeadKey() {
return mDeadKey;
}
public void setClipboardManager(ClipboardManager clipboard) {
this.clipboard = clipboard;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.KEYMODE.equals(key)) {
updateKeymode();
}
}
private void updateKeymode() {
keymode = prefs.getString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
}
public void setCharset(String encoding) {
this.encoding = encoding;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Manager for SSH connections that runs as a service. This service holds a list
* of currently connected SSH bridges that are ready for connection up to a GUI
* if needed.
*
* @author jsharkey
*/
public class TerminalManager extends Service implements BridgeDisconnectedListener, OnSharedPreferenceChangeListener {
public final static String TAG = "ConnectBot.TerminalManager";
public List<TerminalBridge> bridges = new LinkedList<TerminalBridge>();
public Map<HostBean, WeakReference<TerminalBridge>> mHostBridgeMap =
new HashMap<HostBean, WeakReference<TerminalBridge>>();
public Map<String, WeakReference<TerminalBridge>> mNicknameBridgeMap =
new HashMap<String, WeakReference<TerminalBridge>>();
public TerminalBridge defaultBridge = null;
public List<HostBean> disconnected = new LinkedList<HostBean>();
public Handler disconnectHandler = null;
public Map<String, KeyHolder> loadedKeypairs = new HashMap<String, KeyHolder>();
public Resources res;
public HostDatabase hostdb;
public PubkeyDatabase pubkeydb;
protected SharedPreferences prefs;
final private IBinder binder = new TerminalBinder();
private ConnectivityReceiver connectivityManager;
private MediaPlayer mediaPlayer;
private Timer pubkeyTimer;
private Timer idleTimer;
private final long IDLE_TIMEOUT = 300000; // 5 minutes
private Vibrator vibrator;
private volatile boolean wantKeyVibration;
public static final long VIBRATE_DURATION = 30;
private boolean wantBellVibration;
private boolean resizeAllowed = true;
private boolean savingKeys;
protected List<WeakReference<TerminalBridge>> mPendingReconnect
= new LinkedList<WeakReference<TerminalBridge>>();
public boolean hardKeyboardHidden;
@Override
public void onCreate() {
Log.i(TAG, "Starting service");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
res = getResources();
pubkeyTimer = new Timer("pubkeyTimer", true);
hostdb = new HostDatabase(this);
pubkeydb = new PubkeyDatabase(this);
// load all marked pubkeys into memory
updateSavingKeys();
List<PubkeyBean> pubkeys = pubkeydb.getAllStartPubkeys();
for (PubkeyBean pubkey : pubkeys) {
try {
PrivateKey privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
PublicKey pubKey = pubkey.getPublicKey();
Object trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
addKey(pubkey, trileadKey);
} catch (Exception e) {
Log.d(TAG, String.format("Problem adding key '%s' to in-memory cache", pubkey.getNickname()), e);
}
}
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
wantKeyVibration = prefs.getBoolean(PreferenceConstants.BUMPY_ARROWS, true);
wantBellVibration = prefs.getBoolean(PreferenceConstants.BELL_VIBRATE, true);
enableMediaPlayer();
hardKeyboardHidden = (res.getConfiguration().hardKeyboardHidden ==
Configuration.HARDKEYBOARDHIDDEN_YES);
final boolean lockingWifi = prefs.getBoolean(PreferenceConstants.WIFI_LOCK, true);
connectivityManager = new ConnectivityReceiver(this, lockingWifi);
}
private void updateSavingKeys() {
savingKeys = prefs.getBoolean(PreferenceConstants.MEMKEYS, true);
}
@Override
public void onDestroy() {
Log.i(TAG, "Destroying service");
disconnectAll(true);
if(hostdb != null) {
hostdb.close();
hostdb = null;
}
if(pubkeydb != null) {
pubkeydb.close();
pubkeydb = null;
}
synchronized (this) {
if (idleTimer != null)
idleTimer.cancel();
if (pubkeyTimer != null)
pubkeyTimer.cancel();
}
connectivityManager.cleanup();
ConnectionNotifier.getInstance().hideRunningNotification(this);
disableMediaPlayer();
}
/**
* Disconnect all currently connected bridges.
*/
private void disconnectAll(final boolean immediate) {
TerminalBridge[] tmpBridges = null;
synchronized (bridges) {
if (bridges.size() > 0) {
tmpBridges = bridges.toArray(new TerminalBridge[bridges.size()]);
}
}
if (tmpBridges != null) {
// disconnect and dispose of any existing bridges
for (int i = 0; i < tmpBridges.length; i++)
tmpBridges[i].dispatchDisconnect(immediate);
}
}
/**
* Open a new SSH session using the given parameters.
*/
private TerminalBridge openConnection(HostBean host) throws IllegalArgumentException, IOException {
// throw exception if terminal already open
if (getConnectedBridge(host) != null) {
throw new IllegalArgumentException("Connection already open for that nickname");
}
TerminalBridge bridge = new TerminalBridge(this, host);
bridge.setOnDisconnectedListener(this);
bridge.startConnection();
synchronized (bridges) {
bridges.add(bridge);
WeakReference<TerminalBridge> wr = new WeakReference<TerminalBridge>(bridge);
mHostBridgeMap.put(bridge.host, wr);
mNicknameBridgeMap.put(bridge.host.getNickname(), wr);
}
synchronized (disconnected) {
disconnected.remove(bridge.host);
}
if (bridge.isUsingNetwork()) {
connectivityManager.incRef();
}
if (prefs.getBoolean(PreferenceConstants.CONNECTION_PERSIST, true)) {
ConnectionNotifier.getInstance().showRunningNotification(this);
}
// also update database with new connected time
touchHost(host);
return bridge;
}
public String getEmulation() {
return prefs.getString(PreferenceConstants.EMULATION, "screen");
}
public int getScrollback() {
int scrollback = 140;
try {
scrollback = Integer.parseInt(prefs.getString(PreferenceConstants.SCROLLBACK, "140"));
} catch(Exception e) {
}
return scrollback;
}
/**
* Open a new connection by reading parameters from the given URI. Follows
* format specified by an individual transport.
*/
public TerminalBridge openConnection(Uri uri) throws Exception {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null)
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
return openConnection(host);
}
/**
* Update the last-connected value for the given nickname by passing through
* to {@link HostDatabase}.
*/
private void touchHost(HostBean host) {
hostdb.touchHost(host);
}
/**
* Find a connected {@link TerminalBridge} with the given HostBean.
*
* @param host the HostBean to search for
* @return TerminalBridge that uses the HostBean
*/
public TerminalBridge getConnectedBridge(HostBean host) {
WeakReference<TerminalBridge> wr = mHostBridgeMap.get(host);
if (wr != null) {
return wr.get();
} else {
return null;
}
}
/**
* Find a connected {@link TerminalBridge} using its nickname.
*
* @param nickname
* @return TerminalBridge that matches nickname
*/
public TerminalBridge getConnectedBridge(final String nickname) {
if (nickname == null) {
return null;
}
WeakReference<TerminalBridge> wr = mNicknameBridgeMap.get(nickname);
if (wr != null) {
return wr.get();
} else {
return null;
}
}
/**
* Called by child bridge when somehow it's been disconnected.
*/
public void onDisconnected(TerminalBridge bridge) {
boolean shouldHideRunningNotification = false;
synchronized (bridges) {
// remove this bridge from our list
bridges.remove(bridge);
mHostBridgeMap.remove(bridge.host);
mNicknameBridgeMap.remove(bridge.host.getNickname());
if (bridge.isUsingNetwork()) {
connectivityManager.decRef();
}
if (bridges.size() == 0 &&
mPendingReconnect.size() == 0) {
shouldHideRunningNotification = true;
}
}
synchronized (disconnected) {
disconnected.add(bridge.host);
}
if (shouldHideRunningNotification) {
ConnectionNotifier.getInstance().hideRunningNotification(this);
}
// pass notification back up to gui
if (disconnectHandler != null)
Message.obtain(disconnectHandler, -1, bridge).sendToTarget();
}
public boolean isKeyLoaded(String nickname) {
return loadedKeypairs.containsKey(nickname);
}
public void addKey(PubkeyBean pubkey, Object trileadKey) {
addKey(pubkey, trileadKey, false);
}
public void addKey(PubkeyBean pubkey, Object trileadKey, boolean force) {
if (!savingKeys && !force)
return;
removeKey(pubkey.getNickname());
byte[] sshPubKey = PubkeyUtils.extractOpenSSHPublic(trileadKey);
KeyHolder keyHolder = new KeyHolder();
keyHolder.bean = pubkey;
keyHolder.trileadKey = trileadKey;
keyHolder.openSSHPubkey = sshPubKey;
loadedKeypairs.put(pubkey.getNickname(), keyHolder);
if (pubkey.getLifetime() > 0) {
final String nickname = pubkey.getNickname();
pubkeyTimer.schedule(new TimerTask() {
@Override
public void run() {
Log.d(TAG, "Unloading from memory key: " + nickname);
removeKey(nickname);
}
}, pubkey.getLifetime() * 1000);
}
Log.d(TAG, String.format("Added key '%s' to in-memory cache", pubkey.getNickname()));
}
public boolean removeKey(String nickname) {
Log.d(TAG, String.format("Removed key '%s' to in-memory cache", nickname));
return loadedKeypairs.remove(nickname) != null;
}
public boolean removeKey(byte[] publicKey) {
String nickname = null;
for (Entry<String,KeyHolder> entry : loadedKeypairs.entrySet()) {
if (Arrays.equals(entry.getValue().openSSHPubkey, publicKey)) {
nickname = entry.getKey();
break;
}
}
if (nickname != null) {
Log.d(TAG, String.format("Removed key '%s' to in-memory cache", nickname));
return removeKey(nickname);
} else
return false;
}
public Object getKey(String nickname) {
if (loadedKeypairs.containsKey(nickname)) {
KeyHolder keyHolder = loadedKeypairs.get(nickname);
return keyHolder.trileadKey;
} else
return null;
}
public Object getKey(byte[] publicKey) {
for (KeyHolder keyHolder : loadedKeypairs.values()) {
if (Arrays.equals(keyHolder.openSSHPubkey, publicKey))
return keyHolder.trileadKey;
}
return null;
}
public String getKeyNickname(byte[] publicKey) {
for (Entry<String,KeyHolder> entry : loadedKeypairs.entrySet()) {
if (Arrays.equals(entry.getValue().openSSHPubkey, publicKey))
return entry.getKey();
}
return null;
}
private void stopWithDelay() {
// TODO add in a way to check whether keys loaded are encrypted and only
// set timer when we have an encrypted key loaded
if (loadedKeypairs.size() > 0) {
synchronized (this) {
if (idleTimer == null)
idleTimer = new Timer("idleTimer", true);
idleTimer.schedule(new IdleTask(), IDLE_TIMEOUT);
}
} else {
Log.d(TAG, "Stopping service immediately");
stopSelf();
}
}
protected void stopNow() {
if (bridges.size() == 0) {
stopSelf();
}
}
private synchronized void stopIdleTimer() {
if (idleTimer != null) {
idleTimer.cancel();
idleTimer = null;
}
}
public class TerminalBinder extends Binder {
public TerminalManager getService() {
return TerminalManager.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Someone bound to TerminalManager");
setResizeAllowed(true);
stopIdleTimer();
// Make sure we stay running to maintain the bridges
startService(new Intent(this, TerminalManager.class));
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*
* We want this service to continue running until it is explicitly
* stopped, so return sticky.
*/
return START_STICKY;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
setResizeAllowed(true);
Log.i(TAG, "Someone rebound to TerminalManager");
stopIdleTimer();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "Someone unbound from TerminalManager");
setResizeAllowed(true);
if (bridges.size() == 0) {
stopWithDelay();
}
return true;
}
private class IdleTask extends TimerTask {
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
Log.d(TAG, String.format("Stopping service after timeout of ~%d seconds", IDLE_TIMEOUT / 1000));
TerminalManager.this.stopNow();
}
}
public void tryKeyVibrate() {
if (wantKeyVibration)
vibrate();
}
private void vibrate() {
if (vibrator != null)
vibrator.vibrate(VIBRATE_DURATION);
}
private void enableMediaPlayer() {
mediaPlayer = new MediaPlayer();
float volume = prefs.getFloat(PreferenceConstants.BELL_VOLUME,
PreferenceConstants.DEFAULT_BELL_VOLUME);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnCompletionListener(new BeepListener());
AssetFileDescriptor file = res.openRawResourceFd(R.raw.bell);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file
.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(volume, volume);
mediaPlayer.prepare();
} catch (IOException e) {
Log.e(TAG, "Error setting up bell media player", e);
}
}
private void disableMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public void playBeep() {
if (mediaPlayer != null)
mediaPlayer.start();
if (wantBellVibration)
vibrate();
}
private static class BeepListener implements OnCompletionListener {
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
}
}
/**
* Send system notification to user for a certain host. When user selects
* the notification, it will bring them directly to the ConsoleActivity
* displaying the host.
*
* @param host
*/
public void sendActivityNotification(HostBean host) {
if (!prefs.getBoolean(PreferenceConstants.BELL_NOTIFICATION, false))
return;
ConnectionNotifier.getInstance().showActivityNotification(this, host);
}
/* (non-Javadoc)
* @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String)
*/
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.BELL.equals(key)) {
boolean wantAudible = sharedPreferences.getBoolean(
PreferenceConstants.BELL, true);
if (wantAudible && mediaPlayer == null)
enableMediaPlayer();
else if (!wantAudible && mediaPlayer != null)
disableMediaPlayer();
} else if (PreferenceConstants.BELL_VOLUME.equals(key)) {
if (mediaPlayer != null) {
float volume = sharedPreferences.getFloat(
PreferenceConstants.BELL_VOLUME,
PreferenceConstants.DEFAULT_BELL_VOLUME);
mediaPlayer.setVolume(volume, volume);
}
} else if (PreferenceConstants.BELL_VIBRATE.equals(key)) {
wantBellVibration = sharedPreferences.getBoolean(
PreferenceConstants.BELL_VIBRATE, true);
} else if (PreferenceConstants.BUMPY_ARROWS.equals(key)) {
wantKeyVibration = sharedPreferences.getBoolean(
PreferenceConstants.BUMPY_ARROWS, true);
} else if (PreferenceConstants.WIFI_LOCK.equals(key)) {
final boolean lockingWifi = prefs.getBoolean(PreferenceConstants.WIFI_LOCK, true);
connectivityManager.setWantWifiLock(lockingWifi);
} else if (PreferenceConstants.MEMKEYS.equals(key)) {
updateSavingKeys();
}
}
/**
* Allow {@link TerminalBridge} to resize when the parent has changed.
* @param resizeAllowed
*/
public void setResizeAllowed(boolean resizeAllowed) {
this.resizeAllowed = resizeAllowed;
}
public boolean isResizeAllowed() {
return resizeAllowed;
}
public static class KeyHolder {
public PubkeyBean bean;
public Object trileadKey;
public byte[] openSSHPubkey;
}
/**
* Called when connectivity to the network is lost and it doesn't appear
* we'll be getting a different connection any time soon.
*/
public void onConnectivityLost() {
final Thread t = new Thread() {
@Override
public void run() {
disconnectAll(false);
}
};
t.setName("Disconnector");
t.start();
}
/**
* Called when connectivity to the network is restored.
*/
public void onConnectivityRestored() {
final Thread t = new Thread() {
@Override
public void run() {
reconnectPending();
}
};
t.setName("Reconnector");
t.start();
}
/**
* Insert request into reconnect queue to be executed either immediately
* or later when connectivity is restored depending on whether we're
* currently connected.
*
* @param bridge the TerminalBridge to reconnect when possible
*/
public void requestReconnect(TerminalBridge bridge) {
synchronized (mPendingReconnect) {
mPendingReconnect.add(new WeakReference<TerminalBridge>(bridge));
if (!bridge.isUsingNetwork() ||
connectivityManager.isConnected()) {
reconnectPending();
}
}
}
/**
* Reconnect all bridges that were pending a reconnect when connectivity
* was lost.
*/
private void reconnectPending() {
synchronized (mPendingReconnect) {
for (WeakReference<TerminalBridge> ref : mPendingReconnect) {
TerminalBridge bridge = ref.get();
if (bridge == null) {
continue;
}
bridge.startConnection();
}
mPendingReconnect.clear();
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.connectbot.ConsoleActivity;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
/**
* @author Kenny Root
*
* Based on the concept from jasta's blog post.
*/
public abstract class ConnectionNotifier {
private static final int ONLINE_NOTIFICATION = 1;
private static final int ACTIVITY_NOTIFICATION = 2;
public static ConnectionNotifier getInstance() {
if (PreferenceConstants.PRE_ECLAIR)
return PreEclair.Holder.sInstance;
else
return EclairAndBeyond.Holder.sInstance;
}
protected NotificationManager getNotificationManager(Context context) {
return (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
protected Notification newNotification(Context context) {
Notification notification = new Notification();
notification.icon = R.drawable.notification_icon;
notification.when = System.currentTimeMillis();
return notification;
}
protected Notification newActivityNotification(Context context, HostBean host) {
Notification notification = newNotification(context);
Resources res = context.getResources();
String contentText = res.getString(
R.string.notification_text, host.getNickname());
Intent notificationIntent = new Intent(context, ConsoleActivity.class);
notificationIntent.setAction("android.intent.action.VIEW");
notificationIntent.setData(host.getUri());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, res.getString(R.string.app_name), contentText, contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.DEFAULT_LIGHTS;
if (HostDatabase.COLOR_RED.equals(host.getColor()))
notification.ledARGB = Color.RED;
else if (HostDatabase.COLOR_GREEN.equals(host.getColor()))
notification.ledARGB = Color.GREEN;
else if (HostDatabase.COLOR_BLUE.equals(host.getColor()))
notification.ledARGB = Color.BLUE;
else
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
return notification;
}
protected Notification newRunningNotification(Context context) {
Notification notification = newNotification(context);
notification.flags = Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
notification.when = 0;
notification.contentIntent = PendingIntent.getActivity(context,
ONLINE_NOTIFICATION,
new Intent(context, ConsoleActivity.class), 0);
Resources res = context.getResources();
notification.setLatestEventInfo(context,
res.getString(R.string.app_name),
res.getString(R.string.app_is_running),
notification.contentIntent);
return notification;
}
public void showActivityNotification(Service context, HostBean host) {
getNotificationManager(context).notify(ACTIVITY_NOTIFICATION, newActivityNotification(context, host));
}
public void hideActivityNotification(Service context) {
getNotificationManager(context).cancel(ACTIVITY_NOTIFICATION);
}
public abstract void showRunningNotification(Service context);
public abstract void hideRunningNotification(Service context);
private static class PreEclair extends ConnectionNotifier {
private static final Class<?>[] setForegroundSignature = new Class[] {boolean.class};
private Method setForeground = null;
private static class Holder {
private static final PreEclair sInstance = new PreEclair();
}
public PreEclair() {
try {
setForeground = Service.class.getMethod("setForeground", setForegroundSignature);
} catch (Exception e) {
}
}
@Override
public void showRunningNotification(Service context) {
if (setForeground != null) {
Object[] setForegroundArgs = new Object[1];
setForegroundArgs[0] = Boolean.TRUE;
try {
setForeground.invoke(context, setForegroundArgs);
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
getNotificationManager(context).notify(ONLINE_NOTIFICATION, newRunningNotification(context));
}
}
@Override
public void hideRunningNotification(Service context) {
if (setForeground != null) {
Object[] setForegroundArgs = new Object[1];
setForegroundArgs[0] = Boolean.FALSE;
try {
setForeground.invoke(context, setForegroundArgs);
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
getNotificationManager(context).cancel(ONLINE_NOTIFICATION);
}
}
}
private static class EclairAndBeyond extends ConnectionNotifier {
private static class Holder {
private static final EclairAndBeyond sInstance = new EclairAndBeyond();
}
@Override
public void showRunningNotification(Service context) {
context.startForeground(ONLINE_NOTIFICATION, newRunningNotification(context));
}
@Override
public void hideRunningNotification(Service context) {
context.stopForeground(true);
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.service;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.TerminalView;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.bean.SelectionArea;
import org.connectbot.transport.AbsTransport;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Typeface;
import android.text.ClipboardManager;
import android.util.Log;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.VDUDisplay;
import de.mud.terminal.vt320;
/**
* Provides a bridge between a MUD terminal buffer and a possible TerminalView.
* This separation allows us to keep the TerminalBridge running in a background
* service. A TerminalView shares down a bitmap that we can use for rendering
* when available.
*
* This class also provides SSH hostkey verification prompting, and password
* prompting.
*/
@SuppressWarnings("deprecation") // for ClipboardManager
public class TerminalBridge implements VDUDisplay {
public final static String TAG = "ConnectBot.TerminalBridge";
public final static int DEFAULT_FONT_SIZE = 10;
private final static int FONT_SIZE_STEP = 2;
public Integer[] color;
public int defaultFg = HostDatabase.DEFAULT_FG_COLOR;
public int defaultBg = HostDatabase.DEFAULT_BG_COLOR;
protected final TerminalManager manager;
public HostBean host;
/* package */ AbsTransport transport;
final Paint defaultPaint;
private Relay relay;
private final String emulation;
private final int scrollback;
public Bitmap bitmap = null;
public VDUBuffer buffer = null;
private TerminalView parent = null;
private final Canvas canvas = new Canvas();
private boolean disconnected = false;
private boolean awaitingClose = false;
private boolean forcedSize = false;
private int columns;
private int rows;
/* package */ final TerminalKeyListener keyListener;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
// TODO add support for the new clipboard API
private ClipboardManager clipboard;
public int charWidth = -1;
public int charHeight = -1;
private int charTop = -1;
private float fontSize = -1;
private final List<FontSizeChangedListener> fontSizeChangedListeners;
private final List<String> localOutput;
/**
* Flag indicating if we should perform a full-screen redraw during our next
* rendering pass.
*/
private boolean fullRedraw = false;
public PromptHelper promptHelper;
protected BridgeDisconnectedListener disconnectListener = null;
/**
* Create a new terminal bridge suitable for unit testing.
*/
public TerminalBridge() {
buffer = new vt320() {
@Override
public void write(byte[] b) {}
@Override
public void write(int b) {}
@Override
public void sendTelnetCommand(byte cmd) {}
@Override
public void setWindowSize(int c, int r) {}
@Override
public void debug(String s) {}
};
emulation = null;
manager = null;
defaultPaint = new Paint();
selectionArea = new SelectionArea();
scrollback = 1;
localOutput = new LinkedList<String>();
fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>();
transport = null;
keyListener = new TerminalKeyListener(manager, this, buffer, null);
}
/**
* Create new terminal bridge with following parameters. We will immediately
* launch thread to start SSH connection and handle any hostkey verification
* and password authentication.
*/
public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException {
this.manager = manager;
this.host = host;
emulation = manager.getEmulation();
scrollback = manager.getScrollback();
// create prompt helper to relay password and hostkey requests up to gui
promptHelper = new PromptHelper(this);
// create our default paint
defaultPaint = new Paint();
defaultPaint.setAntiAlias(true);
defaultPaint.setTypeface(Typeface.MONOSPACE);
defaultPaint.setFakeBoldText(true); // more readable?
localOutput = new LinkedList<String>();
fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>();
int hostFontSize = host.getFontSize();
if (hostFontSize <= 0)
hostFontSize = DEFAULT_FONT_SIZE;
setFontSize(hostFontSize);
// create terminal buffer and handle outgoing data
// this is probably status reply information
buffer = new vt320() {
@Override
public void debug(String s) {
Log.d(TAG, s);
}
@Override
public void write(byte[] b) {
try {
if (b != null && transport != null)
transport.write(b);
} catch (IOException e) {
Log.e(TAG, "Problem writing outgoing data in vt320() thread", e);
}
}
@Override
public void write(int b) {
try {
if (transport != null)
transport.write(b);
} catch (IOException e) {
Log.e(TAG, "Problem writing outgoing data in vt320() thread", e);
}
}
// We don't use telnet sequences.
@Override
public void sendTelnetCommand(byte cmd) {
}
// We don't want remote to resize our window.
@Override
public void setWindowSize(int c, int r) {
}
@Override
public void beep() {
if (parent.isShown())
manager.playBeep();
else
manager.sendActivityNotification(host);
}
};
// Don't keep any scrollback if a session is not being opened.
if (host.getWantSession())
buffer.setBufferSize(scrollback);
else
buffer.setBufferSize(0);
resetColors();
buffer.setDisplay(this);
selectionArea = new SelectionArea();
keyListener = new TerminalKeyListener(manager, this, buffer, host.getEncoding());
}
public PromptHelper getPromptHelper() {
return promptHelper;
}
/**
* Spawn thread to open connection and start login process.
*/
protected void startConnection() {
transport = TransportFactory.getTransport(host.getProtocol());
transport.setBridge(this);
transport.setManager(manager);
transport.setHost(host);
// TODO make this more abstract so we don't litter on AbsTransport
transport.setCompression(host.getCompression());
transport.setUseAuthAgent(host.getUseAuthAgent());
transport.setEmulation(emulation);
if (transport.canForwardPorts()) {
for (PortForwardBean portForward : manager.hostdb.getPortForwardsForHost(host))
transport.addPortForward(portForward);
}
outputLine(manager.res.getString(R.string.terminal_connecting, host.getHostname(), host.getPort(), host.getProtocol()));
Thread connectionThread = new Thread(new Runnable() {
public void run() {
transport.connect();
}
});
connectionThread.setName("Connection");
connectionThread.setDaemon(true);
connectionThread.start();
}
/**
* Handle challenges from keyboard-interactive authentication mode.
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) {
String[] responses = new String[numPrompts];
for(int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
responses[i] = promptHelper.requestStringPrompt(instruction, prompt[i]);
}
return responses;
}
/**
* @return charset in use by bridge
*/
public Charset getCharset() {
return relay.getCharset();
}
/**
* Sets the encoding used by the terminal. If the connection is live,
* then the character set is changed for the next read.
* @param encoding the canonical name of the character encoding
*/
public void setCharset(String encoding) {
if (relay != null)
relay.setCharset(encoding);
keyListener.setCharset(encoding);
}
/**
* Convenience method for writing a line into the underlying MUD buffer.
* Should never be called once the session is established.
*/
public final void outputLine(String line) {
if (transport != null && transport.isSessionOpen())
Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback"));
synchronized (localOutput) {
final String s = line + "\r\n";
localOutput.add(s);
((vt320) buffer).putString(s);
// For accessibility
final char[] charArray = s.toCharArray();
propagateConsoleText(charArray, charArray.length);
}
}
/**
* Inject a specific string into this terminal. Used for post-login strings
* and pasting clipboard.
*/
public void injectString(final String string) {
if (string == null || string.length() == 0)
return;
Thread injectStringThread = new Thread(new Runnable() {
public void run() {
try {
transport.write(string.getBytes(host.getEncoding()));
} catch (Exception e) {
Log.e(TAG, "Couldn't inject string to remote host: ", e);
}
}
});
injectStringThread.setName("InjectString");
injectStringThread.start();
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
public void onConnected() {
disconnected = false;
((vt320) buffer).reset();
// We no longer need our local output.
localOutput.clear();
// previously tried vt100 and xterm for emulation modes
// "screen" works the best for color and escape codes
((vt320) buffer).setAnswerBack(emulation);
if (HostDatabase.DELKEY_BACKSPACE.equals(host.getDelKey()))
((vt320) buffer).setBackspace(vt320.DELETE_IS_BACKSPACE);
else
((vt320) buffer).setBackspace(vt320.DELETE_IS_DEL);
// create thread to relay incoming connection data to buffer
relay = new Relay(this, transport, (vt320) buffer, host.getEncoding());
Thread relayThread = new Thread(relay);
relayThread.setDaemon(true);
relayThread.setName("Relay");
relayThread.start();
// force font-size to make sure we resizePTY as needed
setFontSize(fontSize);
// finally send any post-login string, if requested
injectString(host.getPostLogin());
}
/**
* @return whether a session is open or not
*/
public boolean isSessionOpen() {
if (transport != null)
return transport.isSessionOpen();
return false;
}
public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) {
this.disconnectListener = disconnectListener;
}
/**
* Force disconnection of this terminal bridge.
*/
public void dispatchDisconnect(boolean immediate) {
// We don't need to do this multiple times.
synchronized (this) {
if (disconnected && !immediate)
return;
disconnected = true;
}
// Cancel any pending prompts.
promptHelper.cancelPrompt();
// disconnection request hangs if we havent really connected to a host yet
// temporary fix is to just spawn disconnection into a thread
Thread disconnectThread = new Thread(new Runnable() {
public void run() {
if (transport != null && transport.isConnected())
transport.close();
}
});
disconnectThread.setName("Disconnect");
disconnectThread.start();
if (immediate) {
awaitingClose = true;
if (disconnectListener != null)
disconnectListener.onDisconnected(TerminalBridge.this);
} else {
{
final String line = manager.res.getString(R.string.alert_disconnect_msg);
((vt320) buffer).putString("\r\n" + line + "\r\n");
}
if (host.getStayConnected()) {
manager.requestReconnect(this);
return;
}
Thread disconnectPromptThread = new Thread(new Runnable() {
public void run() {
Boolean result = promptHelper.requestBooleanPrompt(null,
manager.res.getString(R.string.prompt_host_disconnected));
if (result == null || result.booleanValue()) {
awaitingClose = true;
// Tell the TerminalManager that we can be destroyed now.
if (disconnectListener != null)
disconnectListener.onDisconnected(TerminalBridge.this);
}
}
});
disconnectPromptThread.setName("DisconnectPrompt");
disconnectPromptThread.setDaemon(true);
disconnectPromptThread.start();
}
}
public void setSelectingForCopy(boolean selectingForCopy) {
this.selectingForCopy = selectingForCopy;
}
public boolean isSelectingForCopy() {
return selectingForCopy;
}
public SelectionArea getSelectionArea() {
return selectionArea;
}
public synchronized void tryKeyVibrate() {
manager.tryKeyVibrate();
}
/**
* Request a different font size. Will make call to parentChanged() to make
* sure we resize PTY if needed.
*/
/* package */ final void setFontSize(float size) {
if (size <= 0.0)
return;
defaultPaint.setTextSize(size);
fontSize = size;
// read new metrics to get exact pixel dimensions
FontMetrics fm = defaultPaint.getFontMetrics();
charTop = (int)Math.ceil(fm.top);
float[] widths = new float[1];
defaultPaint.getTextWidths("X", widths);
charWidth = (int)Math.ceil(widths[0]);
charHeight = (int)Math.ceil(fm.descent - fm.top);
// refresh any bitmap with new font size
if(parent != null)
parentChanged(parent);
for (FontSizeChangedListener ofscl : fontSizeChangedListeners)
ofscl.onFontSizeChanged(size);
host.setFontSize((int) fontSize);
manager.hostdb.updateFontSize(host);
forcedSize = false;
}
/**
* Add an {@link FontSizeChangedListener} to the list of listeners for this
* bridge.
*
* @param listener
* listener to add
*/
public void addFontSizeChangedListener(FontSizeChangedListener listener) {
fontSizeChangedListeners.add(listener);
}
/**
* Remove an {@link FontSizeChangedListener} from the list of listeners for
* this bridge.
*
* @param listener
*/
public void removeFontSizeChangedListener(FontSizeChangedListener listener) {
fontSizeChangedListeners.remove(listener);
}
/**
* Something changed in our parent {@link TerminalView}, maybe it's a new
* parent, or maybe it's an updated font size. We should recalculate
* terminal size information and request a PTY resize.
*/
public final synchronized void parentChanged(TerminalView parent) {
if (manager != null && !manager.isResizeAllowed()) {
Log.d(TAG, "Resize is not allowed now");
return;
}
this.parent = parent;
final int width = parent.getWidth();
final int height = parent.getHeight();
// Something has gone wrong with our layout; we're 0 width or height!
if (width <= 0 || height <= 0)
return;
clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
keyListener.setClipboardManager(clipboard);
if (!forcedSize) {
// recalculate buffer size
int newColumns, newRows;
newColumns = width / charWidth;
newRows = height / charHeight;
// If nothing has changed in the terminal dimensions and not an intial
// draw then don't blow away scroll regions and such.
if (newColumns == columns && newRows == rows)
return;
columns = newColumns;
rows = newRows;
}
// reallocate new bitmap if needed
boolean newBitmap = (bitmap == null);
if(bitmap != null)
newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height);
if (newBitmap) {
discardBitmap();
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
canvas.setBitmap(bitmap);
}
// clear out any old buffer information
defaultPaint.setColor(Color.BLACK);
canvas.drawPaint(defaultPaint);
// Stroke the border of the terminal if the size is being forced;
if (forcedSize) {
int borderX = (columns * charWidth) + 1;
int borderY = (rows * charHeight) + 1;
defaultPaint.setColor(Color.GRAY);
defaultPaint.setStrokeWidth(0.0f);
if (width >= borderX)
canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint);
if (height >= borderY)
canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint);
}
try {
// request a terminal pty resize
synchronized (buffer) {
buffer.setScreenSize(columns, rows, true);
}
if(transport != null)
transport.setDimensions(columns, rows, width, height);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to resize screen or PTY", e);
}
// redraw local output if we don't have a sesson to receive our resize request
if (transport == null) {
synchronized (localOutput) {
((vt320) buffer).reset();
for (String line : localOutput)
((vt320) buffer).putString(line);
}
}
// force full redraw with new buffer size
fullRedraw = true;
redraw();
parent.notifyUser(String.format("%d x %d", columns, rows));
Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", columns, rows));
}
/**
* Somehow our parent {@link TerminalView} was destroyed. Now we don't need
* to redraw anywhere, and we can recycle our internal bitmap.
*/
public synchronized void parentDestroyed() {
parent = null;
discardBitmap();
}
private void discardBitmap() {
if (bitmap != null)
bitmap.recycle();
bitmap = null;
}
public void setVDUBuffer(VDUBuffer buffer) {
this.buffer = buffer;
}
public VDUBuffer getVDUBuffer() {
return buffer;
}
public void propagateConsoleText(char[] rawText, int length) {
if (parent != null) {
parent.propagateConsoleText(rawText, length);
}
}
public void onDraw() {
int fg, bg;
synchronized (buffer) {
boolean entireDirty = buffer.update[0] || fullRedraw;
boolean isWideCharacter = false;
// walk through all lines in the buffer
for(int l = 0; l < buffer.height; l++) {
// check if this line is dirty and needs to be repainted
// also check for entire-buffer dirty flags
if (!entireDirty && !buffer.update[l + 1]) continue;
// reset dirty flag for this line
buffer.update[l + 1] = false;
// walk through all characters in this line
for (int c = 0; c < buffer.width; c++) {
int addr = 0;
int currAttr = buffer.charAttributes[buffer.windowBase + l][c];
{
int fgcolor = defaultFg;
// check if foreground color attribute is set
if ((currAttr & VDUBuffer.COLOR_FG) != 0)
fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1;
if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0)
fg = color[fgcolor + 8];
else
fg = color[fgcolor];
}
// check if background color attribute is set
if ((currAttr & VDUBuffer.COLOR_BG) != 0)
bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1];
else
bg = color[defaultBg];
// support character inversion by swapping background and foreground color
if ((currAttr & VDUBuffer.INVERT) != 0) {
int swapc = bg;
bg = fg;
fg = swapc;
}
// set underlined attributes if requested
defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0);
isWideCharacter = (currAttr & VDUBuffer.FULLWIDTH) != 0;
if (isWideCharacter)
addr++;
else {
// determine the amount of continuous characters with the same settings and print them all at once
while(c + addr < buffer.width
&& buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) {
addr++;
}
}
// Save the current clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
// clear this dirty area with background color
defaultPaint.setColor(bg);
if (isWideCharacter) {
canvas.clipRect(c * charWidth,
l * charHeight,
(c + 2) * charWidth,
(l + 1) * charHeight);
} else {
canvas.clipRect(c * charWidth,
l * charHeight,
(c + addr) * charWidth,
(l + 1) * charHeight);
}
canvas.drawPaint(defaultPaint);
// write the text string starting at 'c' for 'addr' number of characters
defaultPaint.setColor(fg);
if((currAttr & VDUBuffer.INVISIBLE) == 0)
canvas.drawText(buffer.charArray[buffer.windowBase + l], c,
addr, c * charWidth, (l * charHeight) - charTop,
defaultPaint);
// Restore the previous clip region
canvas.restore();
// advance to the next text block with different characteristics
c += addr - 1;
if (isWideCharacter)
c++;
}
}
// reset entire-buffer flags
buffer.update[0] = false;
}
fullRedraw = false;
}
public void redraw() {
if (parent != null)
parent.postInvalidate();
}
// We don't have a scroll bar.
public void updateScrollBar() {
}
/**
* Resize terminal to fit [rows]x[cols] in screen of size [width]x[height]
* @param rows
* @param cols
* @param width
* @param height
*/
public synchronized void resizeComputed(int cols, int rows, int width, int height) {
float size = 8.0f;
float step = 8.0f;
float limit = 0.125f;
int direction;
while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0)
size += step;
if (direction == 0) {
Log.d("fontsize", String.format("Found match at %f", size));
return;
}
step /= 2.0f;
size -= step;
while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0
&& step >= limit) {
step /= 2.0f;
if (direction > 0) {
size -= step;
} else {
size += step;
}
}
if (direction > 0)
size -= step;
this.columns = cols;
this.rows = rows;
setFontSize(size);
forcedSize = true;
}
private int fontSizeCompare(float size, int cols, int rows, int width, int height) {
// read new metrics to get exact pixel dimensions
defaultPaint.setTextSize(size);
FontMetrics fm = defaultPaint.getFontMetrics();
float[] widths = new float[1];
defaultPaint.getTextWidths("X", widths);
int termWidth = (int)widths[0] * cols;
int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows;
Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight));
// Check to see if it fits in resolution specified.
if (termWidth > width || termHeight > height)
return 1;
if (termWidth == width || termHeight == height)
return 0;
return -1;
}
/**
* @return whether underlying transport can forward ports
*/
public boolean canFowardPorts() {
return transport.canForwardPorts();
}
/**
* Adds the {@link PortForwardBean} to the list.
* @param portForward the port forward bean to add
* @return true on successful addition
*/
public boolean addPortForward(PortForwardBean portForward) {
return transport.addPortForward(portForward);
}
/**
* Removes the {@link PortForwardBean} from the list.
* @param portForward the port forward bean to remove
* @return true on successful removal
*/
public boolean removePortForward(PortForwardBean portForward) {
return transport.removePortForward(portForward);
}
/**
* @return the list of port forwards
*/
public List<PortForwardBean> getPortForwards() {
return transport.getPortForwards();
}
/**
* Enables a port forward member. After calling this method, the port forward should
* be operational.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward setup
*/
public boolean enablePortForward(PortForwardBean portForward) {
if (!transport.isConnected()) {
Log.i(TAG, "Attempt to enable port forward while not connected");
return false;
}
return transport.enablePortForward(portForward);
}
/**
* Disables a port forward member. After calling this method, the port forward should
* be non-functioning.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward tear-down
*/
public boolean disablePortForward(PortForwardBean portForward) {
if (!transport.isConnected()) {
Log.i(TAG, "Attempt to disable port forward while not connected");
return false;
}
return transport.disablePortForward(portForward);
}
/**
* @return whether the TerminalBridge should close
*/
public boolean isAwaitingClose() {
return awaitingClose;
}
/**
* @return whether this connection had started and subsequently disconnected
*/
public boolean isDisconnected() {
return disconnected;
}
/* (non-Javadoc)
* @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte)
*/
public void setColor(int index, int red, int green, int blue) {
// Don't allow the system colors to be overwritten for now. May violate specs.
if (index < color.length && index >= 16)
color[index] = 0xff000000 | red << 16 | green << 8 | blue;
}
public final void resetColors() {
int[] defaults = manager.hostdb.getDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME);
defaultFg = defaults[0];
defaultBg = defaults[1];
color = manager.hostdb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME);
}
private static Pattern urlPattern = null;
/**
* @return
*/
public List<String> scanForURLs() {
List<String> urls = new LinkedList<String>();
if (urlPattern == null) {
// based on http://www.ietf.org/rfc/rfc2396.txt
String scheme = "[A-Za-z][-+.0-9A-Za-z]*";
String unreserved = "[-._~0-9A-Za-z]";
String pctEncoded = "%[0-9A-Fa-f]{2}";
String subDelims = "[!$&'()*+,;:=]";
String userinfo = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|:)*";
String h16 = "[0-9A-Fa-f]{1,4}";
String decOctet = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
String ipv4address = decOctet + "\\." + decOctet + "\\." + decOctet + "\\." + decOctet;
String ls32 = "(?:" + h16 + ":" + h16 + "|" + ipv4address + ")";
String ipv6address = "(?:(?:" + h16 + "){6}" + ls32 + ")";
String ipvfuture = "v[0-9A-Fa-f]+.(?:" + unreserved + "|" + subDelims + "|:)+";
String ipLiteral = "\\[(?:" + ipv6address + "|" + ipvfuture + ")\\]";
String regName = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + ")*";
String host = "(?:" + ipLiteral + "|" + ipv4address + "|" + regName + ")";
String port = "[0-9]*";
String authority = "(?:" + userinfo + "@)?" + host + "(?::" + port + ")?";
String pchar = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|@)";
String segment = pchar + "*";
String pathAbempty = "(?:/" + segment + ")*";
String segmentNz = pchar + "+";
String pathAbsolute = "/(?:" + segmentNz + "(?:/" + segment + ")*)?";
String pathRootless = segmentNz + "(?:/" + segment + ")*";
String hierPart = "(?://" + authority + pathAbempty + "|" + pathAbsolute + "|" + pathRootless + ")";
String query = "(?:" + pchar + "|/|\\?)*";
String fragment = "(?:" + pchar + "|/|\\?)*";
String uriRegex = scheme + ":" + hierPart + "(?:" + query + ")?(?:#" + fragment + ")?";
urlPattern = Pattern.compile(uriRegex);
}
char[] visibleBuffer = new char[buffer.height * buffer.width];
for (int l = 0; l < buffer.height; l++)
System.arraycopy(buffer.charArray[buffer.windowBase + l], 0,
visibleBuffer, l * buffer.width, buffer.width);
Matcher urlMatcher = urlPattern.matcher(new String(visibleBuffer));
while (urlMatcher.find())
urls.add(urlMatcher.group());
return urls;
}
/**
* @return
*/
public boolean isUsingNetwork() {
return transport.usesNetwork();
}
/**
* @return
*/
public TerminalKeyListener getKeyHandler() {
return keyListener;
}
/**
*
*/
public void resetScrollPosition() {
// if we're in scrollback, scroll to bottom of window on input
if (buffer.windowBase != buffer.screenBase)
buffer.setWindowBase(buffer.screenBase);
}
/**
*
*/
public void increaseFontSize() {
setFontSize(fontSize + FONT_SIZE_STEP);
}
/**
*
*/
public void decreaseFontSize() {
setFontSize(fontSize - FONT_SIZE_STEP);
}
}
|
Java
|
/**
*
*/
package org.connectbot.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;
/**
* @author kroot
*
*/
public class ConnectivityReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectBot.ConnectivityManager";
private boolean mIsConnected = false;
final private TerminalManager mTerminalManager;
final private WifiLock mWifiLock;
private int mNetworkRef = 0;
private boolean mLockingWifi;
private Object[] mLock = new Object[0];
public ConnectivityReceiver(TerminalManager manager, boolean lockingWifi) {
mTerminalManager = manager;
final ConnectivityManager cm =
(ConnectivityManager) manager.getSystemService(Context.CONNECTIVITY_SERVICE);
final WifiManager wm = (WifiManager) manager.getSystemService(Context.WIFI_SERVICE);
mWifiLock = wm.createWifiLock(TAG);
final NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mIsConnected = (info.getState() == State.CONNECTED);
}
mLockingWifi = lockingWifi;
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
manager.registerReceiver(this, filter);
}
/* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called: " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.d(TAG, "onReceived() called; noConnectivity? " + noConnectivity + "; isFailover? " + isFailover);
if (noConnectivity && !isFailover && mIsConnected) {
mIsConnected = false;
mTerminalManager.onConnectivityLost();
} else if (!mIsConnected) {
NetworkInfo info = (NetworkInfo) intent.getExtras()
.get(ConnectivityManager.EXTRA_NETWORK_INFO);
if (mIsConnected = (info.getState() == State.CONNECTED)) {
mTerminalManager.onConnectivityRestored();
}
}
}
/**
*
*/
public void cleanup() {
if (mWifiLock.isHeld())
mWifiLock.release();
mTerminalManager.unregisterReceiver(this);
}
/**
* Increase the number of things using the network. Acquire a Wi-Fi lock
* if necessary.
*/
public void incRef() {
synchronized (mLock) {
mNetworkRef += 1;
acquireWifiLockIfNecessaryLocked();
}
}
/**
* Decrease the number of things using the network. Release the Wi-Fi lock
* if necessary.
*/
public void decRef() {
synchronized (mLock) {
mNetworkRef -= 1;
releaseWifiLockIfNecessaryLocked();
}
}
/**
* @param mLockingWifi
*/
public void setWantWifiLock(boolean lockingWifi) {
synchronized (mLock) {
mLockingWifi = lockingWifi;
if (mLockingWifi) {
acquireWifiLockIfNecessaryLocked();
} else {
releaseWifiLockIfNecessaryLocked();
}
}
}
private void acquireWifiLockIfNecessaryLocked() {
if (mLockingWifi && mNetworkRef > 0 && !mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
private void releaseWifiLockIfNecessaryLocked() {
if (mNetworkRef == 0 && mWifiLock.isHeld()) {
mWifiLock.release();
}
}
/**
* @return whether we're connected to a network
*/
public boolean isConnected() {
return mIsConnected;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.util.List;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* List all portForwards for a particular host and provide a way for users to add more portForwards,
* edit existing portForwards, and delete portForwards.
*
* @author Kenny Root
*/
public class PortForwardListActivity extends ListActivity {
public final static String TAG = "ConnectBot.PortForwardListActivity";
private static final int LISTENER_CYCLE_TIME = 500;
protected HostDatabase hostdb;
private List<PortForwardBean> portForwards;
private ServiceConnection connection = null;
protected TerminalBridge hostBridge = null;
protected LayoutInflater inflater = null;
private HostBean host;
@Override
public void onStart() {
super.onStart();
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
setContentView(R.layout.act_portforwardlist);
// connect with hosts database and populate list
this.hostdb = new HostDatabase(this);
host = hostdb.findHostById(hostId);
{
final String nickname = host != null ? host.getNickname() : null;
final Resources resources = getResources();
if (nickname != null) {
this.setTitle(String.format("%s: %s (%s)",
resources.getText(R.string.app_name),
resources.getText(R.string.title_port_forwards_list),
nickname));
} else {
this.setTitle(String.format("%s: %s",
resources.getText(R.string.app_name),
resources.getText(R.string.title_port_forwards_list)));
}
}
connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
hostBridge = bound.getConnectedBridge(host);
updateHandler.sendEmptyMessage(-1);
}
public void onServiceDisconnected(ComponentName name) {
hostBridge = null;
}
};
this.updateList();
this.registerForContextMenu(this.getListView());
this.getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
ListView lv = PortForwardListActivity.this.getListView();
PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
if (hostBridge != null) {
if (pfb.isEnabled())
hostBridge.disablePortForward(pfb);
else {
if (!hostBridge.enablePortForward(pfb))
Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
}
updateHandler.sendEmptyMessage(-1);
}
}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem add = menu.add(R.string.portforward_menu_add);
add.setIcon(android.R.drawable.ic_menu_add);
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// build dialog to prompt user about updating
final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
final Spinner typeSpinner = (Spinner)portForwardView.findViewById(R.id.portforward_type);
typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> value, View view,
int position, long id) {
destEdit.setEnabled(position != 2);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
new AlertDialog.Builder(PortForwardListActivity.this)
.setView(portForwardView)
.setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
String type = HostDatabase.PORTFORWARD_LOCAL;
switch (typeSpinner.getSelectedItemPosition()) {
case 0:
type = HostDatabase.PORTFORWARD_LOCAL;
break;
case 1:
type = HostDatabase.PORTFORWARD_REMOTE;
break;
case 2:
type = HostDatabase.PORTFORWARD_DYNAMIC5;
break;
}
PortForwardBean pfb = new PortForwardBean(
host != null ? host.getId() : -1,
nicknameEdit.getText().toString(), type,
sourcePortEdit.getText().toString(),
destEdit.getText().toString());
if (hostBridge != null) {
hostBridge.addPortForward(pfb);
hostBridge.enablePortForward(pfb);
}
if (host != null && !hostdb.savePortForward(pfb))
throw new SQLException("Could not save port forward");
updateHandler.sendEmptyMessage(-1);
} catch (Exception e) {
Log.e(TAG, "Could not update port forward", e);
// TODO Show failure dialog.
}
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing port forward
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pfb.getNickname());
MenuItem edit = menu.add(R.string.portforward_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
typeSpinner.setSelection(0);
else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
typeSpinner.setSelection(1);
else
typeSpinner.setSelection(2);
final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
nicknameEdit.setText(pfb.getNickname());
final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
destEdit.setEnabled(false);
} else {
destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
}
typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> value, View view,
int position, long id) {
destEdit.setEnabled(position != 2);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
new AlertDialog.Builder(PortForwardListActivity.this)
.setView(editTunnelView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
if (hostBridge != null)
hostBridge.disablePortForward(pfb);
pfb.setNickname(nicknameEdit.getText().toString());
switch (typeSpinner.getSelectedItemPosition()) {
case 0:
pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
break;
case 1:
pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
break;
case 2:
pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
break;
}
pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
pfb.setDest(destEdit.getText().toString());
// Use the new settings for the existing connection.
if (hostBridge != null)
updateHandler.postDelayed(new Runnable() {
public void run() {
hostBridge.enablePortForward(pfb);
updateHandler.sendEmptyMessage(-1);
}
}, LISTENER_CYCLE_TIME);
if (!hostdb.savePortForward(pfb))
throw new SQLException("Could not save port forward");
updateHandler.sendEmptyMessage(-1);
} catch (Exception e) {
Log.e(TAG, "Could not update port forward", e);
// TODO Show failure dialog.
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
MenuItem delete = menu.add(R.string.portforward_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PortForwardListActivity.this)
.setMessage(getString(R.string.delete_message, pfb.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
// Delete the port forward from the host if needed.
if (hostBridge != null)
hostBridge.removePortForward(pfb);
hostdb.deletePortForward(pfb);
} catch (Exception e) {
Log.e(TAG, "Could not delete port forward", e);
}
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
PortForwardListActivity.this.updateList();
}
};
protected void updateList() {
if (hostBridge != null) {
this.portForwards = hostBridge.getPortForwards();
} else {
if (this.hostdb == null) return;
this.portForwards = this.hostdb.getPortForwardsForHost(host);
}
PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
this.setListAdapter(adapter);
}
class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {
class ViewHolder {
public TextView nickname;
public TextView caption;
}
private List<PortForwardBean> portForwards;
public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
super(context, R.layout.item_portforward, portForwards);
this.portForwards = portForwards;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_portforward, null, false);
holder = new ViewHolder();
holder.nickname = (TextView)convertView.findViewById(android.R.id.text1);
holder.caption = (TextView)convertView.findViewById(android.R.id.text2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PortForwardBean pfb = portForwards.get(position);
holder.nickname.setText(pfb.getNickname());
holder.caption.setText(pfb.getDescription());
if (hostBridge != null && !pfb.isEnabled()) {
holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
return convertView;
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import org.connectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
public class SettingsActivity extends PreferenceActivity {
private static final String TAG = "ConnectBot.Settings";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (ClassCastException e) {
Log.e(TAG, "Shared preferences are corrupt! Resetting to default values.");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Blow away all the preferences
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
// Since they were able to get to the Settings activity, they already agreed to the EULA
editor = preferences.edit();
editor.putBoolean(PreferenceConstants.EULA, true);
editor.commit();
addPreferencesFromResource(R.xml.preferences);
}
// TODO: add parse checking here to make sure we have integer value for scrollback
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.util.EntropyDialog;
import org.connectbot.util.EntropyView;
import org.connectbot.util.OnEntropyGatheredListener;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GeneratePubkeyActivity extends Activity implements OnEntropyGatheredListener {
public final static String TAG = "ConnectBot.GeneratePubkeyActivity";
final static int DEFAULT_BITS = 1024;
private LayoutInflater inflater = null;
private EditText nickname;
private RadioGroup keyTypeGroup;
private SeekBar bitsSlider;
private EditText bitsText;
private CheckBox unlockAtStartup;
private CheckBox confirmUse;
private Button save;
private Dialog entropyDialog;
private ProgressDialog progress;
private EditText password1, password2;
private String keyType = PubkeyDatabase.KEY_TYPE_RSA;
private int minBits = 768;
private int bits = DEFAULT_BITS;
private byte[] entropy;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_generatepubkey);
nickname = (EditText) findViewById(R.id.nickname);
keyTypeGroup = (RadioGroup) findViewById(R.id.key_type);
bitsText = (EditText) findViewById(R.id.bits);
bitsSlider = (SeekBar) findViewById(R.id.bits_slider);
password1 = (EditText) findViewById(R.id.password1);
password2 = (EditText) findViewById(R.id.password2);
unlockAtStartup = (CheckBox) findViewById(R.id.unlock_at_startup);
confirmUse = (CheckBox) findViewById(R.id.confirm_use);
save = (Button) findViewById(R.id.save);
inflater = LayoutInflater.from(this);
nickname.addTextChangedListener(textChecker);
password1.addTextChangedListener(textChecker);
password2.addTextChangedListener(textChecker);
keyTypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rsa) {
minBits = 768;
bitsSlider.setEnabled(true);
bitsSlider.setProgress(DEFAULT_BITS - minBits);
bitsText.setText(String.valueOf(DEFAULT_BITS));
bitsText.setEnabled(true);
keyType = PubkeyDatabase.KEY_TYPE_RSA;
} else if (checkedId == R.id.dsa) {
// DSA keys can only be 1024 bits
bitsSlider.setEnabled(false);
bitsSlider.setProgress(DEFAULT_BITS - minBits);
bitsText.setText(String.valueOf(DEFAULT_BITS));
bitsText.setEnabled(false);
keyType = PubkeyDatabase.KEY_TYPE_DSA;
}
}
});
bitsSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
// Stay evenly divisible by 8 because it looks nicer to have
// 2048 than 2043 bits.
int leftover = progress % 8;
int ourProgress = progress;
if (leftover > 0)
ourProgress += 8 - leftover;
bits = minBits + ourProgress;
bitsText.setText(String.valueOf(bits));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// We don't care about the start.
}
public void onStopTrackingTouch(SeekBar seekBar) {
// We don't care about the stop.
}
});
bitsText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
try {
bits = Integer.parseInt(bitsText.getText().toString());
if (bits < minBits) {
bits = minBits;
bitsText.setText(String.valueOf(bits));
}
} catch (NumberFormatException nfe) {
bits = DEFAULT_BITS;
bitsText.setText(String.valueOf(bits));
}
bitsSlider.setProgress(bits - minBits);
}
}
});
save.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
GeneratePubkeyActivity.this.save.setEnabled(false);
GeneratePubkeyActivity.this.startEntropyGather();
}
});
}
private void checkEntries() {
boolean allowSave = true;
if (!password1.getText().toString().equals(password2.getText().toString()))
allowSave = false;
if (nickname.getText().length() == 0)
allowSave = false;
save.setEnabled(allowSave);
}
private void startEntropyGather() {
final View entropyView = inflater.inflate(R.layout.dia_gatherentropy, null, false);
((EntropyView)entropyView.findViewById(R.id.entropy)).addOnEntropyGatheredListener(GeneratePubkeyActivity.this);
entropyDialog = new EntropyDialog(GeneratePubkeyActivity.this, entropyView);
entropyDialog.show();
}
public void onEntropyGathered(byte[] entropy) {
// For some reason the entropy dialog was aborted, exit activity
if (entropy == null) {
finish();
return;
}
this.entropy = entropy.clone();
int numSetBits = 0;
for (int i = 0; i < 20; i++)
numSetBits += measureNumberOfSetBits(this.entropy[i]);
Log.d(TAG, "Entropy distribution=" + (int)(100.0 * numSetBits / 160.0) + "%");
Log.d(TAG, "entropy gathered; attemping to generate key...");
startKeyGen();
}
private void startKeyGen() {
progress = new ProgressDialog(GeneratePubkeyActivity.this);
progress.setMessage(GeneratePubkeyActivity.this.getResources().getText(R.string.pubkey_generating));
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
Thread keyGenThread = new Thread(mKeyGen);
keyGenThread.setName("KeyGen");
keyGenThread.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
GeneratePubkeyActivity.this.finish();
}
};
final private Runnable mKeyGen = new Runnable() {
public void run() {
try {
boolean encrypted = false;
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(entropy);
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(keyType);
keyPairGen.initialize(bits, random);
KeyPair pair = keyPairGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
String secret = password1.getText().toString();
if (secret.length() > 0)
encrypted = true;
Log.d(TAG, "private: " + PubkeyUtils.formatKey(priv));
Log.d(TAG, "public: " + PubkeyUtils.formatKey(pub));
PubkeyBean pubkey = new PubkeyBean();
pubkey.setNickname(nickname.getText().toString());
pubkey.setType(keyType);
pubkey.setPrivateKey(PubkeyUtils.getEncodedPrivate(priv, secret));
pubkey.setPublicKey(PubkeyUtils.getEncodedPublic(pub));
pubkey.setEncrypted(encrypted);
pubkey.setStartup(unlockAtStartup.isChecked());
pubkey.setConfirmUse(confirmUse.isChecked());
PubkeyDatabase pubkeydb = new PubkeyDatabase(GeneratePubkeyActivity.this);
pubkeydb.savePubkey(pubkey);
pubkeydb.close();
} catch (Exception e) {
Log.e(TAG, "Could not generate key pair");
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
final private TextWatcher textChecker = new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
checkEntries();
}
};
private int measureNumberOfSetBits(byte b) {
int numSetBits = 0;
for (int i = 0; i < 8; i++) {
if ((b & 1) == 1)
numSetBits++;
b >>= 1;
}
return numSetBits;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.bean;
import org.connectbot.util.HostDatabase;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
public class PortForwardBean extends AbstractBean {
public static final String BEAN_NAME = "portforward";
/* Database fields */
private long id = -1;
private long hostId = -1;
private String nickname = null;
private String type = null;
private int sourcePort = -1;
private String destAddr = null;
private int destPort = -1;
/* Transient values */
private boolean enabled = false;
private Object identifier = null;
/**
* @param id database ID of port forward
* @param nickname Nickname to use to identify port forward
* @param type One of the port forward types from {@link HostDatabase}
* @param sourcePort Source port number
* @param destAddr Destination hostname or IP address
* @param destPort Destination port number
*/
public PortForwardBean(long id, long hostId, String nickname, String type, int sourcePort, String destAddr, int destPort) {
this.id = id;
this.hostId = hostId;
this.nickname = nickname;
this.type = type;
this.sourcePort = sourcePort;
this.destAddr = destAddr;
this.destPort = destPort;
}
/**
* @param type One of the port forward types from {@link HostDatabase}
* @param source Source port number
* @param dest Destination is "host:port" format
*/
public PortForwardBean(long hostId, String nickname, String type, String source, String dest) {
this.hostId = hostId;
this.nickname = nickname;
this.type = type;
this.sourcePort = Integer.parseInt(source);
setDest(dest);
}
public String getBeanName() {
return BEAN_NAME;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* @return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param sourcePort the sourcePort to set
*/
public void setSourcePort(int sourcePort) {
this.sourcePort = sourcePort;
}
/**
* @return the sourcePort
*/
public int getSourcePort() {
return sourcePort;
}
/**
* @param dest The destination in "host:port" format
*/
public final void setDest(String dest) {
String[] destSplit = dest.split(":");
this.destAddr = destSplit[0];
if (destSplit.length > 1)
this.destPort = Integer.parseInt(destSplit[1]);
}
/**
* @param destAddr the destAddr to set
*/
public void setDestAddr(String destAddr) {
this.destAddr = destAddr;
}
/**
* @return the destAddr
*/
public String getDestAddr() {
return destAddr;
}
/**
* @param destPort the destPort to set
*/
public void setDestPort(int destPort) {
this.destPort = destPort;
}
/**
* @return the destPort
*/
public int getDestPort() {
return destPort;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param identifier the identifier of this particular type to set
*/
public void setIdentifier(Object identifier) {
this.identifier = identifier;
}
/**
* @return the identifier used by this particular type
*/
public Object getIdentifier() {
return identifier;
}
/**
* @return human readable description of the port forward
*/
public CharSequence getDescription() {
String description = "Unknown type";
if (HostDatabase.PORTFORWARD_LOCAL.equals(type)) {
description = String.format("Local port %d to %s:%d", sourcePort, destAddr, destPort);
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(type)) {
description = String.format("Remote port %d to %s:%d", sourcePort, destAddr, destPort);
/* I don't think we need the SOCKS4 type.
} else if (HostDatabase.PORTFORWARD_DYNAMIC4.equals(type)) {
description = String.format("Dynamic port %d (SOCKS4)", sourcePort);
*/
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(type)) {
description = String.format("Dynamic port %d (SOCKS)", sourcePort);
}
return description;
}
/**
* @return
*/
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(HostDatabase.FIELD_PORTFORWARD_HOSTID, hostId);
values.put(HostDatabase.FIELD_PORTFORWARD_NICKNAME, nickname);
values.put(HostDatabase.FIELD_PORTFORWARD_TYPE, type);
values.put(HostDatabase.FIELD_PORTFORWARD_SOURCEPORT, sourcePort);
values.put(HostDatabase.FIELD_PORTFORWARD_DESTADDR, destAddr);
values.put(HostDatabase.FIELD_PORTFORWARD_DESTPORT, destPort);
return values;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.bean;
import de.mud.terminal.VDUBuffer;
/**
* @author Kenny Root
* Keep track of a selection area for the terminal copying mechanism.
* If the orientation is flipped one way, swap the bottom and top or
* left and right to keep it in the correct orientation.
*/
public class SelectionArea {
private int top;
private int bottom;
private int left;
private int right;
private int maxColumns;
private int maxRows;
private boolean selectingOrigin;
public SelectionArea() {
reset();
}
public final void reset() {
top = left = bottom = right = 0;
selectingOrigin = true;
}
/**
* @param columns
* @param rows
*/
public void setBounds(int columns, int rows) {
maxColumns = columns - 1;
maxRows = rows - 1;
}
private int checkBounds(int value, int max) {
if (value < 0)
return 0;
else if (value > max)
return max;
else
return value;
}
public boolean isSelectingOrigin() {
return selectingOrigin;
}
public void finishSelectingOrigin() {
selectingOrigin = false;
}
public void decrementRow() {
if (selectingOrigin)
setTop(top - 1);
else
setBottom(bottom - 1);
}
public void incrementRow() {
if (selectingOrigin)
setTop(top + 1);
else
setBottom(bottom + 1);
}
public void setRow(int row) {
if (selectingOrigin)
setTop(row);
else
setBottom(row);
}
private void setTop(int top) {
this.top = bottom = checkBounds(top, maxRows);
}
public int getTop() {
return Math.min(top, bottom);
}
private void setBottom(int bottom) {
this.bottom = checkBounds(bottom, maxRows);
}
public int getBottom() {
return Math.max(top, bottom);
}
public void decrementColumn() {
if (selectingOrigin)
setLeft(left - 1);
else
setRight(right - 1);
}
public void incrementColumn() {
if (selectingOrigin)
setLeft(left + 1);
else
setRight(right + 1);
}
public void setColumn(int column) {
if (selectingOrigin)
setLeft(column);
else
setRight(column);
}
private void setLeft(int left) {
this.left = right = checkBounds(left, maxColumns);
}
public int getLeft() {
return Math.min(left, right);
}
private void setRight(int right) {
this.right = checkBounds(right, maxColumns);
}
public int getRight() {
return Math.max(left, right);
}
public String copyFrom(VDUBuffer vb) {
int size = (getRight() - getLeft() + 1) * (getBottom() - getTop() + 1);
StringBuffer buffer = new StringBuffer(size);
for(int y = getTop(); y <= getBottom(); y++) {
int lastNonSpace = buffer.length();
for (int x = getLeft(); x <= getRight(); x++) {
// only copy printable chars
char c = vb.getChar(x, y);
if (!Character.isDefined(c) ||
(Character.isISOControl(c) && c != '\t'))
c = ' ';
if (c != ' ')
lastNonSpace = buffer.length();
buffer.append(c);
}
// Don't leave a bunch of spaces in our copy buffer.
if (buffer.length() > lastNonSpace)
buffer.delete(lastNonSpace + 1, buffer.length());
if (y != bottom)
buffer.append("\n");
}
return buffer.toString();
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("SelectionArea[top=");
buffer.append(top);
buffer.append(", bottom=");
buffer.append(bottom);
buffer.append(", left=");
buffer.append(left);
buffer.append(", right=");
buffer.append(right);
buffer.append(", maxColumns=");
buffer.append(maxColumns);
buffer.append(", maxRows=");
buffer.append(maxRows);
buffer.append(", isSelectingOrigin=");
buffer.append(isSelectingOrigin());
buffer.append("]");
return buffer.toString();
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.bean;
import java.util.Map.Entry;
import org.connectbot.util.XmlBuilder;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
abstract class AbstractBean {
public abstract ContentValues getValues();
public abstract String getBeanName();
public String toXML() {
XmlBuilder xml = new XmlBuilder();
xml.append(String.format("<%s>", getBeanName()));
ContentValues values = getValues();
for (Entry<String, Object> entry : values.valueSet()) {
Object value = entry.getValue();
if (value != null)
xml.append(entry.getKey(), value);
}
xml.append(String.format("</%s>", getBeanName()));
return xml.toString();
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.bean;
import org.connectbot.util.HostDatabase;
import android.content.ContentValues;
import android.net.Uri;
/**
* @author Kenny Root
*
*/
public class HostBean extends AbstractBean {
public static final String BEAN_NAME = "host";
/* Database fields */
private long id = -1;
private String nickname = null;
private String username = null;
private String hostname = null;
private int port = 22;
private String protocol = "ssh";
private String hostKeyAlgo = null;
private byte[] hostKey = null;
private long lastConnect = -1;
private String color;
private boolean useKeys = true;
private String useAuthAgent = HostDatabase.AUTHAGENT_NO;
private String postLogin = null;
private long pubkeyId = -1;
private boolean wantSession = true;
private String delKey = HostDatabase.DELKEY_DEL;
private int fontSize = -1;
private boolean compression = false;
private String encoding = HostDatabase.ENCODING_DEFAULT;
private boolean stayConnected = false;
public HostBean() {
}
@Override
public String getBeanName() {
return BEAN_NAME;
}
public HostBean(String nickname, String protocol, String username, String hostname, int port) {
this.nickname = nickname;
this.protocol = protocol;
this.username = username;
this.hostname = hostname;
this.port = port;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getHostname() {
return hostname;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return port;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocol() {
return protocol;
}
public void setHostKeyAlgo(String hostKeyAlgo) {
this.hostKeyAlgo = hostKeyAlgo;
}
public String getHostKeyAlgo() {
return hostKeyAlgo;
}
public void setHostKey(byte[] hostKey) {
if (hostKey == null)
this.hostKey = null;
else
this.hostKey = hostKey.clone();
}
public byte[] getHostKey() {
if (hostKey == null)
return null;
else
return hostKey.clone();
}
public void setLastConnect(long lastConnect) {
this.lastConnect = lastConnect;
}
public long getLastConnect() {
return lastConnect;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setUseKeys(boolean useKeys) {
this.useKeys = useKeys;
}
public boolean getUseKeys() {
return useKeys;
}
public void setUseAuthAgent(String useAuthAgent) {
this.useAuthAgent = useAuthAgent;
}
public String getUseAuthAgent() {
return useAuthAgent;
}
public void setPostLogin(String postLogin) {
this.postLogin = postLogin;
}
public String getPostLogin() {
return postLogin;
}
public void setPubkeyId(long pubkeyId) {
this.pubkeyId = pubkeyId;
}
public long getPubkeyId() {
return pubkeyId;
}
public void setWantSession(boolean wantSession) {
this.wantSession = wantSession;
}
public boolean getWantSession() {
return wantSession;
}
public void setDelKey(String delKey) {
this.delKey = delKey;
}
public String getDelKey() {
return delKey;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
public int getFontSize() {
return fontSize;
}
public void setCompression(boolean compression) {
this.compression = compression;
}
public boolean getCompression() {
return compression;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding() {
return this.encoding;
}
public void setStayConnected(boolean stayConnected) {
this.stayConnected = stayConnected;
}
public boolean getStayConnected() {
return stayConnected;
}
public String getDescription() {
String description = String.format("%s@%s", username, hostname);
if (port != 22)
description += String.format(":%d", port);
return description;
}
@Override
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(HostDatabase.FIELD_HOST_NICKNAME, nickname);
values.put(HostDatabase.FIELD_HOST_PROTOCOL, protocol);
values.put(HostDatabase.FIELD_HOST_USERNAME, username);
values.put(HostDatabase.FIELD_HOST_HOSTNAME, hostname);
values.put(HostDatabase.FIELD_HOST_PORT, port);
values.put(HostDatabase.FIELD_HOST_HOSTKEYALGO, hostKeyAlgo);
values.put(HostDatabase.FIELD_HOST_HOSTKEY, hostKey);
values.put(HostDatabase.FIELD_HOST_LASTCONNECT, lastConnect);
values.put(HostDatabase.FIELD_HOST_COLOR, color);
values.put(HostDatabase.FIELD_HOST_USEKEYS, Boolean.toString(useKeys));
values.put(HostDatabase.FIELD_HOST_USEAUTHAGENT, useAuthAgent);
values.put(HostDatabase.FIELD_HOST_POSTLOGIN, postLogin);
values.put(HostDatabase.FIELD_HOST_PUBKEYID, pubkeyId);
values.put(HostDatabase.FIELD_HOST_WANTSESSION, Boolean.toString(wantSession));
values.put(HostDatabase.FIELD_HOST_DELKEY, delKey);
values.put(HostDatabase.FIELD_HOST_FONTSIZE, fontSize);
values.put(HostDatabase.FIELD_HOST_COMPRESSION, Boolean.toString(compression));
values.put(HostDatabase.FIELD_HOST_ENCODING, encoding);
values.put(HostDatabase.FIELD_HOST_STAYCONNECTED, stayConnected);
return values;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof HostBean))
return false;
HostBean host = (HostBean)o;
if (id != -1 && host.getId() != -1)
return host.getId() == id;
if (nickname == null) {
if (host.getNickname() != null)
return false;
} else if (!nickname.equals(host.getNickname()))
return false;
if (protocol == null) {
if (host.getProtocol() != null)
return false;
} else if (!protocol.equals(host.getProtocol()))
return false;
if (username == null) {
if (host.getUsername() != null)
return false;
} else if (!username.equals(host.getUsername()))
return false;
if (hostname == null) {
if (host.getHostname() != null)
return false;
} else if (!hostname.equals(host.getHostname()))
return false;
if (port != host.getPort())
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
if (id != -1)
return (int)id;
hash = 31 * hash + (null == nickname ? 0 : nickname.hashCode());
hash = 31 * hash + (null == protocol ? 0 : protocol.hashCode());
hash = 31 * hash + (null == username ? 0 : username.hashCode());
hash = 31 * hash + (null == hostname ? 0 : hostname.hashCode());
hash = 31 * hash + port;
return hash;
}
/**
* @return URI identifying this HostBean
*/
public Uri getUri() {
StringBuilder sb = new StringBuilder();
sb.append(protocol)
.append("://");
if (username != null)
sb.append(Uri.encode(username))
.append('@');
sb.append(Uri.encode(hostname))
.append(':')
.append(port)
.append("/#")
.append(nickname);
return Uri.parse(sb.toString());
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.bean;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
public class PubkeyBean extends AbstractBean {
public static final String BEAN_NAME = "pubkey";
private static final String KEY_TYPE_RSA = "RSA";
private static final String KEY_TYPE_DSA = "DSA";
/* Database fields */
private long id;
private String nickname;
private String type;
private byte[] privateKey;
private PublicKey publicKey;
private boolean encrypted = false;
private boolean startup = false;
private boolean confirmUse = false;
private int lifetime = 0;
/* Transient values */
private boolean unlocked = false;
private Object unlockedPrivate = null;
@Override
public String getBeanName() {
return BEAN_NAME;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setPrivateKey(byte[] privateKey) {
if (privateKey == null)
this.privateKey = null;
else
this.privateKey = privateKey.clone();
}
public byte[] getPrivateKey() {
if (privateKey == null)
return null;
else
return privateKey.clone();
}
private PublicKey decodePublicKeyAs(EncodedKeySpec keySpec, String keyType) {
try {
final KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
return null;
} catch (InvalidKeySpecException e) {
return null;
}
}
public void setPublicKey(byte[] encoded) {
final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
if (type != null) {
publicKey = decodePublicKeyAs(pubKeySpec, type);
} else {
publicKey = decodePublicKeyAs(pubKeySpec, KEY_TYPE_RSA);
if (publicKey != null) {
type = KEY_TYPE_RSA;
} else {
publicKey = decodePublicKeyAs(pubKeySpec, KEY_TYPE_DSA);
if (publicKey != null) {
type = KEY_TYPE_DSA;
}
}
}
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public boolean isEncrypted() {
return encrypted;
}
public void setStartup(boolean startup) {
this.startup = startup;
}
public boolean isStartup() {
return startup;
}
public void setConfirmUse(boolean confirmUse) {
this.confirmUse = confirmUse;
}
public boolean isConfirmUse() {
return confirmUse;
}
public void setLifetime(int lifetime) {
this.lifetime = lifetime;
}
public int getLifetime() {
return lifetime;
}
public void setUnlocked(boolean unlocked) {
this.unlocked = unlocked;
}
public boolean isUnlocked() {
return unlocked;
}
public void setUnlockedPrivate(Object unlockedPrivate) {
this.unlockedPrivate = unlockedPrivate;
}
public Object getUnlockedPrivate() {
return unlockedPrivate;
}
public String getDescription() {
StringBuilder sb = new StringBuilder();
if (publicKey instanceof RSAPublicKey) {
int bits = ((RSAPublicKey) publicKey).getModulus().bitLength();
sb.append("RSA ");
sb.append(bits);
sb.append("-bit");
} else if (publicKey instanceof DSAPublicKey) {
sb.append("DSA 1024-bit");
} else {
sb.append("Unknown Key Type");
}
if (encrypted)
sb.append(" (encrypted)");
return sb.toString();
}
/* (non-Javadoc)
* @see org.connectbot.bean.AbstractBean#getValues()
*/
@Override
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(PubkeyDatabase.FIELD_PUBKEY_NICKNAME, nickname);
values.put(PubkeyDatabase.FIELD_PUBKEY_TYPE, type);
values.put(PubkeyDatabase.FIELD_PUBKEY_PRIVATE, privateKey);
values.put(PubkeyDatabase.FIELD_PUBKEY_PUBLIC, publicKey.getEncoded());
values.put(PubkeyDatabase.FIELD_PUBKEY_ENCRYPTED, encrypted ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_STARTUP, startup ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_CONFIRMUSE, confirmUse ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_LIFETIME, lifetime);
return values;
}
public boolean changePassword(String oldPassword, String newPassword) throws Exception {
PrivateKey priv;
try {
priv = PubkeyUtils.decodePrivate(getPrivateKey(), getType(), oldPassword);
} catch (Exception e) {
return false;
}
setPrivateKey(PubkeyUtils.getEncodedPrivate(priv, newPassword));
setEncrypted(newPassword.length() > 0);
return true;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.lang.ref.WeakReference;
import java.util.List;
import org.connectbot.bean.SelectionArea;
import org.connectbot.service.PromptHelper;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalKeyListener;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PreferenceConstants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import de.mud.terminal.vt320;
public class ConsoleActivity extends Activity {
public final static String TAG = "ConnectBot.ConsoleActivity";
protected static final int REQUEST_EDIT = 1;
private static final int CLICK_TIME = 400;
private static final float MAX_CLICK_DISTANCE = 25f;
private static final int KEYBOARD_DISPLAY_TIME = 1500;
// Direction to shift the ViewFlipper
private static final int SHIFT_LEFT = 0;
private static final int SHIFT_RIGHT = 1;
protected ViewFlipper flip = null;
protected TerminalManager bound = null;
protected LayoutInflater inflater = null;
private SharedPreferences prefs = null;
// determines whether or not menuitem accelerators are bound
// otherwise they collide with an external keyboard's CTRL-char
private boolean hardKeyboard = false;
protected Uri requested;
protected ClipboardManager clipboard;
private RelativeLayout stringPromptGroup;
protected EditText stringPrompt;
private TextView stringPromptInstructions;
private RelativeLayout booleanPromptGroup;
private TextView booleanPrompt;
private Button booleanYes, booleanNo;
private TextView empty;
private Animation slide_left_in, slide_left_out, slide_right_in, slide_right_out, fade_stay_hidden, fade_out_delayed;
private Animation keyboard_fade_in, keyboard_fade_out;
private float lastX, lastY;
private InputMethodManager inputManager;
private MenuItem disconnect, copy, paste, portForward, resize, urlscan;
protected TerminalBridge copySource = null;
private int lastTouchRow, lastTouchCol;
private boolean forcedOrientation;
private Handler handler = new Handler();
private ImageView mKeyboardButton;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// let manager know about our event handling services
bound.disconnectHandler = disconnectHandler;
Log.d(TAG, String.format("Connected to TerminalManager and found bridges.size=%d", bound.bridges.size()));
bound.setResizeAllowed(true);
// clear out any existing bridges and record requested index
flip.removeAllViews();
final String requestedNickname = (requested != null) ? requested.getFragment() : null;
int requestedIndex = 0;
TerminalBridge requestedBridge = bound.getConnectedBridge(requestedNickname);
// If we didn't find the requested connection, try opening it
if (requestedNickname != null && requestedBridge == null) {
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s), so creating one now", requested.toString(), requestedNickname));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
}
}
// create views for all bridges on this service
for (TerminalBridge bridge : bound.bridges) {
final int currentIndex = addNewTerminalView(bridge);
// check to see if this bridge was requested
if (bridge == requestedBridge)
requestedIndex = currentIndex;
}
setDisplayedTerminal(requestedIndex);
}
public void onServiceDisconnected(ComponentName className) {
// tell each bridge to forget about our prompt handler
synchronized (bound.bridges) {
for(TerminalBridge bridge : bound.bridges)
bridge.promptHelper.setHandler(null);
}
flip.removeAllViews();
updateEmptyVisible();
bound = null;
}
};
protected Handler promptHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// someone below us requested to display a prompt
updatePromptVisible();
}
};
protected Handler disconnectHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler");
// someone below us requested to display a password dialog
// they are sending nickname and requested
TerminalBridge bridge = (TerminalBridge)msg.obj;
if (bridge.isAwaitingClose())
closeBridge(bridge);
}
};
/**
* @param bridge
*/
private void closeBridge(final TerminalBridge bridge) {
synchronized (flip) {
final int flipIndex = getFlipIndex(bridge);
if (flipIndex >= 0) {
if (flip.getDisplayedChild() == flipIndex) {
shiftCurrentTerminal(SHIFT_LEFT);
}
flip.removeViewAt(flipIndex);
/* TODO Remove this workaround when ViewFlipper is fixed to listen
* to view removals. Android Issue 1784
*/
final int numChildren = flip.getChildCount();
if (flip.getDisplayedChild() >= numChildren &&
numChildren > 0) {
flip.setDisplayedChild(numChildren - 1);
}
updateEmptyVisible();
}
// If we just closed the last bridge, go back to the previous activity.
if (flip.getChildCount() == 0) {
finish();
}
}
}
protected View findCurrentView(int id) {
View view = flip.getCurrentView();
if(view == null) return null;
return view.findViewById(id);
}
protected PromptHelper getCurrentPromptHelper() {
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return null;
return ((TerminalView)view).bridge.promptHelper;
}
protected void hideAllPrompts() {
stringPromptGroup.setVisibility(View.GONE);
booleanPromptGroup.setVisibility(View.GONE);
}
// more like configureLaxMode -- enable network IO on UI thread
private void configureStrictMode() {
try {
Class.forName("android.os.StrictMode");
StrictModeSetup.run();
} catch (ClassNotFoundException e) {
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
configureStrictMode();
hardKeyboard = getResources().getConfiguration().keyboard ==
Configuration.KEYBOARD_QWERTY;
this.setContentView(R.layout.act_console);
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// hide status bar if requested by user
if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// TODO find proper way to disable volume key beep if it exists.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// handle requested console from incoming intent
requested = getIntent().getData();
inflater = LayoutInflater.from(this);
flip = (ViewFlipper)findViewById(R.id.console_flip);
empty = (TextView)findViewById(android.R.id.empty);
stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
stringPrompt = (EditText)findViewById(R.id.console_password);
stringPrompt.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_UP) return false;
if(keyCode != KeyEvent.KEYCODE_ENTER) return false;
// pass collected password down to current terminal
String value = stringPrompt.getText().toString();
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return false;
helper.setResponse(value);
// finally clear password for next user
stringPrompt.setText("");
updatePromptVisible();
return true;
}
});
booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
booleanPrompt = (TextView)findViewById(R.id.console_prompt);
booleanYes = (Button)findViewById(R.id.console_prompt_yes);
booleanYes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.TRUE);
updatePromptVisible();
}
});
booleanNo = (Button)findViewById(R.id.console_prompt_no);
booleanNo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.FALSE);
updatePromptVisible();
}
});
// preload animations for terminal switching
slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);
// Preload animation for keyboard button
keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);
inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);
mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
mKeyboardButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null)
return;
inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
ctrlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.metaPress(TerminalKeyListener.META_CTRL_ON);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
escButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
keyboardGroup.setVisibility(View.GONE);
}
});
// detect fling gestures to switch between terminals
final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
private float totalY = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final float distx = e2.getRawX() - e1.getRawX();
final float disty = e2.getRawY() - e1.getRawY();
final int goalwidth = flip.getWidth() / 2;
// need to slide across half of display to trigger console change
// make sure user kept a steady hand horizontally
if (Math.abs(disty) < (flip.getHeight() / 4)) {
if (distx > goalwidth) {
shiftCurrentTerminal(SHIFT_RIGHT);
return true;
}
if (distx < -goalwidth) {
shiftCurrentTerminal(SHIFT_LEFT);
return true;
}
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// if copying, then ignore
if (copySource != null && copySource.isSelectingForCopy())
return false;
if (e1 == null || e2 == null)
return false;
// if releasing then reset total scroll
if (e2.getAction() == MotionEvent.ACTION_UP) {
totalY = 0;
}
// activate consider if within x tolerance
if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {
View flip = findCurrentView(R.id.console_flip);
if(flip == null) return false;
TerminalView terminal = (TerminalView)flip;
// estimate how many rows we have scrolled through
// accumulate distance that doesn't trigger immediate scroll
totalY += distanceY;
final int moved = (int)(totalY / terminal.bridge.charHeight);
// consume as scrollback only if towards right half of screen
if (e2.getX() > flip.getWidth() / 2) {
if (moved != 0) {
int base = terminal.bridge.buffer.getWindowBase();
terminal.bridge.buffer.setWindowBase(base + moved);
totalY = 0;
return true;
}
} else {
// otherwise consume as pgup/pgdown for every 5 lines
if (moved > 5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
} else if (moved < -5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
}
}
}
return false;
}
});
flip.setLongClickable(true);
flip.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// when copying, highlight the area
if (copySource != null && copySource.isSelectingForCopy()) {
int row = (int)Math.floor(event.getY() / copySource.charHeight);
int col = (int)Math.floor(event.getX() / copySource.charWidth);
SelectionArea area = copySource.getSelectionArea();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// recording starting area
if (area.isSelectingOrigin()) {
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
}
return true;
case MotionEvent.ACTION_MOVE:
/* ignore when user hasn't moved since last time so
* we can fine-tune with directional pad
*/
if (row == lastTouchRow && col == lastTouchCol)
return true;
// if the user moves, start the selection for other corner
area.finishSelectingOrigin();
// update selected area
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
return true;
case MotionEvent.ACTION_UP:
/* If they didn't move their finger, maybe they meant to
* select the rest of the text with the directional pad.
*/
if (area.getLeft() == area.getRight() &&
area.getTop() == area.getBottom()) {
return true;
}
// copy selected area to clipboard
String copiedText = area.copyFrom(copySource.buffer);
clipboard.setText(copiedText);
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show();
// fall through to clear state
case MotionEvent.ACTION_CANCEL:
// make sure we clear any highlighted area
area.reset();
copySource.setSelectingForCopy(false);
copySource.redraw();
return true;
}
}
Configuration config = getResources().getConfiguration();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lastX = event.getX();
lastY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_UP
&& keyboardGroup.getVisibility() == View.GONE
&& event.getEventTime() - event.getDownTime() < CLICK_TIME
&& Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
&& Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
keyboardGroup.startAnimation(keyboard_fade_in);
keyboardGroup.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
public void run() {
if (keyboardGroup.getVisibility() == View.GONE)
return;
keyboardGroup.startAnimation(keyboard_fade_out);
keyboardGroup.setVisibility(View.GONE);
}
}, KEYBOARD_DISPLAY_TIME);
}
// pass any touch events back to detector
return detect.onTouchEvent(event);
}
});
}
/**
*
*/
private void configureOrientation() {
String rotateDefault;
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_NOKEYS)
rotateDefault = PreferenceConstants.ROTATION_PORTRAIT;
else
rotateDefault = PreferenceConstants.ROTATION_LANDSCAPE;
String rotate = prefs.getString(PreferenceConstants.ROTATION, rotateDefault);
if (PreferenceConstants.ROTATION_DEFAULT.equals(rotate))
rotate = rotateDefault;
// request a forced orientation if requested by user
if (PreferenceConstants.ROTATION_LANDSCAPE.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
forcedOrientation = true;
} else if (PreferenceConstants.ROTATION_PORTRAIT.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
forcedOrientation = true;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
forcedOrientation = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
View view = findCurrentView(R.id.console_flip);
final boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
menu.setQwertyMode(true);
disconnect = menu.add(R.string.list_host_disconnect);
if (hardKeyboard)
disconnect.setAlphabeticShortcut('w');
if (!sessionOpen && disconnected)
disconnect.setTitle(R.string.console_menu_close);
disconnect.setEnabled(activeTerminal);
disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// disconnect or close the currently visible session
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
bridge.dispatchDisconnect(true);
return true;
}
});
copy = menu.add(R.string.console_menu_copy);
if (hardKeyboard)
copy.setAlphabeticShortcut('c');
copy.setIcon(android.R.drawable.ic_menu_set_as);
copy.setEnabled(activeTerminal);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// mark as copying and reset any previous bounds
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
copySource = terminalView.bridge;
SelectionArea area = copySource.getSelectionArea();
area.reset();
area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
copySource.setSelectingForCopy(true);
// Make sure we show the initial selection
copySource.redraw();
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG).show();
return true;
}
});
paste = menu.add(R.string.console_menu_paste);
if (hardKeyboard)
paste.setAlphabeticShortcut('v');
paste.setIcon(android.R.drawable.ic_menu_edit);
paste.setEnabled(clipboard.hasText() && sessionOpen);
paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// force insert of clipboard text into current console
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
// pull string from clipboard and generate all events to force down
String clip = clipboard.getText().toString();
bridge.injectString(clip);
return true;
}
});
portForward = menu.add(R.string.console_menu_portforwards);
if (hardKeyboard)
portForward.setAlphabeticShortcut('f');
portForward.setIcon(android.R.drawable.ic_menu_manage);
portForward.setEnabled(sessionOpen && canForwardPorts);
portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
urlscan = menu.add(R.string.console_menu_urlscan);
if (hardKeyboard)
urlscan.setAlphabeticShortcut('u');
urlscan.setIcon(android.R.drawable.ic_menu_search);
urlscan.setEnabled(activeTerminal);
urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
List<String> urls = terminalView.bridge.scanForURLs();
Dialog urlDialog = new Dialog(ConsoleActivity.this);
urlDialog.setTitle(R.string.console_menu_urlscan);
ListView urlListView = new ListView(ConsoleActivity.this);
URLItemListener urlListener = new URLItemListener(ConsoleActivity.this);
urlListView.setOnItemClickListener(urlListener);
urlListView.setAdapter(new ArrayAdapter<String>(ConsoleActivity.this, android.R.layout.simple_list_item_1, urls));
urlDialog.setContentView(urlListView);
urlDialog.show();
return true;
}
});
resize = menu.add(R.string.console_menu_resize);
if (hardKeyboard)
resize.setAlphabeticShortcut('s');
resize.setIcon(android.R.drawable.ic_menu_crop);
resize.setEnabled(sessionOpen);
resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
new AlertDialog.Builder(ConsoleActivity.this)
.setView(resizeView)
.setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int width, height;
try {
width = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.width))
.getText().toString());
height = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.height))
.getText().toString());
} catch (NumberFormatException nfe) {
// TODO change this to a real dialog where we can
// make the input boxes turn red to indicate an error.
return;
}
terminalView.forceSize(width, height);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
final View view = findCurrentView(R.id.console_flip);
boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
disconnect.setEnabled(activeTerminal);
if (sessionOpen || !disconnected)
disconnect.setTitle(R.string.list_host_disconnect);
else
disconnect.setTitle(R.string.console_menu_close);
copy.setEnabled(activeTerminal);
paste.setEnabled(clipboard.hasText() && sessionOpen);
portForward.setEnabled(sessionOpen && canForwardPorts);
urlscan.setEnabled(activeTerminal);
resize.setEnabled(sessionOpen);
return true;
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onStart() {
super.onStart();
// connect with manager service to find all bridges
// when connected it will insert all views
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
if (forcedOrientation && bound != null)
bound.setResizeAllowed(false);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
// Make sure we don't let the screen fall asleep.
// This also keeps the Wi-Fi chipset from disconnecting us.
if (prefs.getBoolean(PreferenceConstants.KEEP_ALIVE, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
configureOrientation();
if (forcedOrientation && bound != null)
bound.setResizeAllowed(true);
}
/* (non-Javadoc)
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent called");
requested = intent.getData();
if (requested == null) {
Log.e(TAG, "Got null intent data in onNewIntent()");
return;
}
if (bound == null) {
Log.e(TAG, "We're not bound in onNewIntent()");
return;
}
TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment());
int requestedIndex = 0;
synchronized (flip) {
if (requestedBridge == null) {
// If we didn't find the requested connection, try opening it
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s),"+
"so creating one now", requested.toString(), requested.getFragment()));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
// TODO: We should display an error dialog here.
return;
}
requestedIndex = addNewTerminalView(requestedBridge);
} else {
final int flipIndex = getFlipIndex(requestedBridge);
if (flipIndex > requestedIndex) {
requestedIndex = flipIndex;
}
}
setDisplayedTerminal(requestedIndex);
}
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
}
protected void shiftCurrentTerminal(final int direction) {
View overlay;
synchronized (flip) {
boolean shouldAnimate = flip.getChildCount() > 1;
// Only show animation if there is something else to go to.
if (shouldAnimate) {
// keep current overlay from popping up again
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_stay_hidden);
if (direction == SHIFT_LEFT) {
flip.setInAnimation(slide_left_in);
flip.setOutAnimation(slide_left_out);
flip.showNext();
} else if (direction == SHIFT_RIGHT) {
flip.setInAnimation(slide_right_in);
flip.setOutAnimation(slide_right_out);
flip.showPrevious();
}
}
ConsoleActivity.this.updateDefault();
if (shouldAnimate) {
// show overlay on new slide and start fade
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_out_delayed);
}
updatePromptVisible();
}
}
/**
* Save the currently shown {@link TerminalView} as the default. This is
* saved back down into {@link TerminalManager} where we can read it again
* later.
*/
private void updateDefault() {
// update the current default terminal
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
TerminalView terminal = (TerminalView)view;
if(bound == null) return;
bound.defaultBridge = terminal.bridge;
}
protected void updateEmptyVisible() {
// update visibility of empty status message
empty.setVisibility((flip.getChildCount() == 0) ? View.VISIBLE : View.GONE);
}
/**
* Show any prompts requested by the currently visible {@link TerminalView}.
*/
protected void updatePromptVisible() {
// check if our currently-visible terminalbridge is requesting any prompt services
View view = findCurrentView(R.id.console_flip);
// Hide all the prompts in case a prompt request was canceled
hideAllPrompts();
if(!(view instanceof TerminalView)) {
// we dont have an active view, so hide any prompts
return;
}
PromptHelper prompt = ((TerminalView)view).bridge.promptHelper;
if(String.class.equals(prompt.promptRequested)) {
stringPromptGroup.setVisibility(View.VISIBLE);
String instructions = prompt.promptInstructions;
if (instructions != null && instructions.length() > 0) {
stringPromptInstructions.setVisibility(View.VISIBLE);
stringPromptInstructions.setText(instructions);
} else
stringPromptInstructions.setVisibility(View.GONE);
stringPrompt.setText("");
stringPrompt.setHint(prompt.promptHint);
stringPrompt.requestFocus();
} else if(Boolean.class.equals(prompt.promptRequested)) {
booleanPromptGroup.setVisibility(View.VISIBLE);
booleanPrompt.setText(prompt.promptHint);
booleanYes.requestFocus();
} else {
hideAllPrompts();
view.requestFocus();
}
}
private class URLItemListener implements OnItemClickListener {
private WeakReference<Context> contextRef;
URLItemListener(Context context) {
this.contextRef = new WeakReference<Context>(context);
}
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Context context = contextRef.get();
if (context == null)
return;
try {
TextView urlView = (TextView) view;
String url = urlView.getText().toString();
if (url.indexOf("://") < 0)
url = "http://" + url;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "couldn't open URL", e);
// We should probably tell the user that we couldn't find a handler...
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, String.format("onConfigurationChanged; requestedOrientation=%d, newConfig.orientation=%d", getRequestedOrientation(), newConfig.orientation));
if (bound != null) {
if (forcedOrientation &&
(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ||
(newConfig.orientation != Configuration.ORIENTATION_PORTRAIT &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT))
bound.setResizeAllowed(false);
else
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES);
mKeyboardButton.setVisibility(bound.hardKeyboardHidden ? View.VISIBLE : View.GONE);
}
}
/**
* Adds a new TerminalBridge to the current set of views in our ViewFlipper.
*
* @param bridge TerminalBridge to add to our ViewFlipper
* @return the child index of the new view in the ViewFlipper
*/
private int addNewTerminalView(TerminalBridge bridge) {
// let them know about our prompt handler services
bridge.promptHelper.setHandler(promptHandler);
// inflate each terminal view
RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.item_terminal, flip, false);
// set the terminal overlay text
TextView overlay = (TextView)view.findViewById(R.id.terminal_overlay);
overlay.setText(bridge.host.getNickname());
// and add our terminal view control, using index to place behind overlay
TerminalView terminal = new TerminalView(ConsoleActivity.this, bridge);
terminal.setId(R.id.console_flip);
view.addView(terminal, 0);
synchronized (flip) {
// finally attach to the flipper
flip.addView(view);
return flip.getChildCount() - 1;
}
}
private int getFlipIndex(TerminalBridge bridge) {
synchronized (flip) {
final int children = flip.getChildCount();
for (int i = 0; i < children; i++) {
final View view = flip.getChildAt(i).findViewById(R.id.console_flip);
if (view == null || !(view instanceof TerminalView)) {
// How did that happen?
continue;
}
final TerminalView tv = (TerminalView) view;
if (tv.bridge == bridge) {
return i;
}
}
}
return -1;
}
/**
* Displays the child in the ViewFlipper at the requestedIndex and updates the prompts.
*
* @param requestedIndex the index of the terminal view to display
*/
private void setDisplayedTerminal(int requestedIndex) {
synchronized (flip) {
try {
// show the requested bridge if found, also fade out overlay
flip.setDisplayedChild(requestedIndex);
flip.getCurrentView().findViewById(R.id.terminal_overlay)
.startAnimation(fade_out_delayed);
} catch (NullPointerException npe) {
Log.d(TAG, "View went away when we were about to display it", npe);
}
updatePromptVisible();
updateEmptyVisible();
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
/**
* @author Kenny Root
*
*/
public class HelpActivity extends Activity {
public final static String TAG = "ConnectBot.HelpActivity";
public final static String HELPDIR = "help";
public final static String SUFFIX = ".html";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_help);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_help)));
AssetManager am = this.getAssets();
LinearLayout content = (LinearLayout)this.findViewById(R.id.topics);
try {
for (String name : am.list(HELPDIR)) {
if (name.endsWith(SUFFIX)) {
Button button = new Button(this);
final String topic = name.substring(0, name.length() - SUFFIX.length());
button.setText(topic);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(HelpActivity.this, HelpTopicActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, topic);
HelpActivity.this.startActivity(intent);
}
});
content.addView(button);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "couldn't get list of help assets", e);
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.bean.SelectionArea;
import org.connectbot.service.FontSizeChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalKeyListener;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelXorXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.Toast;
import de.mud.terminal.VDUBuffer;
/**
* User interface {@link View} for showing a TerminalBridge in an
* {@link Activity}. Handles drawing bitmap updates and passing keystrokes down
* to terminal.
*
* @author jsharkey
*/
public class TerminalView extends View implements FontSizeChangedListener {
private final Context context;
public final TerminalBridge bridge;
private final Paint paint;
private final Paint cursorPaint;
private final Paint cursorStrokePaint;
// Cursor paints to distinguish modes
private Path ctrlCursor, altCursor, shiftCursor;
private RectF tempSrc, tempDst;
private Matrix scaleMatrix;
private static final Matrix.ScaleToFit scaleType = Matrix.ScaleToFit.FILL;
private Toast notification = null;
private String lastNotification = null;
private volatile boolean notifications = true;
// Related to Accessibility Features
private boolean mAccessibilityInitialized = false;
private boolean mAccessibilityActive = true;
private Object[] mAccessibilityLock = new Object[0];
private StringBuffer mAccessibilityBuffer;
private Pattern mControlCodes = null;
private Matcher mCodeMatcher = null;
private AccessibilityEventSender mEventSender = null;
private static final String BACKSPACE_CODE = "\\x08\\x1b\\[K";
private static final String CONTROL_CODE_PATTERN = "\\x1b\\[K[^m]+[m|:]";
private static final int ACCESSIBILITY_EVENT_THRESHOLD = 1000;
private static final String SCREENREADER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService";
private static final String SCREENREADER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN";
public TerminalView(Context context, TerminalBridge bridge) {
super(context);
this.context = context;
this.bridge = bridge;
paint = new Paint();
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setFocusable(true);
setFocusableInTouchMode(true);
cursorPaint = new Paint();
cursorPaint.setColor(bridge.color[bridge.defaultFg]);
cursorPaint.setXfermode(new PixelXorXfermode(bridge.color[bridge.defaultBg]));
cursorPaint.setAntiAlias(true);
cursorStrokePaint = new Paint(cursorPaint);
cursorStrokePaint.setStrokeWidth(0.1f);
cursorStrokePaint.setStyle(Paint.Style.STROKE);
/*
* Set up our cursor indicators on a 1x1 Path object which we can later
* transform to our character width and height
*/
// TODO make this into a resource somehow
shiftCursor = new Path();
shiftCursor.lineTo(0.5f, 0.33f);
shiftCursor.lineTo(1.0f, 0.0f);
altCursor = new Path();
altCursor.moveTo(0.0f, 1.0f);
altCursor.lineTo(0.5f, 0.66f);
altCursor.lineTo(1.0f, 1.0f);
ctrlCursor = new Path();
ctrlCursor.moveTo(0.0f, 0.25f);
ctrlCursor.lineTo(1.0f, 0.5f);
ctrlCursor.lineTo(0.0f, 0.75f);
// For creating the transform when the terminal resizes
tempSrc = new RectF();
tempSrc.set(0.0f, 0.0f, 1.0f, 1.0f);
tempDst = new RectF();
scaleMatrix = new Matrix();
bridge.addFontSizeChangedListener(this);
// connect our view up to the bridge
setOnKeyListener(bridge.getKeyHandler());
mAccessibilityBuffer = new StringBuffer();
// Enable accessibility features if a screen reader is active.
new AccessibilityStateTester().execute((Void) null);
}
public void destroy() {
// tell bridge to destroy its bitmap
bridge.parentDestroyed();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bridge.parentChanged(this);
scaleCursors();
}
public void onFontSizeChanged(float size) {
scaleCursors();
}
private void scaleCursors() {
// Create a scale matrix to scale our 1x1 representation of the cursor
tempDst.set(0.0f, 0.0f, bridge.charWidth, bridge.charHeight);
scaleMatrix.setRectToRect(tempSrc, tempDst, scaleType);
}
@Override
public void onDraw(Canvas canvas) {
if(bridge.bitmap != null) {
// draw the bitmap
bridge.onDraw();
// draw the bridge bitmap if it exists
canvas.drawBitmap(bridge.bitmap, 0, 0, paint);
// also draw cursor if visible
if (bridge.buffer.isCursorVisible()) {
int cursorColumn = bridge.buffer.getCursorColumn();
final int cursorRow = bridge.buffer.getCursorRow();
final int columns = bridge.buffer.getColumns();
if (cursorColumn == columns)
cursorColumn = columns - 1;
if (cursorColumn < 0 || cursorRow < 0)
return;
int currentAttribute = bridge.buffer.getAttributes(
cursorColumn, cursorRow);
boolean onWideCharacter = (currentAttribute & VDUBuffer.FULLWIDTH) != 0;
int x = cursorColumn * bridge.charWidth;
int y = (bridge.buffer.getCursorRow()
+ bridge.buffer.screenBase - bridge.buffer.windowBase)
* bridge.charHeight;
// Save the current clip and translation
canvas.save();
canvas.translate(x, y);
canvas.clipRect(0, 0,
bridge.charWidth * (onWideCharacter ? 2 : 1),
bridge.charHeight);
canvas.drawPaint(cursorPaint);
final int deadKey = bridge.getKeyHandler().getDeadKey();
if (deadKey != 0) {
canvas.drawText(new char[] { (char)deadKey }, 0, 1, 0, 0, cursorStrokePaint);
}
// Make sure we scale our decorations to the correct size.
canvas.concat(scaleMatrix);
int metaState = bridge.getKeyHandler().getMetaState();
if ((metaState & TerminalKeyListener.META_SHIFT_ON) != 0)
canvas.drawPath(shiftCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_SHIFT_LOCK) != 0)
canvas.drawPath(shiftCursor, cursorPaint);
if ((metaState & TerminalKeyListener.META_ALT_ON) != 0)
canvas.drawPath(altCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_ALT_LOCK) != 0)
canvas.drawPath(altCursor, cursorPaint);
if ((metaState & TerminalKeyListener.META_CTRL_ON) != 0)
canvas.drawPath(ctrlCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_CTRL_LOCK) != 0)
canvas.drawPath(ctrlCursor, cursorPaint);
// Restore previous clip region
canvas.restore();
}
// draw any highlighted area
if (bridge.isSelectingForCopy()) {
SelectionArea area = bridge.getSelectionArea();
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(
area.getLeft() * bridge.charWidth,
area.getTop() * bridge.charHeight,
(area.getRight() + 1) * bridge.charWidth,
(area.getBottom() + 1) * bridge.charHeight
);
canvas.drawPaint(cursorPaint);
canvas.restore();
}
}
}
public void notifyUser(String message) {
if (!notifications)
return;
if (notification != null) {
// Don't keep telling the user the same thing.
if (lastNotification != null && lastNotification.equals(message))
return;
notification.setText(message);
notification.show();
} else {
notification = Toast.makeText(context, message, Toast.LENGTH_SHORT);
notification.show();
}
lastNotification = message;
}
/**
* Ask the {@link TerminalBridge} we're connected to to resize to a specific size.
* @param width
* @param height
*/
public void forceSize(int width, int height) {
bridge.resizeComputed(width, height, getWidth(), getHeight());
}
/**
* Sets the ability for the TerminalView to display Toast notifications to the user.
* @param value whether to enable notifications or not
*/
public void setNotifications(boolean value) {
notifications = value;
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.imeOptions |=
EditorInfo.IME_FLAG_NO_EXTRACT_UI |
EditorInfo.IME_FLAG_NO_ENTER_ACTION |
EditorInfo.IME_ACTION_NONE;
outAttrs.inputType = EditorInfo.TYPE_NULL;
return new BaseInputConnection(this, false) {
@Override
public boolean deleteSurroundingText (int leftLength, int rightLength) {
if (rightLength == 0 && leftLength == 0) {
return this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
for (int i = 0; i < leftLength; i++) {
this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
// TODO: forward delete
return true;
}
};
}
public void propagateConsoleText(char[] rawText, int length) {
if (mAccessibilityActive) {
synchronized (mAccessibilityLock) {
mAccessibilityBuffer.append(rawText, 0, length);
}
if (mAccessibilityInitialized) {
if (mEventSender != null) {
removeCallbacks(mEventSender);
} else {
mEventSender = new AccessibilityEventSender();
}
postDelayed(mEventSender, ACCESSIBILITY_EVENT_THRESHOLD);
}
}
}
private class AccessibilityEventSender implements Runnable {
public void run() {
synchronized (mAccessibilityLock) {
if (mCodeMatcher == null) {
mCodeMatcher = mControlCodes.matcher(mAccessibilityBuffer);
} else {
mCodeMatcher.reset(mAccessibilityBuffer);
}
// Strip all control codes out.
mAccessibilityBuffer = new StringBuffer(mCodeMatcher.replaceAll(" "));
// Apply Backspaces using backspace character sequence
int i = mAccessibilityBuffer.indexOf(BACKSPACE_CODE);
while (i != -1) {
mAccessibilityBuffer = mAccessibilityBuffer.replace(i == 0 ? 0 : i - 1, i
+ BACKSPACE_CODE.length(), "");
i = mAccessibilityBuffer.indexOf(BACKSPACE_CODE);
}
if (mAccessibilityBuffer.length() > 0) {
AccessibilityEvent event = AccessibilityEvent.obtain(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
event.setFromIndex(0);
event.setAddedCount(mAccessibilityBuffer.length());
event.getText().add(mAccessibilityBuffer);
sendAccessibilityEventUnchecked(event);
mAccessibilityBuffer.setLength(0);
}
}
}
}
private class AccessibilityStateTester extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
/*
* Presumably if the accessibility manager is not enabled, we don't
* need to send accessibility events.
*/
final AccessibilityManager accessibility = (AccessibilityManager) context
.getSystemService(Context.ACCESSIBILITY_SERVICE);
if (!accessibility.isEnabled()) {
return false;
}
/*
* Restrict the set of intents to only accessibility services that
* have the category FEEDBACK_SPOKEN (aka, screen readers).
*/
final Intent screenReaderIntent = new Intent(SCREENREADER_INTENT_ACTION);
screenReaderIntent.addCategory(SCREENREADER_INTENT_CATEGORY);
final ContentResolver cr = context.getContentResolver();
final List<ResolveInfo> screenReaders = context.getPackageManager().queryIntentServices(
screenReaderIntent, 0);
boolean foundScreenReader = false;
final int N = screenReaders.size();
for (int i = 0; i < N; i++) {
final ResolveInfo screenReader = screenReaders.get(i);
/*
* All screen readers are expected to implement a content
* provider that responds to:
* content://<nameofpackage>.providers.StatusProvider
*/
final Cursor cursor = cr.query(
Uri.parse("content://" + screenReader.serviceInfo.packageName
+ ".providers.StatusProvider"), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
/*
* These content providers use a special cursor that only has
* one element, an integer that is 1 if the screen reader is
* running.
*/
final int status = cursor.getInt(0);
cursor.close();
if (status == 1) {
foundScreenReader = true;
break;
}
}
}
if (foundScreenReader) {
mControlCodes = Pattern.compile(CONTROL_CODE_PATTERN);
}
return foundScreenReader;
}
@Override
protected void onPostExecute(Boolean result) {
mAccessibilityActive = result;
mAccessibilityInitialized = true;
if (result) {
mEventSender = new AccessibilityEventSender();
postDelayed(mEventSender, ACCESSIBILITY_EVENT_THRESHOLD);
} else {
mAccessibilityBuffer = null;
}
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import org.connectbot.util.HelpTopicView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* @author Kenny Root
*
*/
public class HelpTopicActivity extends Activity {
public final static String TAG = "ConnectBot.HelpActivity";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_help_topic);
String topic = getIntent().getStringExtra(Intent.EXTRA_TITLE);
this.setTitle(String.format("%s: %s - %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_help),
topic));
HelpTopicView helpTopic = (HelpTopicView) findViewById(R.id.topic_text);
helpTopic.setTopic(topic);
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PubkeyDatabase;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
public class HostEditorActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public class CursorPreferenceHack implements SharedPreferences {
protected final String table;
protected final long id;
protected Map<String, String> values = new HashMap<String, String>();
// protected Map<String, String> pubkeys = new HashMap<String, String>();
public CursorPreferenceHack(String table, long id) {
this.table = table;
this.id = id;
cacheValues();
}
protected final void cacheValues() {
// fill a cursor and cache the values locally
// this makes sure we dont have any floating cursor to dispose later
SQLiteDatabase db = hostdb.getReadableDatabase();
Cursor cursor = db.query(table, null, "_id = ?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor.moveToFirst()) {
for(int i = 0; i < cursor.getColumnCount(); i++) {
String key = cursor.getColumnName(i);
if(key.equals(HostDatabase.FIELD_HOST_HOSTKEY)) continue;
String value = cursor.getString(i);
values.put(key, value);
}
}
cursor.close();
db.close();
// db = pubkeydb.getReadableDatabase();
// cursor = db.query(PubkeyDatabase.TABLE_PUBKEYS,
// new String[] { "_id", PubkeyDatabase.FIELD_PUBKEY_NICKNAME },
// null, null, null, null, null);
//
// if (cursor.moveToFirst()) {
// do {
// String pubkeyid = String.valueOf(cursor.getLong(0));
// String value = cursor.getString(1);
// pubkeys.put(pubkeyid, value);
// } while (cursor.moveToNext());
// }
//
// cursor.close();
// db.close();
}
public boolean contains(String key) {
return values.containsKey(key);
}
public class Editor implements SharedPreferences.Editor {
private ContentValues update = new ContentValues();
public SharedPreferences.Editor clear() {
Log.d(this.getClass().toString(), "clear()");
update = new ContentValues();
return this;
}
public boolean commit() {
//Log.d(this.getClass().toString(), "commit() changes back to database");
SQLiteDatabase db = hostdb.getWritableDatabase();
db.update(table, update, "_id = ?", new String[] { String.valueOf(id) });
db.close();
// make sure we refresh the parent cached values
cacheValues();
// and update any listeners
for(OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(CursorPreferenceHack.this, null);
}
return true;
}
// Gingerbread compatibility
public void apply() {
commit();
}
public android.content.SharedPreferences.Editor putBoolean(String key, boolean value) {
return this.putString(key, Boolean.toString(value));
}
public android.content.SharedPreferences.Editor putFloat(String key, float value) {
return this.putString(key, Float.toString(value));
}
public android.content.SharedPreferences.Editor putInt(String key, int value) {
return this.putString(key, Integer.toString(value));
}
public android.content.SharedPreferences.Editor putLong(String key, long value) {
return this.putString(key, Long.toString(value));
}
public android.content.SharedPreferences.Editor putString(String key, String value) {
//Log.d(this.getClass().toString(), String.format("Editor.putString(key=%s, value=%s)", key, value));
update.put(key, value);
return this;
}
public android.content.SharedPreferences.Editor remove(String key) {
//Log.d(this.getClass().toString(), String.format("Editor.remove(key=%s)", key));
update.remove(key);
return this;
}
public android.content.SharedPreferences.Editor putStringSet(String key, Set<String> value) {
throw new UnsupportedOperationException("HostEditor Prefs do not support Set<String>");
}
}
public Editor edit() {
//Log.d(this.getClass().toString(), "edit()");
return new Editor();
}
public Map<String, ?> getAll() {
return values;
}
public boolean getBoolean(String key, boolean defValue) {
return Boolean.valueOf(this.getString(key, Boolean.toString(defValue)));
}
public float getFloat(String key, float defValue) {
return Float.valueOf(this.getString(key, Float.toString(defValue)));
}
public int getInt(String key, int defValue) {
return Integer.valueOf(this.getString(key, Integer.toString(defValue)));
}
public long getLong(String key, long defValue) {
return Long.valueOf(this.getString(key, Long.toString(defValue)));
}
public String getString(String key, String defValue) {
//Log.d(this.getClass().toString(), String.format("getString(key=%s, defValue=%s)", key, defValue));
if(!values.containsKey(key)) return defValue;
return values.get(key);
}
public Set<String> getStringSet(String key, Set<String> defValue) {
throw new ClassCastException("HostEditor Prefs do not support Set<String>");
}
protected List<OnSharedPreferenceChangeListener> listeners = new LinkedList<OnSharedPreferenceChangeListener>();
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
listeners.add(listener);
}
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
listeners.remove(listener);
}
}
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
//Log.d(this.getClass().toString(), String.format("getSharedPreferences(name=%s)", name));
return this.pref;
}
protected static final String TAG = "ConnectBot.HostEditorActivity";
protected HostDatabase hostdb = null;
private PubkeyDatabase pubkeydb = null;
private CursorPreferenceHack pref;
private ServiceConnection connection;
private HostBean host;
protected TerminalBridge hostBridge;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
// TODO: we could pass through a specific ContentProvider uri here
//this.getPreferenceManager().setSharedPreferencesName(uri);
this.hostdb = new HostDatabase(this);
this.pubkeydb = new PubkeyDatabase(this);
host = hostdb.findHostById(hostId);
connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
hostBridge = bound.getConnectedBridge(host);
}
public void onServiceDisconnected(ComponentName name) {
hostBridge = null;
}
};
this.pref = new CursorPreferenceHack(HostDatabase.TABLE_HOSTS, hostId);
this.pref.registerOnSharedPreferenceChangeListener(this);
this.addPreferencesFromResource(R.xml.host_prefs);
// add all existing pubkeys to our listpreference for user to choose from
// TODO: may be an issue here when this activity is recycled after adding a new pubkey
// TODO: should consider moving into onStart, but we dont have a good way of resetting the listpref after filling once
ListPreference pubkeyPref = (ListPreference)this.findPreference(HostDatabase.FIELD_HOST_PUBKEYID);
List<CharSequence> pubkeyNicks = new LinkedList<CharSequence>(Arrays.asList(pubkeyPref.getEntries()));
pubkeyNicks.addAll(pubkeydb.allValues(PubkeyDatabase.FIELD_PUBKEY_NICKNAME));
pubkeyPref.setEntries(pubkeyNicks.toArray(new CharSequence[pubkeyNicks.size()]));
List<CharSequence> pubkeyIds = new LinkedList<CharSequence>(Arrays.asList(pubkeyPref.getEntryValues()));
pubkeyIds.addAll(pubkeydb.allValues("_id"));
pubkeyPref.setEntryValues(pubkeyIds.toArray(new CharSequence[pubkeyIds.size()]));
// Populate the character set encoding list with all available
final ListPreference charsetPref = (ListPreference) findPreference(HostDatabase.FIELD_HOST_ENCODING);
if (CharsetHolder.isInitialized()) {
initCharsetPref(charsetPref);
} else {
String[] currentCharsetPref = new String[1];
currentCharsetPref[0] = charsetPref.getValue();
charsetPref.setEntryValues(currentCharsetPref);
charsetPref.setEntries(currentCharsetPref);
new Thread(new Runnable() {
public void run() {
initCharsetPref(charsetPref);
}
}).start();
}
this.updateSummaries();
}
@Override
public void onStart() {
super.onStart();
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
if(this.pubkeydb == null)
this.pubkeydb = new PubkeyDatabase(this);
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
if(this.pubkeydb != null) {
this.pubkeydb.close();
this.pubkeydb = null;
}
}
private void updateSummaries() {
// for all text preferences, set hint as current database value
for (String key : this.pref.values.keySet()) {
if(key.equals(HostDatabase.FIELD_HOST_POSTLOGIN)) continue;
Preference pref = this.findPreference(key);
if(pref == null) continue;
if(pref instanceof CheckBoxPreference) continue;
CharSequence value = this.pref.getString(key, "");
if (key.equals(HostDatabase.FIELD_HOST_PUBKEYID)) {
try {
int pubkeyId = Integer.parseInt((String) value);
if (pubkeyId >= 0)
pref.setSummary(pubkeydb.getNickname(pubkeyId));
else if(pubkeyId == HostDatabase.PUBKEYID_ANY)
pref.setSummary(R.string.list_pubkeyids_any);
else if(pubkeyId == HostDatabase.PUBKEYID_NEVER)
pref.setSummary(R.string.list_pubkeyids_none);
continue;
} catch (NumberFormatException nfe) {
// Fall through.
}
} else if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
int entryIndex = listPref.findIndexOfValue((String) value);
if (entryIndex >= 0)
value = listPref.getEntries()[entryIndex];
}
pref.setSummary(value);
}
}
private void initCharsetPref(final ListPreference charsetPref) {
charsetPref.setEntryValues(CharsetHolder.getCharsetIds());
charsetPref.setEntries(CharsetHolder.getCharsetNames());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// update values on changed preference
this.updateSummaries();
// Our CursorPreferenceHack always send null keys, so try to set charset anyway
if (hostBridge != null)
hostBridge.setCharset(sharedPreferences
.getString(HostDatabase.FIELD_HOST_ENCODING, HostDatabase.ENCODING_DEFAULT));
}
public static class CharsetHolder {
private static boolean initialized = false;
private static CharSequence[] charsetIds;
private static CharSequence[] charsetNames;
public static CharSequence[] getCharsetNames() {
if (charsetNames == null)
initialize();
return charsetNames;
}
public static CharSequence[] getCharsetIds() {
if (charsetIds == null)
initialize();
return charsetIds;
}
private synchronized static void initialize() {
if (initialized)
return;
List<CharSequence> charsetIdsList = new LinkedList<CharSequence>();
List<CharSequence> charsetNamesList = new LinkedList<CharSequence>();
for (Entry<String, Charset> entry : Charset.availableCharsets().entrySet()) {
Charset c = entry.getValue();
if (c.canEncode() && c.isRegistered()) {
String key = entry.getKey();
if (key.startsWith("cp")) {
// Custom CP437 charset changes
charsetIdsList.add("CP437");
charsetNamesList.add("CP437");
}
charsetIdsList.add(entry.getKey());
charsetNamesList.add(c.displayName());
}
}
charsetIds = charsetIdsList.toArray(new CharSequence[charsetIdsList.size()]);
charsetNames = charsetNamesList.toArray(new CharSequence[charsetNamesList.size()]);
initialized = true;
}
public static boolean isInitialized() {
return initialized;
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.service.TerminalManager.KeyHolder;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DynamicPortForwarder;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.LocalPortForwarder;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSAPrivateKey;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
/**
* @author Kenny Root
*
*/
public class SSH extends AbsTransport implements ConnectionMonitor, InteractiveCallback, AuthAgentCallback {
public SSH() {
super();
}
/**
* @param bridge
* @param db
*/
public SSH(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
private static final String PROTOCOL = "ssh";
private static final String TAG = "ConnectBot.SSH";
private static final int DEFAULT_PORT = 22;
private static final String AUTH_PUBLICKEY = "publickey",
AUTH_PASSWORD = "password",
AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive";
private final static int AUTH_TRIES = 20;
static final Pattern hostmask;
static {
hostmask = Pattern.compile("^(.+)@([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
}
private boolean compression = false;
private volatile boolean authenticated = false;
private volatile boolean connected = false;
private volatile boolean sessionOpen = false;
private boolean pubkeysExhausted = false;
private boolean interactiveCanContinue = true;
private Connection connection;
private Session session;
private ConnectionInfo connectionInfo;
private OutputStream stdin;
private InputStream stdout;
private InputStream stderr;
private static final int conditions = ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA
| ChannelCondition.CLOSED
| ChannelCondition.EOF;
private List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>();
private int columns;
private int rows;
private int width;
private int height;
private String useAuthAgent = HostDatabase.AUTHAGENT_NO;
private String agentLockPassphrase;
public class HostKeyVerifier implements ServerHostKeyVerifier {
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
// read in all known hosts from hostdb
KnownHosts hosts = manager.hostdb.getKnownHosts();
Boolean result;
String matchName = String.format("%s:%d", hostname, port);
String fingerprint = KnownHosts.createHexFingerprint(serverHostKeyAlgorithm, serverHostKey);
String algorithmName;
if ("ssh-rsa".equals(serverHostKeyAlgorithm))
algorithmName = "RSA";
else if ("ssh-dss".equals(serverHostKeyAlgorithm))
algorithmName = "DSA";
else
algorithmName = serverHostKeyAlgorithm;
switch(hosts.verifyHostkey(matchName, serverHostKeyAlgorithm, serverHostKey)) {
case KnownHosts.HOSTKEY_IS_OK:
bridge.outputLine(manager.res.getString(R.string.terminal_sucess, algorithmName, fingerprint));
return true;
case KnownHosts.HOSTKEY_IS_NEW:
// prompt user
bridge.outputLine(manager.res.getString(R.string.host_authenticity_warning, hostname));
bridge.outputLine(manager.res.getString(R.string.host_fingerprint, algorithmName, fingerprint));
result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
if(result == null) return false;
if(result.booleanValue()) {
// save this key in known database
manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
}
return result.booleanValue();
case KnownHosts.HOSTKEY_HAS_CHANGED:
String header = String.format("@ %s @",
manager.res.getString(R.string.host_verification_failure_warning_header));
char[] atsigns = new char[header.length()];
Arrays.fill(atsigns, '@');
String border = new String(atsigns);
bridge.outputLine(border);
bridge.outputLine(manager.res.getString(R.string.host_verification_failure_warning));
bridge.outputLine(border);
bridge.outputLine(String.format(manager.res.getString(R.string.host_fingerprint),
algorithmName, fingerprint));
// Users have no way to delete keys, so we'll prompt them for now.
result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
if(result == null) return false;
if(result.booleanValue()) {
// save this key in known database
manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
}
return result.booleanValue();
default:
return false;
}
}
}
private void authenticate() {
try {
if (connection.authenticateWithNone(host.getUsername())) {
finishConnection();
return;
}
} catch(Exception e) {
Log.d(TAG, "Host does not support 'none' authentication.");
}
bridge.outputLine(manager.res.getString(R.string.terminal_auth));
try {
long pubkeyId = host.getPubkeyId();
if (!pubkeysExhausted &&
pubkeyId != HostDatabase.PUBKEYID_NEVER &&
connection.isAuthMethodAvailable(host.getUsername(), AUTH_PUBLICKEY)) {
// if explicit pubkey defined for this host, then prompt for password as needed
// otherwise just try all in-memory keys held in terminalmanager
if (pubkeyId == HostDatabase.PUBKEYID_ANY) {
// try each of the in-memory keys
bridge.outputLine(manager.res
.getString(R.string.terminal_auth_pubkey_any));
for (Entry<String, KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
if (entry.getValue().bean.isConfirmUse()
&& !promptForPubkeyUse(entry.getKey()))
continue;
if (this.tryPublicKey(host.getUsername(), entry.getKey(),
entry.getValue().trileadKey)) {
finishConnection();
break;
}
}
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_specific));
// use a specific key for this host, as requested
PubkeyBean pubkey = manager.pubkeydb.findPubkeyById(pubkeyId);
if (pubkey == null)
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_invalid));
else
if (tryPublicKey(pubkey))
finishConnection();
}
pubkeysExhausted = true;
} else if (interactiveCanContinue &&
connection.isAuthMethodAvailable(host.getUsername(), AUTH_KEYBOARDINTERACTIVE)) {
// this auth method will talk with us using InteractiveCallback interface
// it blocks until authentication finishes
bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki));
interactiveCanContinue = false;
if(connection.authenticateWithKeyboardInteractive(host.getUsername(), this)) {
finishConnection();
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki_fail));
}
} else if (connection.isAuthMethodAvailable(host.getUsername(), AUTH_PASSWORD)) {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass));
String password = bridge.getPromptHelper().requestStringPrompt(null,
manager.res.getString(R.string.prompt_password));
if (password != null
&& connection.authenticateWithPassword(host.getUsername(), password)) {
finishConnection();
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass_fail));
}
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_fail));
}
} catch (IllegalStateException e) {
Log.e(TAG, "Connection went away while we were trying to authenticate", e);
return;
} catch(Exception e) {
Log.e(TAG, "Problem during handleAuthentication()", e);
}
}
/**
* Attempt connection with database row pointed to by cursor.
* @param cursor
* @return true for successful authentication
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws IOException
*/
private boolean tryPublicKey(PubkeyBean pubkey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
Object trileadKey = null;
if(manager.isKeyLoaded(pubkey.getNickname())) {
// load this key from memory if its already there
Log.d(TAG, String.format("Found unlocked key '%s' already in-memory", pubkey.getNickname()));
if (pubkey.isConfirmUse()) {
if (!promptForPubkeyUse(pubkey.getNickname()))
return false;
}
trileadKey = manager.getKey(pubkey.getNickname());
} else {
// otherwise load key from database and prompt for password as needed
String password = null;
if (pubkey.isEncrypted()) {
password = bridge.getPromptHelper().requestStringPrompt(null,
manager.res.getString(R.string.prompt_pubkey_password, pubkey.getNickname()));
// Something must have interrupted the prompt.
if (password == null)
return false;
}
if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
// load specific key using pem format
trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password);
} else {
// load using internal generated format
PrivateKey privKey;
try {
privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(),
pubkey.getType(), password);
} catch (Exception e) {
String message = String.format("Bad password for key '%s'. Authentication failed.", pubkey.getNickname());
Log.e(TAG, message, e);
bridge.outputLine(message);
return false;
}
PublicKey pubKey = pubkey.getPublicKey();
// convert key to trilead format
trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
}
Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname()));
// save this key in memory
manager.addKey(pubkey, trileadKey);
}
return tryPublicKey(host.getUsername(), pubkey.getNickname(), trileadKey);
}
private boolean tryPublicKey(String username, String keyNickname, Object trileadKey) throws IOException {
//bridge.outputLine(String.format("Attempting 'publickey' with key '%s' [%s]...", keyNickname, trileadKey.toString()));
boolean success = connection.authenticateWithPublicKey(username, trileadKey);
if(!success)
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_fail, keyNickname));
return success;
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
private void finishConnection() {
authenticated = true;
for (PortForwardBean portForward : portForwards) {
try {
enablePortForward(portForward);
bridge.outputLine(manager.res.getString(R.string.terminal_enable_portfoward, portForward.getDescription()));
} catch (Exception e) {
Log.e(TAG, "Error setting up port forward during connect", e);
}
}
if (!host.getWantSession()) {
bridge.outputLine(manager.res.getString(R.string.terminal_no_session));
bridge.onConnected();
return;
}
try {
session = connection.openSession();
if (!useAuthAgent.equals(HostDatabase.AUTHAGENT_NO))
session.requestAuthAgentForwarding(this);
session.requestPTY(getEmulation(), columns, rows, width, height, null);
session.startShell();
stdin = session.getStdin();
stdout = session.getStdout();
stderr = session.getStderr();
sessionOpen = true;
bridge.onConnected();
} catch (IOException e1) {
Log.e(TAG, "Problem while trying to create PTY in finishConnection()", e1);
}
}
@Override
public void connect() {
connection = new Connection(host.getHostname(), host.getPort());
connection.addConnectionMonitor(this);
try {
connection.setCompression(compression);
} catch (IOException e) {
Log.e(TAG, "Could not enable compression!", e);
}
try {
/* Uncomment when debugging SSH protocol:
DebugLogger logger = new DebugLogger() {
public void log(int level, String className, String message) {
Log.d("SSH", message);
}
};
Logger.enabled = true;
Logger.logger = logger;
*/
connectionInfo = connection.connect(new HostKeyVerifier());
connected = true;
if (connectionInfo.clientToServerCryptoAlgorithm
.equals(connectionInfo.serverToClientCryptoAlgorithm)
&& connectionInfo.clientToServerMACAlgorithm
.equals(connectionInfo.serverToClientMACAlgorithm)) {
bridge.outputLine(manager.res.getString(R.string.terminal_using_algorithm,
connectionInfo.clientToServerCryptoAlgorithm,
connectionInfo.clientToServerMACAlgorithm));
} else {
bridge.outputLine(manager.res.getString(
R.string.terminal_using_c2s_algorithm,
connectionInfo.clientToServerCryptoAlgorithm,
connectionInfo.clientToServerMACAlgorithm));
bridge.outputLine(manager.res.getString(
R.string.terminal_using_s2c_algorithm,
connectionInfo.serverToClientCryptoAlgorithm,
connectionInfo.serverToClientMACAlgorithm));
}
} catch (IOException e) {
Log.e(TAG, "Problem in SSH connection thread during authentication", e);
// Display the reason in the text.
bridge.outputLine(e.getCause().getMessage());
onDisconnect();
return;
}
try {
// enter a loop to keep trying until authentication
int tries = 0;
while (connected && !connection.isAuthenticationComplete() && tries++ < AUTH_TRIES) {
authenticate();
// sleep to make sure we dont kill system
Thread.sleep(1000);
}
} catch(Exception e) {
Log.e(TAG, "Problem in SSH connection thread during authentication", e);
}
}
@Override
public void close() {
connected = false;
if (session != null) {
session.close();
session = null;
}
if (connection != null) {
connection.close();
connection = null;
}
}
private void onDisconnect() {
close();
bridge.dispatchDisconnect(false);
}
@Override
public void flush() throws IOException {
if (stdin != null)
stdin.flush();
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
int bytesRead = 0;
if (session == null)
return 0;
int newConditions = session.waitForCondition(conditions, 0);
if ((newConditions & ChannelCondition.STDOUT_DATA) != 0) {
bytesRead = stdout.read(buffer, start, len);
}
if ((newConditions & ChannelCondition.STDERR_DATA) != 0) {
byte discard[] = new byte[256];
while (stderr.available() > 0) {
stderr.read(discard);
}
}
if ((newConditions & ChannelCondition.EOF) != 0) {
onDisconnect();
throw new IOException("Remote end closed connection");
}
return bytesRead;
}
@Override
public void write(byte[] buffer) throws IOException {
if (stdin != null)
stdin.write(buffer);
}
@Override
public void write(int c) throws IOException {
if (stdin != null)
stdin.write(c);
}
@Override
public Map<String, String> getOptions() {
Map<String, String> options = new HashMap<String, String>();
options.put("compression", Boolean.toString(compression));
return options;
}
@Override
public void setOptions(Map<String, String> options) {
if (options.containsKey("compression"))
compression = Boolean.parseBoolean(options.get("compression"));
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public boolean isSessionOpen() {
return sessionOpen;
}
@Override
public boolean isConnected() {
return connected;
}
public void connectionLost(Throwable reason) {
onDisconnect();
}
@Override
public boolean canForwardPorts() {
return true;
}
@Override
public List<PortForwardBean> getPortForwards() {
return portForwards;
}
@Override
public boolean addPortForward(PortForwardBean portForward) {
return portForwards.add(portForward);
}
@Override
public boolean removePortForward(PortForwardBean portForward) {
// Make sure we don't have a phantom forwarder.
disablePortForward(portForward);
return portForwards.remove(portForward);
}
@Override
public boolean enablePortForward(PortForwardBean portForward) {
if (!portForwards.contains(portForward)) {
Log.e(TAG, "Attempt to enable port forward not in list");
return false;
}
if (!authenticated)
return false;
if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
LocalPortForwarder lpf = null;
try {
lpf = connection.createLocalPortForwarder(
new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()),
portForward.getDestAddr(), portForward.getDestPort());
} catch (Exception e) {
Log.e(TAG, "Could not create local port forward", e);
return false;
}
if (lpf == null) {
Log.e(TAG, "returned LocalPortForwarder object is null");
return false;
}
portForward.setIdentifier(lpf);
portForward.setEnabled(true);
return true;
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
try {
connection.requestRemotePortForwarding("", portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort());
} catch (Exception e) {
Log.e(TAG, "Could not create remote port forward", e);
return false;
}
portForward.setEnabled(true);
return true;
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
DynamicPortForwarder dpf = null;
try {
dpf = connection.createDynamicPortForwarder(
new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()));
} catch (Exception e) {
Log.e(TAG, "Could not create dynamic port forward", e);
return false;
}
portForward.setIdentifier(dpf);
portForward.setEnabled(true);
return true;
} else {
// Unsupported type
Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
return false;
}
}
@Override
public boolean disablePortForward(PortForwardBean portForward) {
if (!portForwards.contains(portForward)) {
Log.e(TAG, "Attempt to disable port forward not in list");
return false;
}
if (!authenticated)
return false;
if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
LocalPortForwarder lpf = null;
lpf = (LocalPortForwarder)portForward.getIdentifier();
if (!portForward.isEnabled() || lpf == null) {
Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
return false;
}
portForward.setEnabled(false);
try {
lpf.close();
} catch (IOException e) {
Log.e(TAG, "Could not stop local port forwarder, setting enabled to false", e);
return false;
}
return true;
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
portForward.setEnabled(false);
try {
connection.cancelRemotePortForwarding(portForward.getSourcePort());
} catch (IOException e) {
Log.e(TAG, "Could not stop remote port forwarding, setting enabled to false", e);
return false;
}
return true;
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
DynamicPortForwarder dpf = null;
dpf = (DynamicPortForwarder)portForward.getIdentifier();
if (!portForward.isEnabled() || dpf == null) {
Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
return false;
}
portForward.setEnabled(false);
try {
dpf.close();
} catch (IOException e) {
Log.e(TAG, "Could not stop dynamic port forwarder, setting enabled to false", e);
return false;
}
return true;
} else {
// Unsupported type
Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
return false;
}
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
this.columns = columns;
this.rows = rows;
if (sessionOpen) {
try {
session.resizePTY(columns, rows, width, height);
} catch (IOException e) {
Log.e(TAG, "Couldn't send resize PTY packet", e);
}
}
}
@Override
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
if (port == DEFAULT_PORT) {
return String.format("%s@%s", username, hostname);
} else {
return String.format("%s@%s:%d", username, hostname, port);
}
}
public static Uri getUri(String input) {
Matcher matcher = hostmask.matcher(input);
if (!matcher.matches())
return null;
StringBuilder sb = new StringBuilder();
sb.append(PROTOCOL)
.append("://")
.append(Uri.encode(matcher.group(1)))
.append('@')
.append(matcher.group(2));
String portString = matcher.group(4);
int port = DEFAULT_PORT;
if (portString != null) {
try {
port = Integer.parseInt(portString);
if (port < 1 || port > 65535) {
port = DEFAULT_PORT;
}
} catch (NumberFormatException nfe) {
// Keep the default port
}
}
if (port != DEFAULT_PORT) {
sb.append(':')
.append(port);
}
sb.append("/#")
.append(Uri.encode(input));
Uri uri = Uri.parse(sb.toString());
return uri;
}
/**
* Handle challenges from keyboard-interactive authentication mode.
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) {
interactiveCanContinue = true;
String[] responses = new String[numPrompts];
for(int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
responses[i] = bridge.promptHelper.requestStringPrompt(instruction, prompt[i]);
}
return responses;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
host.setHostname(uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
host.setPort(port);
host.setUsername(uri.getUserInfo());
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
selection.put(HostDatabase.FIELD_HOST_USERNAME, uri.getUserInfo());
}
@Override
public void setCompression(boolean compression) {
this.compression = compression;
}
public static String getFormatHint(Context context) {
return String.format("%s@%s:%s",
context.getString(R.string.format_username),
context.getString(R.string.format_hostname),
context.getString(R.string.format_port));
}
@Override
public void setUseAuthAgent(String useAuthAgent) {
this.useAuthAgent = useAuthAgent;
}
public Map<String,byte[]> retrieveIdentities() {
Map<String,byte[]> pubKeys = new HashMap<String,byte[]>(manager.loadedKeypairs.size());
for (Entry<String,KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
Object trileadKey = entry.getValue().trileadKey;
try {
if (trileadKey instanceof RSAPrivateKey) {
RSAPublicKey pubkey = ((RSAPrivateKey) trileadKey).getPublicKey();
pubKeys.put(entry.getKey(), RSASHA1Verify.encodeSSHRSAPublicKey(pubkey));
} else if (trileadKey instanceof DSAPrivateKey) {
DSAPublicKey pubkey = ((DSAPrivateKey) trileadKey).getPublicKey();
pubKeys.put(entry.getKey(), DSASHA1Verify.encodeSSHDSAPublicKey(pubkey));
} else
continue;
} catch (IOException e) {
continue;
}
}
return pubKeys;
}
public Object getPrivateKey(byte[] publicKey) {
String nickname = manager.getKeyNickname(publicKey);
if (nickname == null)
return null;
if (useAuthAgent.equals(HostDatabase.AUTHAGENT_NO)) {
Log.e(TAG, "");
return null;
} else if (useAuthAgent.equals(HostDatabase.AUTHAGENT_CONFIRM) ||
manager.loadedKeypairs.get(nickname).bean.isConfirmUse()) {
if (!promptForPubkeyUse(nickname))
return null;
}
return manager.getKey(nickname);
}
private boolean promptForPubkeyUse(String nickname) {
Boolean result = bridge.promptHelper.requestBooleanPrompt(null,
manager.res.getString(R.string.prompt_allow_agent_to_use_key,
nickname));
return result;
}
public boolean addIdentity(Object key, String comment, boolean confirmUse, int lifetime) {
PubkeyBean pubkey = new PubkeyBean();
// pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setNickname(comment);
pubkey.setConfirmUse(confirmUse);
pubkey.setLifetime(lifetime);
manager.addKey(pubkey, key);
return true;
}
public boolean removeAllIdentities() {
manager.loadedKeypairs.clear();
return true;
}
public boolean removeIdentity(byte[] publicKey) {
return manager.removeKey(publicKey);
}
public boolean isAgentLocked() {
return agentLockPassphrase != null;
}
public boolean requestAgentUnlock(String unlockPassphrase) {
if (agentLockPassphrase == null)
return false;
if (agentLockPassphrase.equals(unlockPassphrase))
agentLockPassphrase = null;
return agentLockPassphrase == null;
}
public boolean setAgentLock(String lockPassphrase) {
if (agentLockPassphrase != null)
return false;
agentLockPassphrase = lockPassphrase;
return true;
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return true;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.transport;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import android.content.Context;
import android.net.Uri;
/**
* @author Kenny Root
*
*/
public abstract class AbsTransport {
HostBean host;
TerminalBridge bridge;
TerminalManager manager;
String emulation;
public AbsTransport() {}
public AbsTransport(HostBean host, TerminalBridge bridge, TerminalManager manager) {
this.host = host;
this.bridge = bridge;
this.manager = manager;
}
/**
* @return protocol part of the URI
*/
public static String getProtocolName() {
return "unknown";
}
/**
* Encode the current transport into a URI that can be passed via intent calls.
* @return URI to host
*/
public static Uri getUri(String input) {
return null;
}
/**
* Causes transport to connect to the target host. After connecting but before a
* session is started, must call back to {@link TerminalBridge#onConnected()}.
* After that call a session may be opened.
*/
public abstract void connect();
/**
* Reads from the transport. Transport must support reading into a the byte array
* <code>buffer</code> at the start of <code>offset</code> and a maximum of
* <code>length</code> bytes. If the remote host disconnects, throw an
* {@link IOException}.
* @param buffer byte buffer to store read bytes into
* @param offset where to start writing in the buffer
* @param length maximum number of bytes to read
* @return number of bytes read
* @throws IOException when remote host disconnects
*/
public abstract int read(byte[] buffer, int offset, int length) throws IOException;
/**
* Writes to the transport. If the host is not yet connected, simply return without
* doing anything. An {@link IOException} should be thrown if there is an error after
* connection.
* @param buffer bytes to write to transport
* @throws IOException when there is a problem writing after connection
*/
public abstract void write(byte[] buffer) throws IOException;
/**
* Writes to the transport. See {@link #write(byte[])} for behavior details.
* @param c character to write to the transport
* @throws IOException when there is a problem writing after connection
*/
public abstract void write(int c) throws IOException;
/**
* Flushes the write commands to the transport.
* @throws IOException when there is a problem writing after connection
*/
public abstract void flush() throws IOException;
/**
* Closes the connection to the terminal. Note that the resulting failure to read
* should call {@link TerminalBridge#dispatchDisconnect(boolean)}.
*/
public abstract void close();
/**
* Tells the transport what dimensions the display is currently
* @param columns columns of text
* @param rows rows of text
* @param width width in pixels
* @param height height in pixels
*/
public abstract void setDimensions(int columns, int rows, int width, int height);
public void setOptions(Map<String,String> options) {
// do nothing
}
public Map<String,String> getOptions() {
return null;
}
public void setCompression(boolean compression) {
// do nothing
}
public void setUseAuthAgent(String useAuthAgent) {
// do nothing
}
public void setEmulation(String emulation) {
this.emulation = emulation;
}
public String getEmulation() {
return emulation;
}
public void setHost(HostBean host) {
this.host = host;
}
public void setBridge(TerminalBridge bridge) {
this.bridge = bridge;
}
public void setManager(TerminalManager manager) {
this.manager = manager;
}
/**
* Whether or not this transport type can forward ports.
* @return true on ability to forward ports
*/
public boolean canForwardPorts() {
return false;
}
/**
* Adds the {@link PortForwardBean} to the list.
* @param portForward the port forward bean to add
* @return true on successful addition
*/
public boolean addPortForward(PortForwardBean portForward) {
return false;
}
/**
* Enables a port forward member. After calling this method, the port forward should
* be operational iff it could be enabled by the transport.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward setup
*/
public boolean enablePortForward(PortForwardBean portForward) {
return false;
}
/**
* Disables a port forward member. After calling this method, the port forward should
* be non-functioning iff it could be disabled by the transport.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward tear-down
*/
public boolean disablePortForward(PortForwardBean portForward) {
return false;
}
/**
* Removes the {@link PortForwardBean} from the available port forwards.
* @param portForward the port forward bean to remove
* @return true on successful removal
*/
public boolean removePortForward(PortForwardBean portForward) {
return false;
}
/**
* Gets a list of the {@link PortForwardBean} currently used by this transport.
* @return the list of port forwards
*/
public List<PortForwardBean> getPortForwards() {
return null;
}
public abstract boolean isConnected();
public abstract boolean isSessionOpen();
/**
* @return int default port for protocol
*/
public abstract int getDefaultPort();
/**
* @param username
* @param hostname
* @param port
* @return
*/
public abstract String getDefaultNickname(String username, String hostname, int port);
/**
* @param uri
* @param selectionKeys
* @param selectionValues
*/
public abstract void getSelectionArgs(Uri uri, Map<String, String> selection);
/**
* @param uri
* @return
*/
public abstract HostBean createHost(Uri uri);
/**
* @param context context containing the correct resources
* @return string that hints at the format for connection
*/
public static String getFormatHint(Context context) {
return "???";
}
/**
* @return
*/
public abstract boolean usesNetwork();
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.transport;
import java.util.HashMap;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
/**
* @author Kenny Root
*
*/
public class TransportFactory {
private static final String TAG = "ConnectBot.TransportFactory";
private static String[] transportNames = {
SSH.getProtocolName(),
Telnet.getProtocolName(),
Local.getProtocolName(),
};
/**
* @param protocol
* @return
*/
public static AbsTransport getTransport(String protocol) {
if (SSH.getProtocolName().equals(protocol)) {
return new SSH();
} else if (Telnet.getProtocolName().equals(protocol)) {
return new Telnet();
} else if (Local.getProtocolName().equals(protocol)) {
return new Local();
} else {
return null;
}
}
public static Uri getUri(String scheme, String input) {
Log.d("TransportFactory", String.format(
"Attempting to discover URI for scheme=%s on input=%s", scheme,
input));
if (SSH.getProtocolName().equals(scheme))
return SSH.getUri(input);
else if (Telnet.getProtocolName().equals(scheme))
return Telnet.getUri(input);
else if (Local.getProtocolName().equals(scheme)) {
Log.d("TransportFactory", "Got to the local parsing area");
return Local.getUri(input);
} else
return null;
}
public static String[] getTransportNames() {
return transportNames;
}
public static boolean isSameTransportType(AbsTransport a, AbsTransport b) {
if (a == null || b == null)
return false;
return a.getClass().equals(b.getClass());
}
public static boolean canForwardPorts(String protocol) {
// TODO uh, make this have less knowledge about its children
if (SSH.getProtocolName().equals(protocol)) {
return true;
} else {
return false;
}
}
/**
* @param protocol text name of protocol
* @param context
* @return expanded format hint
*/
public static String getFormatHint(String protocol, Context context) {
if (SSH.getProtocolName().equals(protocol)) {
return SSH.getFormatHint(context);
} else if (Telnet.getProtocolName().equals(protocol)) {
return Telnet.getFormatHint(context);
} else if (Local.getProtocolName().equals(protocol)) {
return Local.getFormatHint(context);
} else {
return AbsTransport.getFormatHint(context);
}
}
/**
* @param hostdb Handle to HostDatabase
* @param uri URI to target server
* @param host HostBean in which to put the results
* @return true when host was found
*/
public static HostBean findHost(HostDatabase hostdb, Uri uri) {
AbsTransport transport = getTransport(uri.getScheme());
Map<String, String> selection = new HashMap<String, String>();
transport.getSelectionArgs(uri, selection);
if (selection.size() == 0) {
Log.e(TAG, String.format("Transport %s failed to do something useful with URI=%s",
uri.getScheme(), uri.toString()));
throw new IllegalStateException("Failed to get needed selection arguments");
}
return hostdb.findHost(selection);
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import de.mud.telnet.TelnetProtocolHandler;
/**
* Telnet transport implementation.<br/>
* Original idea from the JTA telnet package (de.mud.telnet)
*
* @author Kenny Root
*
*/
public class Telnet extends AbsTransport {
private static final String TAG = "ConnectBot.Telnet";
private static final String PROTOCOL = "telnet";
private static final int DEFAULT_PORT = 23;
private TelnetProtocolHandler handler;
private Socket socket;
private InputStream is;
private OutputStream os;
private int width;
private int height;
private boolean connected = false;
static final Pattern hostmask;
static {
hostmask = Pattern.compile("^([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
}
public Telnet() {
handler = new TelnetProtocolHandler() {
/** get the current terminal type */
@Override
public String getTerminalType() {
return getEmulation();
}
/** get the current window size */
@Override
public int[] getWindowSize() {
return new int[] { width, height };
}
/** notify about local echo */
@Override
public void setLocalEcho(boolean echo) {
/* EMPTY */
}
/** write data to our back end */
@Override
public void write(byte[] b) throws IOException {
if (os != null)
os.write(b);
}
/** sent on IAC EOR (prompt terminator for remote access systems). */
@Override
public void notifyEndOfRecord() {
}
@Override
protected String getCharsetName() {
Charset charset = bridge.getCharset();
if (charset != null)
return charset.name();
else
return "";
}
};
}
/**
* @param host
* @param bridge
* @param manager
*/
public Telnet(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public void connect() {
try {
socket = new Socket(host.getHostname(), host.getPort());
connected = true;
is = socket.getInputStream();
os = socket.getOutputStream();
bridge.onConnected();
} catch (UnknownHostException e) {
Log.d(TAG, "IO Exception connecting to host", e);
} catch (IOException e) {
Log.d(TAG, "IO Exception connecting to host", e);
}
}
@Override
public void close() {
connected = false;
if (socket != null)
try {
socket.close();
socket = null;
} catch (IOException e) {
Log.d(TAG, "Error closing telnet socket.", e);
}
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public boolean isSessionOpen() {
return connected;
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
/* process all already read bytes */
int n = 0;
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
while (n <= 0) {
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
n = is.read(buffer, start, len);
if (n < 0) {
bridge.dispatchDisconnect(false);
throw new IOException("Remote end closed connection.");
}
handler.inputfeed(buffer, start, n);
n = handler.negotiate(buffer, start);
}
return n;
}
@Override
public void write(byte[] buffer) throws IOException {
try {
if (os != null)
os.write(buffer);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void write(int c) throws IOException {
try {
if (os != null)
os.write(c);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
try {
handler.setWindowSize(columns, rows);
} catch (IOException e) {
Log.e(TAG, "Couldn't resize remote terminal", e);
}
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
if (port == DEFAULT_PORT) {
return String.format("%s", hostname);
} else {
return String.format("%s:%d", hostname, port);
}
}
public static Uri getUri(String input) {
Matcher matcher = hostmask.matcher(input);
if (!matcher.matches())
return null;
StringBuilder sb = new StringBuilder();
sb.append(PROTOCOL)
.append("://")
.append(matcher.group(1));
String portString = matcher.group(3);
int port = DEFAULT_PORT;
if (portString != null) {
try {
port = Integer.parseInt(portString);
if (port < 1 || port > 65535) {
port = DEFAULT_PORT;
}
} catch (NumberFormatException nfe) {
// Keep the default port
}
}
if (port != DEFAULT_PORT) {
sb.append(':');
sb.append(port);
}
sb.append("/#")
.append(Uri.encode(input));
Uri uri = Uri.parse(sb.toString());
return uri;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
host.setHostname(uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
host.setPort(port);
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
}
public static String getFormatHint(Context context) {
return String.format("%s:%s",
context.getString(R.string.format_hostname),
context.getString(R.string.format_port));
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return true;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot.transport;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.google.ase.Exec;
/**
* @author Kenny Root
*
*/
public class Local extends AbsTransport {
private static final String TAG = "ConnectBot.Local";
private static final String PROTOCOL = "local";
private static final String DEFAULT_URI = "local:#Local";
private FileDescriptor shellFd;
private FileInputStream is;
private FileOutputStream os;
/**
*
*/
public Local() {
}
/**
* @param host
* @param bridge
* @param manager
*/
public Local(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public void close() {
try {
if (os != null) {
os.close();
os = null;
}
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
Log.e(TAG, "Couldn't close shell", e);
}
}
@Override
public void connect() {
int[] pids = new int[1];
try {
shellFd = Exec.createSubprocess("/system/bin/sh", "-", null, pids);
} catch (Exception e) {
bridge.outputLine(manager.res.getString(R.string.local_shell_unavailable));
Log.e(TAG, "Cannot start local shell", e);
return;
}
final int shellPid = pids[0];
Runnable exitWatcher = new Runnable() {
public void run() {
Exec.waitFor(shellPid);
bridge.dispatchDisconnect(false);
}
};
Thread exitWatcherThread = new Thread(exitWatcher);
exitWatcherThread.setName("LocalExitWatcher");
exitWatcherThread.setDaemon(true);
exitWatcherThread.start();
is = new FileInputStream(shellFd);
os = new FileOutputStream(shellFd);
bridge.onConnected();
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
return DEFAULT_URI;
}
@Override
public int getDefaultPort() {
return 0;
}
@Override
public boolean isConnected() {
return is != null && os != null;
}
@Override
public boolean isSessionOpen() {
return is != null && os != null;
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
if (is == null) {
bridge.dispatchDisconnect(false);
throw new IOException("session closed");
}
return is.read(buffer, start, len);
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
try {
Exec.setPtyWindowSize(shellFd, rows, columns, width, height);
} catch (Exception e) {
Log.e(TAG, "Couldn't resize pty", e);
}
}
@Override
public void write(byte[] buffer) throws IOException {
if (os != null)
os.write(buffer);
}
@Override
public void write(int c) throws IOException {
if (os != null)
os.write(c);
}
public static Uri getUri(String input) {
Uri uri = Uri.parse(DEFAULT_URI);
if (input != null && input.length() > 0) {
uri = uri.buildUpon().fragment(input).build();
}
return uri;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
}
public static String getFormatHint(Context context) {
return context.getString(R.string.hostpref_nickname_title);
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return false;
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import android.os.StrictMode;
public class StrictModeSetup {
public static void run() {
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.util.List;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences.Editor;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class HostListActivity extends ListActivity {
public final static int REQUEST_EDIT = 1;
public final static int REQUEST_EULA = 2;
protected TerminalManager bound = null;
protected HostDatabase hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private Spinner transportSpinner;
private TextView quickconnect;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
HostListActivity.this.updateList();
}
};
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EULA) {
if(resultCode == Activity.RESULT_OK) {
// yay they agreed, so store that info
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.EULA, true);
edit.commit();
} else {
// user didnt agree, so close
this.finish();
}
} else if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_hosts_list)));
// check for eula agreement
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean agreed = prefs.getBoolean(PreferenceConstants.EULA, false);
if(!agreed) {
this.startActivityForResult(new Intent(this, WizardActivity.class), REQUEST_EULA);
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = new HostDatabase(this);
ListView list = this.getListView();
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
//this.list.setSelector(R.drawable.highlight_disabled_pressed);
list.setOnItemClickListener(new OnItemClickListener() {
public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// launch off to console details
HostBean host = (HostBean) parent.getAdapter().getItem(position);
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(HostListActivity.this, R.drawable.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
HostListActivity.this.startActivity(contents);
}
}
});
this.registerForContextMenu(list);
quickconnect = (TextView) this.findViewById(R.id.front_quickconnect);
quickconnect.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
quickconnect.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_UP) return false;
if(keyCode != KeyEvent.KEYCODE_ENTER) return false;
return startConsoleActivity();
}
});
transportSpinner = (Spinner)findViewById(R.id.transport_selection);
transportSpinner.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
ArrayAdapter<String> transportSelection = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, TransportFactory.getTransportNames());
transportSelection.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
transportSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
String formatHint = TransportFactory.getFormatHint(
(String) transportSpinner.getSelectedItem(),
HostListActivity.this);
quickconnect.setHint(formatHint);
quickconnect.setError(null);
quickconnect.requestFocus();
}
public void onNothingSelected(AdapterView<?> arg0) { }
});
transportSpinner.setAdapter(transportSelection);
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if(makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add("Colors");
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// create menu to handle hosts
// create menu to handle deleting and sharing lists
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final HostBean host = (HostBean) this.getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(host.getNickname());
// edit, disconnect, delete
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = bound.getConnectedBridge(host);
connect.setEnabled((bridge != null));
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, HostEditorActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(HostListActivity.this)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if(bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
/**
* @param text
* @return
*/
private boolean startConsoleActivity() {
Uri uri = TransportFactory.getUri((String) transportSpinner
.getSelectedItem(), quickconnect.getText().toString());
if (uri == null) {
quickconnect.setError(getString(R.string.list_format_error,
TransportFactory.getFormatHint(
(String) transportSpinner.getSelectedItem(),
HostListActivity.this)));
return false;
}
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.commit();
}
if (hostdb == null)
hostdb = new HostDatabase(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.bridges) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
HostAdapter adapter = new HostAdapter(this, hosts, bound);
this.setListAdapter(adapter);
}
class HostAdapter extends ArrayAdapter<HostBean> {
private List<HostBean> hosts;
private final TerminalManager manager;
private final ColorStateList red, green, blue;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context, R.layout.item_host, hosts);
this.hosts = hosts;
this.manager = manager;
red = context.getResources().getColorStateList(R.color.red);
green = context.getResources().getColorStateList(R.color.green);
blue = context.getResources().getColorStateList(R.color.blue);
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we dont have backend service
if (this.manager == null)
return STATE_UNKNOWN;
if (manager.getConnectedBridge(host) != null)
return STATE_CONNECTED;
if (manager.disconnected.contains(host))
return STATE_DISCONNECTED;
return STATE_UNKNOWN;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_host, null, false);
holder = new ViewHolder();
holder.nickname = (TextView)convertView.findViewById(android.R.id.text1);
holder.caption = (TextView)convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView)convertView.findViewById(android.R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
HostBean host = hosts.get(position);
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
holder.nickname.setText("Error during lookup");
holder.caption.setText("see 'adb logcat' for more");
return convertView;
}
holder.nickname.setText(host.getNickname());
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
holder.icon.setImageState(new int[] { }, true);
break;
case STATE_CONNECTED:
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
break;
case STATE_DISCONNECTED:
holder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
break;
}
ColorStateList chosen = null;
if (HostDatabase.COLOR_RED.equals(host.getColor()))
chosen = this.red;
else if (HostDatabase.COLOR_GREEN.equals(host.getColor()))
chosen = this.green;
else if (HostDatabase.COLOR_BLUE.equals(host.getColor()))
chosen = this.blue;
Context context = convertView.getContext();
if (chosen != null) {
// set color normally if not selected
holder.nickname.setTextColor(chosen);
holder.caption.setTextColor(chosen);
} else {
// selected, so revert back to default black text
holder.nickname.setTextAppearance(context, android.R.attr.textAppearanceLarge);
holder.caption.setTextAppearance(context, android.R.attr.textAppearanceSmall);
}
long now = System.currentTimeMillis() / 1000;
String nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
int minutes = (int)((now - host.getLastConnect()) / 60);
if (minutes >= 60) {
int hours = (minutes / 60);
if (hours >= 24) {
int days = (hours / 24);
nice = context.getString(R.string.bind_days, days);
} else
nice = context.getString(R.string.bind_hours, hours);
} else
nice = context.getString(R.string.bind_minutes, minutes);
}
holder.caption.setText(nice);
return convertView;
}
}
}
|
Java
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.connectbot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collections;
import java.util.EventListener;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import org.openintents.intents.FileManagerIntents;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.crypto.PEMStructure;
/**
* List public keys in database by nickname and describe their properties. Allow users to import,
* generate, rename, and delete key pairs.
*
* @author Kenny Root
*/
public class PubkeyListActivity extends ListActivity implements EventListener {
public final static String TAG = "ConnectBot.PubkeyListActivity";
private static final int MAX_KEYFILE_SIZE = 8192;
private static final int REQUEST_CODE_PICK_FILE = 1;
// Constants for AndExplorer's file picking intent
private static final String ANDEXPLORER_TITLE = "explorer_title";
private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file";
protected PubkeyDatabase pubkeydb;
private List<PubkeyBean> pubkeys;
protected ClipboardManager clipboard;
protected LayoutInflater inflater = null;
protected TerminalManager bound = null;
private MenuItem onstartToggle = null;
private MenuItem confirmUse = null;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
updateList();
}
};
@Override
public void onStart() {
super.onStart();
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(pubkeydb == null)
pubkeydb = new PubkeyDatabase(this);
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
if(pubkeydb != null) {
pubkeydb.close();
pubkeydb = null;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_pubkeylist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_pubkey_list)));
// connect with hosts database and populate list
pubkeydb = new PubkeyDatabase(this);
updateList();
registerForContextMenu(getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position);
boolean loaded = bound.isKeyLoaded(pubkey.getNickname());
// handle toggling key in-memory on/off
if(loaded) {
bound.removeKey(pubkey.getNickname());
updateHandler.sendEmptyMessage(-1);
} else {
handleAddKey(pubkey);
}
}
});
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
inflater = LayoutInflater.from(this);
}
/**
* Read given file into memory as <code>byte[]</code>.
*/
protected static byte[] readRaw(File file) throws Exception {
InputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
is.close();
return os.toByteArray();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem generatekey = menu.add(R.string.pubkey_generate);
generatekey.setIcon(android.R.drawable.ic_menu_manage);
generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class));
MenuItem importkey = menu.add(R.string.pubkey_import);
importkey.setIcon(android.R.drawable.ic_menu_upload);
importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory());
String pickerTitle = getString(R.string.pubkey_list_pick);
// Try to use OpenIntent's file browser to pick a file
Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE);
intent.setData(sdcard);
intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle);
intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok));
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e) {
// If OI didn't work, try AndExplorer
intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE);
intent.putExtra(ANDEXPLORER_TITLE, pickerTitle);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e1) {
pickFileSimple();
}
}
return true;
}
});
return true;
}
protected void handleAddKey(final PubkeyBean pubkey) {
if (pubkey.isEncrypted()) {
final View view = inflater.inflate(R.layout.dia_password, null);
final EditText passwordField = (EditText)view.findViewById(android.R.id.text1);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(view)
.setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
handleAddKey(pubkey, passwordField.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
} else {
handleAddKey(pubkey, null);
}
}
protected void handleAddKey(PubkeyBean pubkey, String password) {
Object trileadKey = null;
if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
// load specific key using pem format
try {
trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password);
} catch(Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, pubkey.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG);
}
} else {
// load using internal generated format
PrivateKey privKey = null;
PublicKey pubKey = null;
try {
privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType(), password);
pubKey = pubkey.getPublicKey();
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, pubkey.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG);
return;
}
// convert key to trilead format
trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
}
if(trileadKey == null) return;
Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname()));
// save this key in memory
bound.addKey(pubkey, trileadKey, true);
updateHandler.sendEmptyMessage(-1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing pubkey
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pubkey.getNickname());
// TODO: option load/unload key from in-memory list
// prompt for password as needed for passworded keys
// cant change password or clipboard imported keys
final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
final boolean loaded = bound.isKeyLoaded(pubkey.getNickname());
MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load);
load.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if(loaded) {
bound.removeKey(pubkey.getNickname());
updateHandler.sendEmptyMessage(-1);
} else {
handleAddKey(pubkey);
//bound.addKey(nickname, trileadKey);
}
return true;
}
});
onstartToggle = menu.add(R.string.pubkey_load_on_start);
onstartToggle.setEnabled(!pubkey.isEncrypted());
onstartToggle.setCheckable(true);
onstartToggle.setChecked(pubkey.isStartup());
onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle onstart status
pubkey.setStartup(!pubkey.isStartup());
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public);
copyPublicToClipboard.setEnabled(!imported);
copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
PublicKey pk = pubkey.getPublicKey();
String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname());
clipboard.setText(openSSHPubkey);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private);
copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported);
copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
String data = null;
if (imported)
data = new String(pubkey.getPrivateKey());
else {
PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
data = PubkeyUtils.exportPEM(pk, null);
}
clipboard.setText(data);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem changePassword = menu.add(R.string.pubkey_change_password);
changePassword.setEnabled(!imported);
changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false);
((TableRow)changePasswordView.findViewById(R.id.old_password_prompt))
.setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(changePasswordView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String oldPassword = ((EditText)changePasswordView.findViewById(R.id.old_password)).getText().toString();
String password1 = ((EditText)changePasswordView.findViewById(R.id.password1)).getText().toString();
String password2 = ((EditText)changePasswordView.findViewById(R.id.password2)).getText().toString();
if (!password1.equals(password2)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_passwords_do_not_match_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
try {
if (!pubkey.changePassword(oldPassword, password1))
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_wrong_password_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
else {
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
}
} catch (Exception e) {
Log.e(TAG, "Could not change private key password", e);
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_key_corrupted_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
confirmUse = menu.add(R.string.pubkey_confirm_use);
confirmUse.setCheckable(true);
confirmUse.setChecked(pubkey.isConfirmUse());
confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle confirm use
pubkey.setConfirmUse(!pubkey.isConfirmUse());
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem delete = menu.add(R.string.pubkey_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(getString(R.string.delete_message, pubkey.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dont forget to remove from in-memory
if(loaded)
bound.removeKey(pubkey.getNickname());
// delete from backend database and update gui
pubkeydb.deletePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
updateList();
}
};
protected void updateList() {
if (pubkeydb == null) return;
pubkeys = pubkeydb.allPubkeys();
PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys);
this.setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
readKeyFromFile(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null)
readKeyFromFile(new File(URI.create(filename)));
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from picked file", e);
}
}
break;
}
}
/**
* @param name
*/
private void readKeyFromFile(File file) {
PubkeyBean pubkey = new PubkeyBean();
// find the exact file selected
pubkey.setNickname(file.getName());
if (file.length() > MAX_KEYFILE_SIZE) {
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
return;
}
// parse the actual key once to check if its encrypted
// then save original file contents into our database
try {
byte[] raw = readRaw(file);
String data = new String(raw);
if (data.startsWith(PubkeyUtils.PKCS8_START)) {
int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
int end = data.indexOf(PubkeyUtils.PKCS8_END);
if (end > start) {
char[] encoded = data.substring(start, end - 1).toCharArray();
Log.d(TAG, "encoded: " + new String(encoded));
byte[] decoded = Base64.decode(encoded);
KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);
pubkey.setType(kp.getPrivate().getAlgorithm());
pubkey.setPrivateKey(kp.getPrivate().getEncoded());
pubkey.setPublicKey(kp.getPublic().getEncoded());
} else {
Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
}
} else {
PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setPrivateKey(raw);
}
// write new value into database
if (pubkeydb == null)
pubkeydb = new PubkeyDatabase(this);
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
} catch(Exception e) {
Log.e(TAG, "Problem parsing imported private key", e);
Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
}
}
/**
*
*/
private void pickFileSimple() {
// build list of all files in sdcard root
final File sdcard = Environment.getExternalStorageDirectory();
Log.d(TAG, sdcard.toString());
// Don't show a dialog if the SD card is completely absent.
final String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
&& !Environment.MEDIA_MOUNTED.equals(state)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_sdcard_absent)
.setNegativeButton(android.R.string.cancel, null).create().show();
return;
}
List<String> names = new LinkedList<String>();
{
File[] files = sdcard.listFiles();
if (files != null) {
for(File file : sdcard.listFiles()) {
if(file.isDirectory()) continue;
names.add(file.getName());
}
}
}
Collections.sort(names);
final String[] namesList = names.toArray(new String[] {});
Log.d(TAG, names.toString());
// prompt user to select any file from the sdcard root
new AlertDialog.Builder(PubkeyListActivity.this)
.setTitle(R.string.pubkey_list_pick)
.setItems(namesList, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String name = namesList[arg1];
readKeyFromFile(new File(sdcard, name));
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
}
class PubkeyAdapter extends ArrayAdapter<PubkeyBean> {
private List<PubkeyBean> pubkeys;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) {
super(context, R.layout.item_pubkey, pubkeys);
this.pubkeys = pubkeys;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_pubkey, null, false);
holder = new ViewHolder();
holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PubkeyBean pubkey = pubkeys.get(position);
holder.nickname.setText(pubkey.getNickname());
boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
if (imported) {
try {
PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray());
String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA";
holder.caption.setText(String.format("%s unknown-bit", type));
} catch (IOException e) {
Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e);
}
} else {
try {
holder.caption.setText(pubkey.getDescription());
} catch (Exception e) {
Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e);
holder.caption.setText(R.string.pubkey_unknown_format);
}
}
if (bound == null) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
if (bound.isKeyLoaded(pubkey.getNickname()))
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
else
holder.icon.setImageState(new int[] { }, true);
}
return convertView;
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.