From 02e9e71389aab34c2a9df83f253d1575c3807ed0 Mon Sep 17 00:00:00 2001 From: limboemu Date: Tue, 17 Aug 2021 18:16:09 +0300 Subject: [PATCH 001/154] refactored sdl mode --- .../android/limbo/jni/VMExecutor.java | 4 +- .../android/limbo/main/LimboSDLActivity.java | 2738 ++++++++--------- 2 files changed, 1361 insertions(+), 1381 deletions(-) diff --git a/limbo-android-lib/src/main/java/com/max2idea/android/limbo/jni/VMExecutor.java b/limbo-android-lib/src/main/java/com/max2idea/android/limbo/jni/VMExecutor.java index 22889c267..c64bac959 100644 --- a/limbo-android-lib/src/main/java/com/max2idea/android/limbo/jni/VMExecutor.java +++ b/limbo-android-lib/src/main/java/com/max2idea/android/limbo/jni/VMExecutor.java @@ -359,7 +359,7 @@ else if (machine.shared_folder_mode == 1) public static void onVMResolutionChanged(int width, int height) { if (LimboSDLActivity.mIsSurfaceReady) - LimboSDLActivity.onVMResolutionChanged(width, height); + LimboSDLActivity.getSingleton().onVMResolutionChanged(width, height); } public void print(String[] params) { @@ -1086,7 +1086,7 @@ public int onLimboMouse(int button, int action, int relative, float x, float y) //XXX: Check boundaries, perhaps not necessary since SDL is also doing the same thing if (relative == 1 - || (x >= 0 && x <= LimboSDLActivity.vm_width && y >= 0 && y <= LimboSDLActivity.vm_height) + || (x >= 0 && x <= LimboSDLActivity.getSingleton().vm_width && y >= 0 && y <= LimboSDLActivity.getSingleton().vm_height) || (action == MotionEvent.ACTION_SCROLL)) { // Log.d(TAG, "onLimboMouse: B: " + button + ", A: " + action + ", R: " + relative + ", X: " + x + ", Y: " + y); return onmouse(button, action, relative, x, y); diff --git a/limbo-android-lib/src/main/java/com/max2idea/android/limbo/main/LimboSDLActivity.java b/limbo-android-lib/src/main/java/com/max2idea/android/limbo/main/LimboSDLActivity.java index dd506a7f1..b130b8892 100644 --- a/limbo-android-lib/src/main/java/com/max2idea/android/limbo/main/LimboSDLActivity.java +++ b/limbo-android-lib/src/main/java/com/max2idea/android/limbo/main/LimboSDLActivity.java @@ -1,10 +1,8 @@ package com.max2idea.android.limbo.main; -import androidx.appcompat.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; -import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; @@ -16,9 +14,8 @@ import android.os.Bundle; import android.os.Handler; import android.os.Looper; +import android.os.SystemClock; import android.os.Vibrator; -import androidx.core.view.MenuItemCompat; - import android.util.Log; import android.view.Display; import android.view.GestureDetector; @@ -41,6 +38,9 @@ import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; +import androidx.appcompat.app.ActionBar; +import androidx.core.view.MenuItemCompat; + import com.limbo.emu.lib.R; import com.max2idea.android.limbo.utils.DrivesDialogBox; import com.max2idea.android.limbo.utils.FileUtils; @@ -49,7 +49,6 @@ import com.max2idea.android.limbo.utils.UIUtils; import org.json.JSONObject; - import org.libsdl.app.SDLActivity; import org.libsdl.app.SDLControllerManager; @@ -66,404 +65,379 @@ * SDL Activity */ public class LimboSDLActivity extends SDLActivity { - public static final String TAG = "LimboSDLActivity"; - - public static LimboSDLActivity activity ; + public static final String TAG = "LimboSDLActivity"; public static final int KEYBOARD = 10000; - public static final int QUIT = 10001; - public static final int HELP = 10002; + public static final int QUIT = 10001; - private boolean monitorMode = false; - private boolean mouseOn = false; - private Object lockTime = new Object(); - private boolean timeQuit = false; - private boolean once = true; - private boolean zoomable = false; - private String status = null; + private static int singleClickDelay = 100; + private static int keyDelay = 75; + private static int mouseButtonDelay = 100; - public static int vm_width; - public static int vm_height; + private boolean monitorMode = false; + private final Object lockTime = new Object(); + private boolean timeQuit = false; + GestureDetector gestureDetector; - private Thread timeListenerThread; + public int vm_width; + public int vm_height; - private ProgressDialog progDialog; - protected static ViewGroup mMainLayout; + protected ViewGroup mMainLayout; - public String cd_iso_path = null; + public String cd_iso_path = null; - // HDD - public String hda_img_path = null; - public String hdb_img_path = null; - public String hdc_img_path = null; - public String hdd_img_path = null; + // HDD + public String hda_img_path = null; + public String hdb_img_path = null; + public String hdc_img_path = null; + public String hdd_img_path = null; - public String fda_img_path = null; - public String fdb_img_path = null; - public String cpu = null; + public String fda_img_path = null; + public String fdb_img_path = null; + public String cpu = null; - // Default Settings - public int memory = 128; - public String bootdevice = null; + // Default Settings + public int memory = 128; + public String bootdevice = null; - // net - public String net_cfg = "None"; - public int nic_num = 1; - public String vga_type = "std"; - public String hd_cache = "default"; - public String nic_driver = null; + // net + public String net_cfg = "None"; + public String vga_type = "std"; + public String hd_cache = "default"; + public String nic_driver = null; public String soundcard = null; - public String lib = "liblimbo.so"; - public String lib_path = null; - public String snapshot_name = "limbo"; - public int disableacpi = 0; - public int disablehpet = 0; - public int disabletsc = 0; - public int enableqmp = 0; - public int enablevnc = 0; - public String vnc_passwd = null; - public int vnc_allow_external = 0; - public String qemu_dev = null; - public String qemu_dev_value = null; - - public String dns_addr = null; - public int restart = 0; - - // This is what SDL runs in. It invokes SDL_main(), eventually - private static Thread mSDLThread; - - // EGL private objects - private static EGLContext mEGLContext; - private static EGLSurface mEGLSurface; - private static EGLDisplay mEGLDisplay; - private static EGLConfig mEGLConfig; - private static int mGLMajor, mGLMinor; - - - private static Activity activity1; - - // public static void showTextInput(int x, int y, int w, int h) { - // // Transfer the task to the main thread as a Runnable - // // mSingleton.commandHandler.post(new ShowTextInputHandler(x, y, w, h)); - // } - - public static void singleClick(final MotionEvent event, final int pointer_id) { - - Thread t = new Thread(new Runnable() { - public void run() { - // Log.d("SDL", "Mouse Single Click"); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - // Log.v("singletap", "Could not sleep"); - } - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_DOWN, 1,0, 0); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - // Log.v("singletap", "Could not sleep"); - } - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1, 0, 0); - } - }); - t.start(); - } - - - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); + public String lib = "liblimbo.so"; + public String snapshot_name = "limbo"; + public int disableacpi = 0; + public int disablehpet = 0; + public int disabletsc = 0; + public int enableqmp = 0; + public int enablevnc = 0; + + // This is what SDL runs in. It invokes SDL_main(), eventually + private static Thread mSDLThread; + + // EGL private objects + private static EGLContext mEGLContext; + private static EGLSurface mEGLSurface; + private static EGLDisplay mEGLDisplay; + private static EGLConfig mEGLConfig; + private static int mGLMajor, mGLMinor; + + // public static void showTextInput(int x, int y, int w, int h) { + // // Transfer the task to the main thread as a Runnable + // // mSingleton.commandHandler.post(new ShowTextInputHandler(x, y, w, h)); + // } + + final Object singleClickLock = new Object(); + + public void singleClick(final MotionEvent event, final int pointer_id) { + Thread t = new Thread(new Runnable() { + public void run() { + // Log.d("SDL", "Mouse Single Click"); + synchronized (singleClickLock) { + delay(singleClickDelay); + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_DOWN, 1, 0, 0); + delay(singleClickDelay); + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1, 0, 0); + } + } + }); + t.start(); + } + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); if (requestCode == Config.OPEN_IMAGE_FILE_REQUEST_CODE || requestCode == Config.OPEN_IMAGE_FILE_ASF_REQUEST_CODE) { String file = null; - if(requestCode == Config.OPEN_IMAGE_FILE_ASF_REQUEST_CODE) { + if (requestCode == Config.OPEN_IMAGE_FILE_ASF_REQUEST_CODE) { file = FileUtils.getFileUriFromIntent(this, data, true); } else { DrivesDialogBox.filetype = FileUtils.getFileTypeFromIntent(this, data); - file = FileUtils.getFilePathFromIntent(activity, data); + file = FileUtils.getFilePathFromIntent(this, data); } - if(drives !=null && file!=null) + if (drives != null && file != null) drives.setDriveAttr(DrivesDialogBox.filetype, file); - }else if (requestCode == Config.OPEN_LOG_FILE_DIR_REQUEST_CODE|| requestCode == Config.OPEN_LOG_FILE_DIR_ASF_REQUEST_CODE) { + } else if (requestCode == Config.OPEN_LOG_FILE_DIR_REQUEST_CODE || requestCode == Config.OPEN_LOG_FILE_DIR_ASF_REQUEST_CODE) { String file = null; - if(requestCode == Config.OPEN_LOG_FILE_DIR_ASF_REQUEST_CODE) { + if (requestCode == Config.OPEN_LOG_FILE_DIR_ASF_REQUEST_CODE) { file = FileUtils.getFileUriFromIntent(this, data, true); } else { file = FileUtils.getDirPathFromIntent(this, data); } - if(file!=null) { - FileUtils.saveLogToFile(activity, file); + if (file != null) { + FileUtils.saveLogToFile(this, file); + } + } + + } + + public void setParams(Machine machine) { + + if (machine == null) { + return; + } + memory = machine.memory; + vga_type = machine.vga_type; + hd_cache = machine.hd_cache; + snapshot_name = machine.snapshot_name; + disableacpi = machine.disableacpi; + disablehpet = machine.disablehpet; + disabletsc = machine.disabletsc; + enableqmp = machine.enableqmp; + enablevnc = machine.enablevnc; + + if (machine.cpu.endsWith("(64Bit)")) { + cpu = machine.cpu.split(" ")[0]; + } else { + cpu = machine.cpu; + } + + if (machine.cd_iso_path == null || machine.cd_iso_path.equals("None")) { + cd_iso_path = null; + } else { + cd_iso_path = machine.cd_iso_path; + } + if (machine.hda_img_path == null || machine.hda_img_path.equals("None")) { + hda_img_path = null; + } else { + hda_img_path = machine.hda_img_path; + } + + if (machine.hdb_img_path == null || machine.hdb_img_path.equals("None")) { + hdb_img_path = null; + } else { + hdb_img_path = machine.hdb_img_path; + } + + if (machine.hdc_img_path == null || machine.hdc_img_path.equals("None")) { + hdc_img_path = null; + } else { + hdc_img_path = machine.hdc_img_path; + } + + if (machine.hdd_img_path == null || machine.hdd_img_path.equals("None")) { + hdd_img_path = null; + } else { + hdd_img_path = machine.hdd_img_path; + } + + if (machine.fda_img_path == null || machine.fda_img_path.equals("None")) { + fda_img_path = null; + } else { + fda_img_path = machine.fda_img_path; + } + + if (machine.fdb_img_path == null || machine.fdb_img_path.equals("None")) { + fdb_img_path = null; + } else { + fdb_img_path = machine.fdb_img_path; + } + if (machine.bootdevice == null) { + bootdevice = null; + } else if (machine.bootdevice.equals("Default")) { + bootdevice = null; + } else if (machine.bootdevice.equals("CD Rom")) { + bootdevice = "d"; + } else if (machine.bootdevice.equals("Floppy")) { + bootdevice = "a"; + } else if (machine.bootdevice.equals("Hard Disk")) { + bootdevice = "c"; + } + + if (machine.net_cfg == null || machine.net_cfg.equals("None")) { + net_cfg = "none"; + nic_driver = null; + } else if (machine.net_cfg.equals("User")) { + net_cfg = "user"; + nic_driver = machine.nic_card; + } + + soundcard = machine.soundcard; + + } + + public void delay(int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void sendCtrlAltKey(int code) { + delay(keyDelay); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_LEFT, true); + delay(keyDelay); + sendNativeKey(null, KeyEvent.KEYCODE_ALT_LEFT, true); + delay(keyDelay); + if (code >= 0) { + sendNativeKey(null, code, true); + delay(keyDelay); + sendNativeKey(null, code, false); + delay(keyDelay); + } + sendNativeKey(null, KeyEvent.KEYCODE_ALT_LEFT, false); + delay(keyDelay); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_LEFT, false); + } + + public void stopTimeListener() { + Log.v("SaveVM", "Stopping Listener"); + synchronized (lockTime) { + timeQuit = true; + lockTime.notifyAll(); + } + } + + public void onDestroy() { + + // Now wait for the SDL thread to quit + Log.v("LimboSDL", "Waiting for SDL thread to quit"); + if (mSDLThread != null) { + try { + mSDLThread.join(); + } catch (Exception e) { + Log.v("SDL", "Problem stopping thread: " + e); + } + mSDLThread = null; + + Log.v("SDL", "Finished waiting for SDL thread"); + } + this.stopTimeListener(); + + LimboActivity.vmexecutor.doStopVM(0); + super.onDestroy(); + } + + + public void checkStatus() { + while (!timeQuit) { + LimboActivity.VMStatus status = Machine.checkSaveVMStatus(this); + Log.v(TAG, "Status: " + status); + if (status == LimboActivity.VMStatus.Unknown + || status == LimboActivity.VMStatus.Completed + || status == LimboActivity.VMStatus.Failed + ) { + Log.v("Inside", "Saving state is done: " + status); + stopTimeListener(); + return; + } + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + Log.w("SaveVM", "Interrupted"); } } + Log.v("SaveVM", "Save state complete"); + } + + + public void startTimeListener() { + this.stopTimeListener(); + timeQuit = false; + try { + Log.v("Listener", "Time Listener Started..."); + checkStatus(); + synchronized (lockTime) { + while (timeQuit == false) { + lockTime.wait(); + } + lockTime.notifyAll(); + } + } catch (Exception ex) { + ex.printStackTrace(); + Log.v("SaveVM", "Time listener thread error: " + ex.getMessage()); + } + Log.v("Listener", "Time listener thread exited..."); + + } + + public DrivesDialogBox drives = null; + public static boolean toggleKeyboardFlag = true; - } - - public void setParams(Machine machine) { - - if (machine == null) { - return; - } - memory = machine.memory; - vga_type = machine.vga_type; - hd_cache = machine.hd_cache; - snapshot_name = machine.snapshot_name; - disableacpi = machine.disableacpi; - disablehpet = machine.disablehpet; - disabletsc = machine.disabletsc; - enableqmp = machine.enableqmp; - enablevnc = machine.enablevnc; - - if (machine.cpu.endsWith("(64Bit)")) { - cpu = machine.cpu.split(" ")[0]; - } else { - cpu = machine.cpu; - } - - if (machine.cd_iso_path == null || machine.cd_iso_path.equals("None")) { - cd_iso_path = null; - } else { - cd_iso_path = machine.cd_iso_path; - } - if (machine.hda_img_path == null || machine.hda_img_path.equals("None")) { - hda_img_path = null; - } else { - hda_img_path = machine.hda_img_path; - } - - if (machine.hdb_img_path == null || machine.hdb_img_path.equals("None")) { - hdb_img_path = null; - } else { - hdb_img_path = machine.hdb_img_path; - } - - if (machine.hdc_img_path == null || machine.hdc_img_path.equals("None")) { - hdc_img_path = null; - } else { - hdc_img_path = machine.hdc_img_path; - } - - if (machine.hdd_img_path == null || machine.hdd_img_path.equals("None")) { - hdd_img_path = null; - } else { - hdd_img_path = machine.hdd_img_path; - } - - if (machine.fda_img_path == null || machine.fda_img_path.equals("None")) { - fda_img_path = null; - } else { - fda_img_path = machine.fda_img_path; - } - - if (machine.fdb_img_path == null || machine.fdb_img_path.equals("None")) { - fdb_img_path = null; - } else { - fdb_img_path = machine.fdb_img_path; - } - if (machine.bootdevice == null) { - bootdevice = null; - } else if (machine.bootdevice.equals("Default")) { - bootdevice = null; - } else if (machine.bootdevice.equals("CD Rom")) { - bootdevice = "d"; - } else if (machine.bootdevice.equals("Floppy")) { - bootdevice = "a"; - } else if (machine.bootdevice.equals("Hard Disk")) { - bootdevice = "c"; - } - - if (machine.net_cfg == null || machine.net_cfg.equals("None")) { - net_cfg = "none"; - nic_driver = null; - } else if (machine.net_cfg.equals("User")) { - net_cfg = "user"; - nic_driver = machine.nic_card; - } - - soundcard = machine.soundcard; - - } - - public static void delayKey(int ms) { - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - public static void sendCtrlAltKey(int code) { - delayKey(100); - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_CTRL_LEFT); - delayKey(100); - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_ALT_LEFT); - delayKey(100); - if(code>=0) { - SDLActivity.onNativeKeyDown(code); - delayKey(100); - SDLActivity.onNativeKeyUp(code); - delayKey(100); - } - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_ALT_LEFT); - delayKey(100); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_CTRL_LEFT); - } - - public void stopTimeListener() { - Log.v("SaveVM", "Stopping Listener"); - synchronized (this.lockTime) { - this.timeQuit = true; - this.lockTime.notifyAll(); - } - } - - public void onDestroy() { - - // Now wait for the SDL thread to quit - Log.v("LimboSDL", "Waiting for SDL thread to quit"); - if (mSDLThread != null) { - try { - mSDLThread.join(); - } catch (Exception e) { - Log.v("SDL", "Problem stopping thread: " + e); - } - mSDLThread = null; - - Log.v("SDL", "Finished waiting for SDL thread"); - } - this.stopTimeListener(); - - LimboActivity.vmexecutor.doStopVM(0); - super.onDestroy(); - } - - - public void checkStatus() { - while (timeQuit != true) { - LimboActivity.VMStatus status = Machine.checkSaveVMStatus(activity); - Log.v(TAG, "Status: " + status); - if (status == LimboActivity.VMStatus.Unknown - || status == LimboActivity.VMStatus.Completed - || status == LimboActivity.VMStatus.Failed - ) { - Log.v("Inside", "Saving state is done: " + status); - stopTimeListener(); - return; - } - try { - Thread.sleep(1000); - } catch (InterruptedException ex) { - Log.w("SaveVM", "Interrupted"); - } - } - Log.v("SaveVM", "Save state complete"); - - } - - - public void startTimeListener() { - this.stopTimeListener(); - timeQuit = false; - try { - Log.v("Listener", "Time Listener Started..."); - checkStatus(); - synchronized (lockTime) { - while (timeQuit == false) { - lockTime.wait(); - } - lockTime.notifyAll(); - } - } catch (Exception ex) { - ex.printStackTrace(); - Log.v("SaveVM", "Time listener thread error: " + ex.getMessage()); - } - Log.v("Listener", "Time listener thread exited..."); - - } - - public DrivesDialogBox drives = null; - public static boolean toggleKeyboardFlag = true; - - @Override - public boolean onOptionsItemSelected(final MenuItem item) { - // Log.v("Limbo", "Inside Options Check"); - super.onOptionsItemSelected(item); - if (item.getItemId() == R.id.itemDrives) { - // Show up removable devices dialog - if (LimboActivity.currMachine.hasRemovableDevices()) { - drives = new DrivesDialogBox(activity, R.style.Transparent, this, LimboActivity.currMachine); - drives.show(); - } else { - UIUtils.toastShort(activity, "No removable devices attached"); - } - } else if (item.getItemId() == R.id.itemReset) { - Machine.resetVM(activity); - } else if (item.getItemId() == R.id.itemShutdown) { + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + // Log.v("Limbo", "Inside Options Check"); + super.onOptionsItemSelected(item); + if (item.getItemId() == R.id.itemDrives) { + // Show up removable devices dialog + if (LimboActivity.currMachine.hasRemovableDevices()) { + drives = new DrivesDialogBox(this, R.style.Transparent, this, LimboActivity.currMachine); + drives.show(); + } else { + UIUtils.toastShort(this, "No removable devices attached"); + } + } else if (item.getItemId() == R.id.itemReset) { + Machine.resetVM(this); + } else if (item.getItemId() == R.id.itemShutdown) { UIUtils.hideKeyboard(this, mSurface); - Machine.stopVM(activity); - } else if (item.getItemId() == R.id.itemMouse) { + Machine.stopVM(this); + } else if (item.getItemId() == R.id.itemMouse) { onMouseMode(); - } else if (item.getItemId() == this.KEYBOARD || item.getItemId() == R.id.itemKeyboard) { - //XXX: need to post after delay to work correctly + } else if (item.getItemId() == this.KEYBOARD || item.getItemId() == R.id.itemKeyboard) { + //XXX: need to delay to work properly new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - toggleKeyboardFlag = UIUtils.onKeyboard(activity, toggleKeyboardFlag, mSurface); + toggleKeyboardFlag = UIUtils.onKeyboard(LimboSDLActivity.this, toggleKeyboardFlag, mSurface); } }, 200); - - } - else if (item.getItemId() == R.id.itemMonitor) { - if (this.monitorMode) { - this.onVMConsole(); - } else { - this.onMonitor(); - } - } else if (item.getItemId() == R.id.itemVolume) { - this.onSelectMenuVol(); - } else if (item.getItemId() == R.id.itemSaveState) { - this.promptPause(activity); - } else if (item.getItemId() == R.id.itemSaveSnapshot) { - //TODO: - //this.promptStateName(activity); - } else if (item.getItemId() == R.id.itemFitToScreen) { + } else if (item.getItemId() == R.id.itemMonitor) { + if (this.monitorMode) { + this.onVMConsole(); + } else { + this.onMonitor(); + } + } else if (item.getItemId() == R.id.itemVolume) { + this.onSelectMenuVol(); + } else if (item.getItemId() == R.id.itemSaveState) { + this.promptPause(this); + } else if (item.getItemId() == R.id.itemSaveSnapshot) { + //TODO: + //this.promptStateName(activity); + } else if (item.getItemId() == R.id.itemFitToScreen) { onFitToScreen(); - } else if (item.getItemId() == R.id.itemStretchToScreen) { - onStretchToScreen(); - } else if (item.getItemId() == R.id.itemZoomIn) { - this.setZoomIn(); - } else if (item.getItemId() == R.id.itemZoomOut) { - this.setZoomOut(); - } else if (item.getItemId() == R.id.itemCtrlAltDel) { - this.onCtrlAltDel(); - } else if (item.getItemId() == R.id.itemCtrlC) { - this.onCtrlC(); - } else if (item.getItemId() == R.id.itemOneToOne) { - this.onNormalScreen(); - } else if (item.getItemId() == R.id.itemZoomable) { - this.setZoomable(); - } else if (item.getItemId() == this.QUIT) { - } else if (item.getItemId() == R.id.itemHelp) { - UIUtils.onHelp(this); - } else if (item.getItemId() == R.id.itemHideToolbar) { + } else if (item.getItemId() == R.id.itemStretchToScreen) { + onStretchToScreen(); + } else if (item.getItemId() == R.id.itemZoomIn) { + this.setZoomIn(); + } else if (item.getItemId() == R.id.itemZoomOut) { + this.setZoomOut(); + } else if (item.getItemId() == R.id.itemCtrlAltDel) { + this.onCtrlAltDel(); + } else if (item.getItemId() == R.id.itemCtrlC) { + this.onCtrlC(); + } else if (item.getItemId() == R.id.itemOneToOne) { + this.onNormalScreen(); + } else if (item.getItemId() == R.id.itemZoomable) { + this.setZoomable(); + } else if (item.getItemId() == this.QUIT) { + } else if (item.getItemId() == R.id.itemHelp) { + UIUtils.onHelp(this); + } else if (item.getItemId() == R.id.itemHideToolbar) { this.onHideToolbar(); } else if (item.getItemId() == R.id.itemDisplay) { this.onSelectMenuSDLDisplay(); - } else if (item.getItemId() == R.id.itemViewLog) { + } else if (item.getItemId() == R.id.itemViewLog) { this.onViewLog(); } - // this.canvas.requestFocus(); + // this.canvas.requestFocus(); this.invalidateOptionsMenu(); - return true; - } + return true; + } public void onViewLog() { FileUtils.viewLimboLog(this); } - public void onHideToolbar(){ + public void onHideToolbar() { ActionBar bar = this.getSupportActionBar(); if (bar != null) { bar.hide(); @@ -473,7 +447,7 @@ public void onHideToolbar(){ private void onMouseMode() { - String [] items = {"Trackpad Mouse (Phone)", + String[] items = {"Trackpad Mouse (Phone)", "Bluetooth/USB Mouse (Desktop mode)", //Physical mouse for Chromebook, Android x86 PC, or Bluetooth Mouse }; final AlertDialog.Builder mBuilder = new AlertDialog.Builder(this); @@ -481,12 +455,12 @@ private void onMouseMode() { mBuilder.setSingleChoiceItems(items, Config.mouseMode.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { - switch(i){ + switch (i) { case 0: setUIModeMobile(true); break; case 1: - promptSetUIModeDesktop(false); + promptSetUIModeDesktop(false); break; default: break; @@ -499,47 +473,47 @@ public void onClick(DialogInterface dialog, int i) { } - public boolean checkVMResolutionFits() { - int width = mLayout.getWidth(); - int height = mLayout.getHeight(); - ActionBar bar = activity.getSupportActionBar(); + public boolean checkVMResolutionFits() { + int width = mLayout.getWidth(); + int height = mLayout.getHeight(); + ActionBar bar = this.getSupportActionBar(); - if (!LimboSettingsManager.getAlwaysShowMenuToolbar(LimboSDLActivity.this) - && bar != null && bar.isShowing()) { - height += bar.getHeight(); - } + if (!LimboSettingsManager.getAlwaysShowMenuToolbar(LimboSDLActivity.this) + && bar != null && bar.isShowing()) { + height += bar.getHeight(); + } - if(vm_width < width && vm_height < height) - return true; + if (vm_width < width && vm_height < height) + return true; - return false; - } + return false; + } public void calibration() { - //XXX: No need to calibrate for SDL trackpad. + //XXX: No need to calibrate for SDL trackpad. } - private void setUIModeMobile(boolean fitToScreen){ + private void setUIModeMobile(boolean fitToScreen) { - try { - UIUtils.setOrientation(this); - MotionEvent a = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0, 0, 0); - - //TODO: needed? - //LimboSDLActivity.singleClick(a, 0); - Config.mouseMode = Config.MouseMode.Trackpad; - LimboSettingsManager.setDesktopMode(this, false); - LimboActivity.vmexecutor.setRelativeMouseMode(1); - if(Config.showToast) + try { + UIUtils.setOrientation(this); + MotionEvent a = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0, 0, 0); + + //TODO: needed? + //LimboSDLActivity.singleClick(a, 0); + Config.mouseMode = Config.MouseMode.Trackpad; + LimboSettingsManager.setDesktopMode(this, false); + LimboActivity.vmexecutor.setRelativeMouseMode(1); + if (Config.showToast) UIUtils.toastShort(this.getApplicationContext(), "Trackpad Enabled"); - if(fitToScreen) - onFitToScreen(); - else - onNormalScreen(); - calibration(); - invalidateOptionsMenu(); - }catch (Exception ex){ - if(Config.debug) + if (fitToScreen) + onFitToScreen(); + else + onNormalScreen(); + calibration(); + invalidateOptionsMenu(); + } catch (Exception ex) { + if (Config.debug) ex.printStackTrace(); } @@ -547,30 +521,29 @@ private void setUIModeMobile(boolean fitToScreen){ private void promptSetUIModeDesktop(final boolean mouseMethodAlt) { - final AlertDialog alertDialog; - alertDialog = new AlertDialog.Builder(activity).create(); + alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Desktop Mode"); LinearLayout mLayout = new LinearLayout(this); - mLayout.setPadding(20,20,20,20); + mLayout.setPadding(20, 20, 20, 20); mLayout.setOrientation(LinearLayout.VERTICAL); - TextView textView = new TextView(activity); + TextView textView = new TextView(this); textView.setVisibility(View.VISIBLE); - String desktopInstructions = this.getString(R.string.desktopInstructions); - if(!checkVMResolutionFits()){ - String resolutionWarning = "Warning: Machine resolution " - + vm_width+ "x" + vm_height + - " is too high for Desktop Mode. " + - "Scaling will be used and Mouse Alignment will not be accurate. " + - "Reduce display resolution within the Guest OS for better experience.\n\n"; - desktopInstructions = resolutionWarning + desktopInstructions; - } - textView.setText(desktopInstructions); - - ScrollView scrollView = new ScrollView(this); - scrollView.addView(textView); + String desktopInstructions = this.getString(R.string.desktopInstructions); + if (!checkVMResolutionFits()) { + String resolutionWarning = "Warning: Machine resolution " + + vm_width + "x" + vm_height + + " is too high for Desktop Mode. " + + "Scaling will be used and Mouse Alignment will not be accurate. " + + "Reduce display resolution within the Guest OS for better experience.\n\n"; + desktopInstructions = resolutionWarning + desktopInstructions; + } + textView.setText(desktopInstructions); + + ScrollView scrollView = new ScrollView(this); + scrollView.addView(textView); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); @@ -595,7 +568,7 @@ public void onClick(DialogInterface dialog, int which) { private void setUIModeDesktop() { - try { + try { MotionEvent a = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0, 0, 0); //TODO: needed? @@ -608,112 +581,109 @@ private void setUIModeDesktop() { Config.mouseMode = Config.MouseMode.External; LimboSettingsManager.setDesktopMode(this, true); LimboActivity.vmexecutor.setRelativeMouseMode(0); - if(Config.showToast) + if (Config.showToast) UIUtils.toastShort(LimboSDLActivity.this, "External Mouse Enabled"); onNormalScreen(); calibration(); invalidateOptionsMenu(); - }catch (Exception ex){ - if(Config.debug) - ex.printStackTrace(); + } catch (Exception ex) { + if (Config.debug) + ex.printStackTrace(); } - } + } private void onCtrlAltDel() { - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_CTRL_RIGHT); - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_ALT_RIGHT); - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_FORWARD_DEL); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_FORWARD_DEL); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_ALT_RIGHT); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_CTRL_RIGHT); - } - - private void onCtrlC() { + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_RIGHT, true); + sendNativeKey(null, KeyEvent.KEYCODE_ALT_RIGHT, true); + sendNativeKey(null, KeyEvent.KEYCODE_FORWARD_DEL, true); + sendNativeKey(null, KeyEvent.KEYCODE_FORWARD_DEL, false); + sendNativeKey(null, KeyEvent.KEYCODE_ALT_RIGHT, false); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_RIGHT, false); + } - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_CTRL_RIGHT); - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_C); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_C); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_CTRL_RIGHT); - } + private void onCtrlC() { + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_RIGHT, true); + sendNativeKey(null, KeyEvent.KEYCODE_C, true); + sendNativeKey(null, KeyEvent.KEYCODE_C, false); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_RIGHT, false); + } - //TODO: not working - private void onStretchToScreen() { + //TODO: not working + private void onStretchToScreen() { - new Thread(new Runnable() { - public void run() { - Log.d(TAG, "onStretchToScreen"); - screenMode = SDLScreenMode.Fullscreen; + new Thread(new Runnable() { + public void run() { + Log.d(TAG, "onStretchToScreen"); + screenMode = SDLScreenMode.Fullscreen; sendCtrlAltKey(KeyEvent.KEYCODE_F); // not working - if(Config.showToast) - UIUtils.toastShort(activity, "Resizing, Please Wait"); + if (Config.showToast) + UIUtils.toastShort(LimboSDLActivity.this, "Resizing, Please Wait"); resize(null); - } - }).start(); + } + }).start(); - } + } - private void onFitToScreen() { - try { - UIUtils.setOrientation(this); - ActionBar bar = LimboSDLActivity.this.getSupportActionBar(); - if (bar != null && !LimboSettingsManager.getAlwaysShowMenuToolbar(this)) { - bar.hide(); - } - new Thread(new Runnable() { - public void run() { - Log.d(TAG, "onFitToScreen"); - screenMode = SDLScreenMode.FitToScreen; - if(Config.showToast) - UIUtils.toastShort(activity, "Resizing, Please Wait"); - resize(null); - - } - }).start(); - }catch (Exception ex){ - if(Config.debug) + private void onFitToScreen() { + try { + UIUtils.setOrientation(this); + ActionBar bar = LimboSDLActivity.this.getSupportActionBar(); + if (bar != null && !LimboSettingsManager.getAlwaysShowMenuToolbar(this)) { + bar.hide(); + } + new Thread(new Runnable() { + public void run() { + Log.d(TAG, "onFitToScreen"); + screenMode = SDLScreenMode.FitToScreen; + if (Config.showToast) + UIUtils.toastShort(LimboSDLActivity.this, "Resizing, Please Wait"); + resize(null); + + } + }).start(); + } catch (Exception ex) { + if (Config.debug) ex.printStackTrace(); } } - private void onNormalScreen() { - try { - ActionBar bar = LimboSDLActivity.this.getSupportActionBar(); - if (bar != null && !LimboSettingsManager.getAlwaysShowMenuToolbar(this)) { - bar.hide(); - } - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); - new Thread(new Runnable() { - public void run() { - Log.d(TAG, "onNormalScreen"); - screenMode = SDLScreenMode.Normal; - if(Config.showToast) - UIUtils.toastShort(activity, "Resizing, Please Wait"); - resize(null); + private void onNormalScreen() { + try { + ActionBar bar = LimboSDLActivity.this.getSupportActionBar(); + if (bar != null && !LimboSettingsManager.getAlwaysShowMenuToolbar(this)) { + bar.hide(); + } + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); + new Thread(new Runnable() { + public void run() { + Log.d(TAG, "onNormalScreen"); + screenMode = SDLScreenMode.Normal; + if (Config.showToast) + UIUtils.toastShort(LimboSDLActivity.this, "Resizing, Please Wait"); + resize(null); - } - }).start(); - }catch (Exception ex){ - if(Config.debug) + } + }).start(); + } catch (Exception ex) { + if (Config.debug) ex.printStackTrace(); } } - public void resize(final Configuration newConfig) { - - //XXX: flag so no mouse events are processed - isResizing = true; - - //XXX: This is needed so Nougat+ devices will update their layout - new Handler(Looper.getMainLooper()).post(new Runnable() { - @Override - public void run() { - ((LimboSDLSurface) mSurface).getHolder().setFixedSize(1, 1); + public void resize(final Configuration newConfig) { + //XXX: ignore further mouse events until we are done resizing + isResizing = true; + //XXX: This is needed so Nougat+ devices will update their layout + new Handler(Looper.getMainLooper()).post(new Runnable() { + @Override + public void run() { + ((LimboSDLSurface) mSurface).getHolder().setFixedSize(1, 1); setLayout(newConfig); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @@ -722,492 +692,476 @@ public void run() { ((LimboSDLSurface) mSurface).doResize(false, newConfig); } }, 1000); - } - }); - - } - - private void setZoomIn() { - - new Thread(new Runnable() { - public void run() { - screenMode = SDLScreenMode.Normal; - sendCtrlAltKey(KeyEvent.KEYCODE_4); - } - }).start(); - - } - - private void setZoomOut() { + } + }); + } + private void setZoomIn() { - new Thread(new Runnable() { - public void run() { + new Thread(new Runnable() { + public void run() { screenMode = SDLScreenMode.Normal; - sendCtrlAltKey(KeyEvent.KEYCODE_3); - - } - }).start(); - - } + sendCtrlAltKey(KeyEvent.KEYCODE_4); + } + }).start(); - private void setZoomable() { + } - zoomable = true; + private void setZoomOut() { + new Thread(new Runnable() { + public void run() { + screenMode = SDLScreenMode.Normal; + sendCtrlAltKey(KeyEvent.KEYCODE_3); + } + }).start(); + } - } + private void setZoomable() { + //TODO: + } - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - menu.clear(); - return this.setupMenu(menu); - } + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + menu.clear(); + return this.setupMenu(menu); + } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - menu.clear(); - return this.setupMenu(menu); - } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + menu.clear(); + return this.setupMenu(menu); + } - public boolean setupMenu(Menu menu) { - // Log.v("Limbo", "Inside Options Created"); - getMenuInflater().inflate(R.menu.sdlactivitymenu, menu); + public boolean setupMenu(Menu menu) { + getMenuInflater().inflate(R.menu.sdlactivitymenu, menu); int maxMenuItemsShown = 4; int actionShow = MenuItemCompat.SHOW_AS_ACTION_IF_ROOM; - if(UIUtils.isLandscapeOrientation(this)) { + if (UIUtils.isLandscapeOrientation(this)) { maxMenuItemsShown = 6; actionShow = MenuItemCompat.SHOW_AS_ACTION_ALWAYS; } - // if (vncCanvas.scaling != null) { - // menu.findItem(vncCanvas.scaling.getId()).setChecked(true); - // } + //TODO: enable scaling + // if (vncCanvas.scaling != null) { + // menu.findItem(vncCanvas.scaling.getId()).setChecked(true); + // } - // Remove snapshots for now - menu.removeItem(menu.findItem(R.id.itemSaveSnapshot).getItemId()); + // Remove snapshots for now + menu.removeItem(menu.findItem(R.id.itemSaveSnapshot).getItemId()); - // Remove Monitor console for SDL2 it creates 2 SDL windows and SDL for - // android supports only 1 - menu.removeItem(menu.findItem(R.id.itemMonitor).getItemId()); + // Remove Monitor console for SDL2 it creates 2 SDL windows and SDL for + // android supports only 1 + menu.removeItem(menu.findItem(R.id.itemMonitor).getItemId()); - // Remove scaling for now - menu.removeItem(menu.findItem(R.id.itemScaling).getItemId()); + // Remove scaling for now + menu.removeItem(menu.findItem(R.id.itemScaling).getItemId()); - // Remove external mouse for now - menu.removeItem(menu.findItem(R.id.itemExternalMouse).getItemId()); - //menu.removeItem(menu.findItem(R.id.itemUIMode).getItemId()); + // Remove external mouse for now + menu.removeItem(menu.findItem(R.id.itemExternalMouse).getItemId()); menu.removeItem(menu.findItem(R.id.itemCtrlAltDel).getItemId()); menu.removeItem(menu.findItem(R.id.itemCtrlC).getItemId()); - if (LimboSettingsManager.getAlwaysShowMenuToolbar(activity) || Config.mouseMode == Config.MouseMode.External) { + if (LimboSettingsManager.getAlwaysShowMenuToolbar(this) || Config.mouseMode == Config.MouseMode.External) { menu.removeItem(menu.findItem(R.id.itemHideToolbar).getItemId()); maxMenuItemsShown--; } - if (soundcard==null || soundcard.equals("None")) { + if (soundcard == null || soundcard.equals("None")) { menu.removeItem(menu.findItem(R.id.itemVolume).getItemId()); maxMenuItemsShown--; } - for (int i = 0; i < menu.size() && i < maxMenuItemsShown; i++) { MenuItemCompat.setShowAsAction(menu.getItem(i), actionShow); } - return true; - - } - - private void onMonitor() { - new Thread(new Runnable() { - public void run() { - monitorMode = true; - // final KeyEvent altDown = new KeyEvent(downTime, eventTime, - // KeyEvent.ACTION_DOWN, - // KeyEvent.KEYCODE_2, 1, KeyEvent.META_ALT_LEFT_ON); - sendCtrlAltKey(KeyEvent.KEYCODE_2); - // sendCtrlAltKey(altDown); - Log.v("Limbo", "Monitor On"); - } - }).start(); - - } - - private void onVMConsole() { - monitorMode = false; - sendCtrlAltKey(KeyEvent.KEYCODE_1); - } - - - // FIXME: We need this to able to catch complex characters strings like - // grave and send it as text - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - if (event.getAction() == KeyEvent.ACTION_MULTIPLE && event.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN) { - sendText(event.getCharacters().toString()); - return true; - } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { - this.onBackPressed(); - return true; - } if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) { - // We emulate right click with volume down - if(event.getAction() == KeyEvent.ACTION_DOWN) { - MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, 0, 0, 0, 0, 0, 0, 0, - InputDevice.SOURCE_TOUCHSCREEN, 0); - rightClick(e, 0); - } - return true; - } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) { - // We emulate middle click with volume up - if(event.getAction() == KeyEvent.ACTION_DOWN) { - MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, 0, 0, 0, 0, 0, 0, 0, - InputDevice.SOURCE_TOUCHSCREEN, 0); - middleClick(e, 0); - } - return true; - } else { - return super.dispatchKeyEvent(event); - } - - } - - private static void sendText(String string) { - - // Log.v("sendText", string); - KeyCharacterMap keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); - KeyEvent[] keyEvents = keyCharacterMap.getEvents(string.toCharArray()); - if (keyEvents != null) - for (int i = 0; i < keyEvents.length; i++) { - - if (keyEvents[i].getAction() == KeyEvent.ACTION_DOWN) { - // Log.v("sendText", "Up: " + keyEvents[i].getKeyCode()); - SDLActivity.onNativeKeyDown(keyEvents[i].getKeyCode()); - } else if (keyEvents[i].getAction() == KeyEvent.ACTION_UP) { - // Log.v("sendText", "Down: " + keyEvents[i].getKeyCode()); - SDLActivity.onNativeKeyUp(keyEvents[i].getKeyCode()); - } - } - } - - - // Setup - protected void onCreate(Bundle savedInstanceState) { - // Log.v("SDL", "onCreate()"); - activity = this; - - if (LimboSettingsManager.getFullscreen(this)) - getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, - WindowManager.LayoutParams.FLAG_FULLSCREEN); - - super.onCreate(savedInstanceState); - setupVolume(); + return true; - mSingleton = this; + } - Log.v("SDL", "Max Mem = " + Runtime.getRuntime().maxMemory()); + private void onMonitor() { + new Thread(new Runnable() { + public void run() { + monitorMode = true; + // final KeyEvent altDown = new KeyEvent(downTime, eventTime, + // KeyEvent.ACTION_DOWN, + // KeyEvent.KEYCODE_2, 1, KeyEvent.META_ALT_LEFT_ON); + sendCtrlAltKey(KeyEvent.KEYCODE_2); + // sendCtrlAltKey(altDown); + Log.v("Limbo", "Monitor On"); + } + }).start(); - this.activity1 = this; + } - if (LimboActivity.currMachine == null) { - Log.v("SDLAcivity", "No VM selected!"); - }else - setParams(LimboActivity.currMachine); + private void onVMConsole() { + monitorMode = false; + sendCtrlAltKey(KeyEvent.KEYCODE_1); + } - // So we can call stuff from static callbacks - mSingleton = this; - createUI(0, 0); + // FIXME: We need this to able to catch complex characters strings like + // grave and send it as text + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_MULTIPLE && event.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN) { + sendText(event.getCharacters().toString()); + return true; + } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { + this.onBackPressed(); + return true; + } + if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) { + // We emulate right click with volume down + if (event.getAction() == KeyEvent.ACTION_DOWN) { + MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, 0, 0, 0, 0, 0, 0, 0, + InputDevice.SOURCE_TOUCHSCREEN, 0); + rightClick(e, 0); + } + return true; + } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) { + // We emulate middle click with volume up + if (event.getAction() == KeyEvent.ACTION_DOWN) { + MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, 0, 0, 0, 0, 0, 0, 0, + InputDevice.SOURCE_TOUCHSCREEN, 0); + middleClick(e, 0); + } + return true; + } else { + return super.dispatchKeyEvent(event); + } - UIUtils.setupToolBar(this); + } - UIUtils.showHints(this); + private static void sendText(String string) { - this.resumeVM(); + // Log.v("sendText", string); + KeyCharacterMap keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); + KeyEvent[] keyEvents = keyCharacterMap.getEvents(string.toCharArray()); + if (keyEvents != null) + for (int i = 0; i < keyEvents.length; i++) { - UIUtils.setOrientation(this); + if (keyEvents[i].getAction() == KeyEvent.ACTION_DOWN) { + // Log.v("sendText", "Up: " + keyEvents[i].getKeyCode()); + sendNativeKey(null, keyEvents[i].getKeyCode(), true); + } else if (keyEvents[i].getAction() == KeyEvent.ACTION_UP) { + // Log.v("sendText", "Down: " + keyEvents[i].getKeyCode()); + sendNativeKey(null, keyEvents[i].getKeyCode(), false); + } + } + } + protected void onCreate(Bundle savedInstanceState) { + if (LimboSettingsManager.getFullscreen(this)) + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, + WindowManager.LayoutParams.FLAG_FULLSCREEN); - } + //XXX: if the app is terminated the last activity is in the recents + // so we prevent crashing + checkIfStarted(); - private void createUI(int w, int h) { - mSurface = new LimboSDLSurface(this); + super.onCreate(savedInstanceState); + setupVolume(); + mSingleton = this; + Log.v("SDL", "Max Mem = " + Runtime.getRuntime().maxMemory()); - int width = w; - int height = h; - if (width == 0) { - width = RelativeLayout.LayoutParams.WRAP_CONTENT; - } - if (height == 0) { - height = RelativeLayout.LayoutParams.WRAP_CONTENT; - } + if (LimboActivity.currMachine == null) { + Log.v("SDLAcivity", "No VM selected!"); + } else + setParams(LimboActivity.currMachine); - setContentView(R.layout.limbo_sdl); + // So we can call stuff from static callbacks + mSingleton = this; - //TODO: - mLayout = (RelativeLayout) activity.findViewById(R.id.sdl_layout); - mMainLayout = (LinearLayout) activity.findViewById(R.id.main_layout); + createUI(0, 0); + UIUtils.setupToolBar(this); + UIUtils.showHints(this); + resumeVM(); + UIUtils.setOrientation(this); + } - RelativeLayout mLayout = (RelativeLayout) findViewById(R.id.sdl); - RelativeLayout.LayoutParams surfaceParams = new RelativeLayout.LayoutParams(width, height); - surfaceParams.addRule(RelativeLayout.CENTER_IN_PARENT); + public static LimboSDLActivity getSingleton() { + return (LimboSDLActivity) mSingleton; + } - mLayout.addView(mSurface, surfaceParams); + private void checkIfStarted() { + if (LimboActivity.vmexecutor == null) + System.exit(1); + } - } + private void createUI(int w, int h) { + mSurface = new LimboSDLSurface(this); - protected void onPause() { - Log.v("SDL", "onPause()"); - LimboService.updateServiceNotification(LimboActivity.currMachine.machinename + ": VM Suspended"); - super.onPause(); + int width = w; + int height = h; + if (width == 0) { + width = RelativeLayout.LayoutParams.WRAP_CONTENT; + } + if (height == 0) { + height = RelativeLayout.LayoutParams.WRAP_CONTENT; + } + setContentView(R.layout.limbo_sdl); + mLayout = (RelativeLayout) findViewById(R.id.sdl_layout); + mMainLayout = (LinearLayout) findViewById(R.id.main_layout); + RelativeLayout mLayout = (RelativeLayout) findViewById(R.id.sdl); + RelativeLayout.LayoutParams surfaceParams = new RelativeLayout.LayoutParams(width, height); + surfaceParams.addRule(RelativeLayout.CENTER_IN_PARENT); + mLayout.addView(mSurface, surfaceParams); + } - } + protected void onPause() { + Log.v("SDL", "onPause()"); + LimboService.updateServiceNotification(LimboActivity.currMachine.machinename + ": VM Suspended"); + super.onPause(); + + } - public void onSelectMenuVol() { + public void onSelectMenuVol() { - final AlertDialog alertDialog; - alertDialog = new AlertDialog.Builder(activity).create(); - alertDialog.setTitle("Volume"); + final AlertDialog alertDialog; + alertDialog = new AlertDialog.Builder(this).create(); + alertDialog.setTitle("Volume"); LinearLayout.LayoutParams volParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); - LinearLayout t = createVolumePanel(); - t.setLayoutParams(volParams); + LinearLayout t = createVolumePanel(); + t.setLayoutParams(volParams); - ScrollView s = new ScrollView(activity); - s.addView(t); - alertDialog.setView(s); - alertDialog.setButton(Dialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { + ScrollView s = new ScrollView(this); + s.addView(t); + alertDialog.setView(s); + alertDialog.setButton(Dialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - alertDialog.cancel(); - } - }); - alertDialog.show(); + public void onClick(DialogInterface dialog, int which) { + alertDialog.cancel(); + } + }); + alertDialog.show(); - } + } - public LinearLayout createVolumePanel() { - LinearLayout layout = new LinearLayout (this); - layout.setPadding(20, 20, 20, 20); + public LinearLayout createVolumePanel() { + LinearLayout layout = new LinearLayout(this); + layout.setPadding(20, 20, 20, 20); LinearLayout.LayoutParams volparams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); - SeekBar vol = new SeekBar(this); + SeekBar vol = new SeekBar(this); - int volume = 0; + int volume = 0; - //TODO: - vol.setMax(maxVolume); - volume = getCurrentVolume(); + //TODO: + vol.setMax(maxVolume); + volume = getCurrentVolume(); - vol.setProgress(volume); - vol.setLayoutParams(volparams); + vol.setProgress(volume); + vol.setLayoutParams(volparams); - ((SeekBar) vol).setOnSeekBarChangeListener(new OnSeekBarChangeListener() { + ((SeekBar) vol).setOnSeekBarChangeListener(new OnSeekBarChangeListener() { - public void onProgressChanged(SeekBar s, int progress, boolean touch) { - //TODO: + public void onProgressChanged(SeekBar s, int progress, boolean touch) { + //TODO: setVolume(progress); - } + } - public void onStartTrackingTouch(SeekBar arg0) { + public void onStartTrackingTouch(SeekBar arg0) { - } + } - public void onStopTrackingTouch(SeekBar arg0) { + public void onStopTrackingTouch(SeekBar arg0) { - } - }); + } + }); - layout.addView(vol); + layout.addView(vol); - return layout; + return layout; - } + } - protected void onResume() { - Log.v("SDL", "onResume()"); - LimboService.updateServiceNotification(LimboActivity.currMachine.machinename + ": VM Running"); - super.onResume(); - } + protected void onResume() { + Log.v("SDL", "onResume()"); + LimboService.updateServiceNotification(LimboActivity.currMachine.machinename + ": VM Running"); + super.onResume(); + } - // Messages from the SDLMain thread - static int COMMAND_CHANGE_TITLE = 1; - static int COMMAND_SAVEVM = 2; + // Messages from the SDLMain thread + static int COMMAND_CHANGE_TITLE = 1; + static int COMMAND_SAVEVM = 2; - public void loadLibraries() { + public void loadLibraries() { //XXX: override for the specific arch - } - - - public void promptPause(final Activity activity) { - - final AlertDialog alertDialog; - alertDialog = new AlertDialog.Builder(activity).create(); - alertDialog.setTitle("Pause VM"); - TextView stateView = new TextView(activity); - stateView.setText("This make take a while depending on the RAM size used"); - stateView.setPadding(20, 20, 20, 20); - alertDialog.setView(stateView); - - alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Pause", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int which) { - onPauseVM(); - return; - } - }); - alertDialog.show(); - } - - private void onPauseVM() { - Thread t = new Thread(new Runnable() { - public void run() { - // Delete any previous state file - if (LimboActivity.vmexecutor.save_state_name != null) { - File file = new File(LimboActivity.vmexecutor.save_state_name); - if (file.exists()) { - file.delete(); - } - } - if(Config.showToast) - UIUtils.toastShort(getApplicationContext(), "Please wait while saving VM State"); - LimboActivity.vmexecutor.current_fd = LimboActivity.vmexecutor.get_fd(LimboActivity.vmexecutor.save_state_name); - - String uri = "fd:" + LimboActivity.vmexecutor.current_fd; - String command = QmpClient.stop(); - String msg = QmpClient.sendCommand(command); - command = QmpClient.migrate(false, false, uri); - msg = QmpClient.sendCommand(command); - if (msg != null) { + } + + + public void promptPause(final Activity activity) { + + final AlertDialog alertDialog; + alertDialog = new AlertDialog.Builder(activity).create(); + alertDialog.setTitle("Pause VM"); + TextView stateView = new TextView(activity); + stateView.setText("This make take a while depending on the RAM size used"); + stateView.setPadding(20, 20, 20, 20); + alertDialog.setView(stateView); + + alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Pause", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + onPauseVM(); + return; + } + }); + alertDialog.show(); + } + + private void onPauseVM() { + Thread t = new Thread(new Runnable() { + public void run() { + // Delete any previous state file + if (LimboActivity.vmexecutor.save_state_name != null) { + File file = new File(LimboActivity.vmexecutor.save_state_name); + if (file.exists()) { + file.delete(); + } + } + if (Config.showToast) + UIUtils.toastShort(getApplicationContext(), "Please wait while saving VM State"); + LimboActivity.vmexecutor.current_fd = LimboActivity.vmexecutor.get_fd(LimboActivity.vmexecutor.save_state_name); + + String uri = "fd:" + LimboActivity.vmexecutor.current_fd; + String command = QmpClient.stop(); + String msg = QmpClient.sendCommand(command); + command = QmpClient.migrate(false, false, uri); + msg = QmpClient.sendCommand(command); + if (msg != null) { processMigrationResponse(msg); } - // XXX: Instead we poll to see if migration is complete - new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { - @Override - public void run() { - VMListener a = new VMListener(); - a.execute(); - } - }, 0); - } - }); - t.start(); + // XXX: Instead we poll to see if migration is complete + new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { + @Override + public void run() { + VMListener a = new VMListener(); + a.execute(); + } + }, 0); + } + }); + t.start(); - } + } private void processMigrationResponse(String response) { String errorStr = null; try { JSONObject object = new JSONObject(response); errorStr = object.getString("error"); - }catch (Exception ex) { - if(Config.debug) - ex.printStackTrace(); + } catch (Exception ex) { + if (Config.debug) + ex.printStackTrace(); } - if (errorStr != null) { - String descStr = null; + if (errorStr != null) { + String descStr = null; + + try { + JSONObject descObj = new JSONObject(errorStr); + descStr = descObj.getString("desc"); + } catch (Exception ex) { + if (Config.debug) + ex.printStackTrace(); + } + final String descStr1 = descStr; - try { - JSONObject descObj = new JSONObject(errorStr); - descStr = descObj.getString("desc"); - }catch (Exception ex) { - if(Config.debug) - ex.printStackTrace(); + new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { + @Override + public void run() { + Machine.pausedErrorVM(LimboSDLActivity.this, descStr1); } - final String descStr1 = descStr; - - new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { - @Override - public void run() { - Machine.pausedErrorVM(activity, descStr1); - } - }, 100); + }, 100); - } + } } private class VMListener extends AsyncTask { - @Override - protected Void doInBackground(Void... arg0) { - startTimeListener(); - return null; - } + @Override + protected Void doInBackground(Void... arg0) { + startTimeListener(); + return null; + } - @Override - protected void onPostExecute(Void test) { + @Override + protected void onPostExecute(Void test) { - } - } + } + } - @Override - public boolean onTouchEvent(MotionEvent event) { + @Override + public boolean onTouchEvent(MotionEvent event) { boolean res = false; - if(Config.mouseMode == Config.MouseMode.External){ + if (Config.mouseMode == Config.MouseMode.External) { return res; } //TODO: - res = ((LimboSDLSurface) this.mSurface).onTouchProcess(this.mSurface, event); - res = ((LimboSDLSurface) this.mSurface).onTouchEventProcess(event); - return true; - } - - private void resumeVM() { - if(LimboActivity.vmexecutor == null){ - return; - } - Thread t = new Thread(new Runnable() { - public void run() { - if (LimboActivity.vmexecutor.paused == 1) { - - try { - Thread.sleep(4000); - } catch (InterruptedException ex) { - Logger.getLogger(LimboVNCActivity.class.getName()).log(Level.SEVERE, null, ex); - } - LimboActivity.vmexecutor.paused = 0; - - String command = QmpClient.cont(); - String msg = QmpClient.sendCommand(command); - new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { - @Override - public void run() { - if(Config.mouseMode == Config.MouseMode.External) - setUIModeDesktop(); - else - setUIModeMobile(screenMode == SDLScreenMode.FitToScreen); - } - }, 500); - } - } - }); - t.start(); - - } - - public void onBackPressed() { - if (!LimboSettingsManager.getAlwaysShowMenuToolbar(activity)) { - ActionBar bar = this.getSupportActionBar(); - if (bar != null) { - if (bar.isShowing()) - bar.hide(); - else - bar.show(); - } - } else { + res = ((LimboSDLSurface) this.mSurface).onTouchProcess(this.mSurface, event); + res = ((LimboSDLSurface) this.mSurface).onTouchEventProcess(event); + return true; + } + + private void resumeVM() { + if (LimboActivity.vmexecutor == null) { + return; + } + Thread t = new Thread(new Runnable() { + public void run() { + if (LimboActivity.vmexecutor.paused == 1) { + + try { + Thread.sleep(4000); + } catch (InterruptedException ex) { + Logger.getLogger(LimboVNCActivity.class.getName()).log(Level.SEVERE, null, ex); + } + LimboActivity.vmexecutor.paused = 0; + + String command = QmpClient.cont(); + String msg = QmpClient.sendCommand(command); + new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { + @Override + public void run() { + if (Config.mouseMode == Config.MouseMode.External) + setUIModeDesktop(); + else + setUIModeMobile(screenMode == SDLScreenMode.FitToScreen); + } + }, 500); + } + } + }); + t.start(); + + } + + public void onBackPressed() { + if (!LimboSettingsManager.getAlwaysShowMenuToolbar(this)) { + ActionBar bar = this.getSupportActionBar(); + if (bar != null) { + if (bar.isShowing()) + bar.hide(); + else + bar.show(); + } + } else { UIUtils.hideKeyboard(this, mSurface); - Machine.stopVM(activity); - } + Machine.stopVM(this); + } - } + } @Override public void onConfigurationChanged(Configuration newConfig) { @@ -1218,7 +1172,7 @@ public void onConfigurationChanged(Configuration newConfig) { public void onSelectMenuSDLDisplay() { final AlertDialog alertDialog; - alertDialog = new AlertDialog.Builder(activity).create(); + alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Display"); LinearLayout.LayoutParams volParams = new LinearLayout.LayoutParams( @@ -1227,7 +1181,7 @@ public void onSelectMenuSDLDisplay() { LinearLayout t = createSDLDisplayPanel(); t.setLayoutParams(volParams); - ScrollView s = new ScrollView(activity); + ScrollView s = new ScrollView(this); s.addView(t); alertDialog.setView(s); alertDialog.setButton(Dialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @@ -1253,7 +1207,7 @@ public LinearLayout createSDLDisplayPanel() { LinearLayout buttonsLayout = new LinearLayout(this); buttonsLayout.setOrientation(LinearLayout.HORIZONTAL); buttonsLayout.setGravity(Gravity.CENTER_HORIZONTAL); - Button displayMode = new Button (this); + Button displayMode = new Button(this); displayMode.setText("Display Mode"); displayMode.setOnClickListener(new View.OnClickListener() { @@ -1265,7 +1219,7 @@ public void onClick(View view) { layout.addView(buttonsLayout); final TextView value = new TextView(this); - value.setText("Idle Refresh Rate: " + currRate+" Hz"); + value.setText("Idle Refresh Rate: " + currRate + " Hz"); layout.addView(value); value.setLayoutParams(params); @@ -1278,7 +1232,7 @@ public void onClick(View view) { ((SeekBar) rate).setOnSeekBarChangeListener(new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar s, int progress, boolean touch) { - value.setText("Idle Refresh Rate: " + (progress+1)+" Hz"); + value.setText("Idle Refresh Rate: " + (progress + 1) + " Hz"); } public void onStartTrackingTouch(SeekBar arg0) { @@ -1286,7 +1240,7 @@ public void onStartTrackingTouch(SeekBar arg0) { } public void onStopTrackingTouch(SeekBar arg0) { - int progress = arg0.getProgress()+1; + int progress = arg0.getProgress() + 1; int refreshMs = 1000 / progress; Log.v(TAG, "Changing idle refresh rate: (ms)" + refreshMs); LimboActivity.vmexecutor.setsdlrefreshrate(refreshMs); @@ -1305,31 +1259,30 @@ public int getCurrentSDLRefreshRate() { } - private void onDisplayMode() { - String [] items = { + String[] items = { "Normal (One-To-One)", "Fit To Screen" // ,"Stretch To Screen" //Stretched }; int currentScaleType = 0; - if(screenMode == SDLScreenMode.FitToScreen){ - currentScaleType = 1; - } else if(screenMode == SDLScreenMode.Fullscreen) - currentScaleType = 2; + if (screenMode == SDLScreenMode.FitToScreen) { + currentScaleType = 1; + } else if (screenMode == SDLScreenMode.Fullscreen) + currentScaleType = 2; final AlertDialog.Builder mBuilder = new AlertDialog.Builder(this); mBuilder.setTitle("Display Mode"); mBuilder.setSingleChoiceItems(items, currentScaleType, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { - switch(i){ + switch (i) { case 0: onNormalScreen(); break; case 1: - if(Config.mouseMode == Config.MouseMode.External){ + if (Config.mouseMode == Config.MouseMode.External) { UIUtils.toastShort(LimboSDLActivity.this, "Fit to Screen Disabled under Desktop Mode"); dialog.dismiss(); return; @@ -1337,12 +1290,12 @@ public void onClick(DialogInterface dialog, int i) { onFitToScreen(); break; case 2: - if(Config.mouseMode == Config.MouseMode.External){ - UIUtils.toastShort(LimboSDLActivity.this, "Stretch Screen Disabled under Desktop Mode"); - dialog.dismiss(); - return; - } - onStretchToScreen(); + if (Config.mouseMode == Config.MouseMode.External) { + UIUtils.toastShort(LimboSDLActivity.this, "Stretch Screen Disabled under Desktop Mode"); + dialog.dismiss(); + return; + } + onStretchToScreen(); break; default: break; @@ -1357,38 +1310,35 @@ public void onClick(DialogInterface dialog, int i) { @Override - protected synchronized void runSDLMain(){ - - //We go through the vm executor - LimboActivity.startvm(this, Config.UI_SDL); + protected synchronized void runSDLMain() { - //XXX: we hold the thread because SDLActivity will exit - try { - wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + //We go through the vm executor + LimboActivity.startvm(this, Config.UI_SDL); - public static void onVMResolutionChanged(int w, int h) - { - boolean refreshDisplay = false; - - if(w!=vm_width || h!=vm_height) - refreshDisplay = true; - vm_width = w; - vm_height = h; + //XXX: we hold the thread because SDLActivity will exit + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } - Log.v(TAG, "VM resolution changed to " + vm_width + "x" + vm_height); + public void onVMResolutionChanged(int w, int h) { + boolean refreshDisplay = false; + if (w != vm_width || h != vm_height) + refreshDisplay = true; + vm_width = w; + vm_height = h; - if(refreshDisplay) { - activity.resize(null); - } + Log.v(TAG, "VM resolution changed to " + vm_width + "x" + vm_height); + if (refreshDisplay) { + resize(null); + } - } + } - public static boolean isResizing = false; + public static boolean isResizing = false; public enum SDLScreenMode { Normal, @@ -1401,13 +1351,13 @@ public enum SDLScreenMode { private void setLayout(Configuration newConfig) { boolean isLanscape = - (newConfig!=null && newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) + (newConfig != null && newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) || UIUtils.isLandscapeOrientation(this); View vnc_canvas_layout = (View) this.findViewById(R.id.sdl_layout); RelativeLayout.LayoutParams vnc_canvas_layout_params = null; //normal 1-1 - if(screenMode == SDLScreenMode.Normal) { + if (screenMode == SDLScreenMode.Normal) { if (isLanscape) { vnc_canvas_layout_params = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, @@ -1448,108 +1398,107 @@ private void setLayout(Configuration newConfig) { this.invalidateOptionsMenu(); } - public class LimboSDLSurface extends ExSDLSurface implements View.OnKeyListener, View.OnTouchListener { + public class LimboSDLSurface extends ExSDLSurface implements View.OnKeyListener, View.OnTouchListener { - public boolean initialized = false; + public boolean initialized = false; - public LimboSDLSurface(Context context) { - super(context); - setOnKeyListener(this); - setOnTouchListener(this); - gestureDetector = new GestureDetector(activity, new GestureListener()); - setOnGenericMotionListener(new SDLGenericMotionListener_API12()); - } + public LimboSDLSurface(Context context) { + super(context); + setOnKeyListener(this); + setOnTouchListener(this); + gestureDetector = new GestureDetector(LimboSDLActivity.this, new GestureListener()); + setOnGenericMotionListener(new SDLGenericMotionListener_API12()); + } - public void surfaceChanged(SurfaceHolder holder, - int format, int width, int height) { - super.surfaceChanged(holder, format, width, height); + public void surfaceChanged(SurfaceHolder holder, + int format, int width, int height) { + super.surfaceChanged(holder, format, width, height); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - SDLActivity.onNativeKeyDown(KeyEvent.KEYCODE_CTRL_LEFT); - SDLActivity.onNativeKeyUp(KeyEvent.KEYCODE_CTRL_LEFT); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_LEFT, true); + sendNativeKey(null, KeyEvent.KEYCODE_CTRL_LEFT, false); } }, 500); - } + } - @Override - public void surfaceCreated(SurfaceHolder holder) { - super.surfaceCreated(holder); + @Override + public void surfaceCreated(SurfaceHolder holder) { + super.surfaceCreated(holder); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { - if(Config.mouseMode == Config.MouseMode.External) + if (Config.mouseMode == Config.MouseMode.External) setUIModeDesktop(); else setUIModeMobile(screenMode == SDLScreenMode.FitToScreen); } - },1000); - } + }, 1000); + } - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - Log.d(TAG,"Configuration changed"); + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + Log.d(TAG, "Configuration changed"); resize(newConfig); - } - + } - public synchronized void doResize(boolean reverse, final Configuration newConfig) { - //XXX: notify the UI not to process mouse motion - isResizing = true; - Log.v(TAG, "Resizing Display"); + public synchronized void doResize(boolean reverse, final Configuration newConfig) { + //XXX: notify the UI not to process mouse motion + isResizing = true; + Log.v(TAG, "Resizing Display"); - Display display = SDLActivity.mSingleton.getWindowManager().getDefaultDisplay(); - int height = 0; - int width = 0; + Display display = SDLActivity.mSingleton.getWindowManager().getDefaultDisplay(); + int height = 0; + int width = 0; - Point size = new Point(); - display.getSize(size); - int screen_width = size.x; - int screen_height = size.y; + Point size = new Point(); + display.getSize(size); + int screen_width = size.x; + int screen_height = size.y; - final ActionBar bar = ((SDLActivity) activity).getSupportActionBar(); + final ActionBar bar = getSupportActionBar(); - if(LimboSDLActivity.mLayout != null) { - width = LimboSDLActivity.mLayout.getWidth(); - height = LimboSDLActivity.mLayout.getHeight(); - } + if (LimboSDLActivity.mLayout != null) { + width = LimboSDLActivity.mLayout.getWidth(); + height = LimboSDLActivity.mLayout.getHeight(); + } - //native resolution for use with external mouse - if(screenMode != SDLScreenMode.Fullscreen && screenMode != SDLScreenMode.FitToScreen) { - width = LimboSDLActivity.vm_width; - height = LimboSDLActivity.vm_height; - } + //native resolution for use with external mouse + if (screenMode != SDLScreenMode.Fullscreen && screenMode != SDLScreenMode.FitToScreen) { + width = vm_width; + height = vm_height; + } - if(reverse){ - int temp = width; - width = height; - height = temp; - } + if (reverse) { + int temp = width; + width = height; + height = temp; + } - boolean portrait = SDLActivity.mSingleton.getResources() - .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; + boolean portrait = SDLActivity.mSingleton.getResources() + .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; - if (portrait) { - if(Config.mouseMode != Config.MouseMode.External) { - int height_n = (int) (width / (LimboSDLActivity.vm_width / (float) LimboSDLActivity.vm_height)); + if (portrait) { + if (Config.mouseMode != Config.MouseMode.External) { + int height_n = (int) (width / (vm_width / (float) vm_height)); Log.d(TAG, "Resizing portrait: " + width + " x " + height_n); - getHolder().setFixedSize(width, height_n); - } - } else { - if ( (screenMode == SDLScreenMode.Fullscreen || screenMode == SDLScreenMode.FitToScreen) - && !LimboSettingsManager.getAlwaysShowMenuToolbar(LimboSDLActivity.this) - && bar != null && bar.isShowing()) { - height += bar.getHeight(); - } + getHolder().setFixedSize(width, height_n); + } + } else { + if ((screenMode == SDLScreenMode.Fullscreen || screenMode == SDLScreenMode.FitToScreen) + && !LimboSettingsManager.getAlwaysShowMenuToolbar(LimboSDLActivity.this) + && bar != null && bar.isShowing()) { + height += bar.getHeight(); + } Log.d(TAG, "Resizing landscape: " + width + " x " + height); - getHolder().setFixedSize(width, height); - } - initialized = true; + getHolder().setFixedSize(width, height); + } + initialized = true; new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override @@ -1558,368 +1507,396 @@ public void run() { } }, 1000); + } + + // XXX: SDL is missing some key codes in sdl2-keymap.h + // So we create them with a Shift Modifier + private boolean handleMissingKeys(int keyCode, int action) { + + int keyCodeTmp = keyCode; + switch (keyCode) { + case 77: + keyCodeTmp = 9; + break; + case 81: + keyCodeTmp = 70; + break; + case 17: + keyCodeTmp = 15; + break; + case 18: + keyCodeTmp = 10; + break; + default: + return false; + } + if (action == KeyEvent.ACTION_DOWN) { + sendNativeKey(null, 59, true); + sendNativeKey(null, keyCodeTmp, true); + } else { + sendNativeKey(null, 59, false); + sendNativeKey(null, keyCodeTmp, false); + } + return true; + } + + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) { + + if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) { + // dismiss android back and forward keys + return true; + } else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) { + return false; + } else if (event.getAction() == KeyEvent.ACTION_DOWN) { + //Log.v("SDL", "key down: " + keyCode); + sendKeyAsync(event, keyCode, event.getAction(), true); + return true; + } else if (event.getAction() == KeyEvent.ACTION_UP) { + //Log.v("SDL", "key up: " + keyCode); + sendKeyAsync(event, keyCode, event.getAction(), false); + return true; + } else { + return super.onKey(v, keyCode, event); + } + } + final Object sendKeyLock = new Object(); - } - - // XXX: SDL is missing some key codes in sdl2-keymap.h - // So we create them with a Shift Modifier - private boolean handleMissingKeys(int keyCode, int action) { - - int keyCodeTmp = keyCode; - switch (keyCode) { - case 77: - keyCodeTmp = 9; - break; - case 81: - keyCodeTmp = 70; - break; - case 17: - keyCodeTmp = 15; - break; - case 18: - keyCodeTmp = 10; - break; - default: - return false; - - } - if (action == KeyEvent.ACTION_DOWN) { - SDLActivity.onNativeKeyDown(59); - SDLActivity.onNativeKeyDown(keyCodeTmp); - } else { - SDLActivity.onNativeKeyUp(59); - SDLActivity.onNativeKeyUp(keyCodeTmp); - } - return true; - - } - - @Override - public boolean onKey(View v, int keyCode, KeyEvent event) { - - if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) { - // dismiss android back and forward keys - return true; - } else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) { - return false; - } else if (event.getAction() == KeyEvent.ACTION_DOWN) { - //Log.v("SDL", "key down: " + keyCode); - if (!handleMissingKeys(keyCode, event.getAction())) - SDLActivity.onNativeKeyDown(keyCode); - return true; - } else if (event.getAction() == KeyEvent.ACTION_UP) { - //Log.v("SDL", "key up: " + keyCode); - if (!handleMissingKeys(keyCode, event.getAction())) - SDLActivity.onNativeKeyUp(keyCode); - return true; - } else { - return super.onKey(v, keyCode, event); - } - - } - - // Touch events - public boolean onTouchProcess(View v, MotionEvent event) { - int action = event.getAction(); - float x = event.getX(0); - float y = event.getY(0); - float p = event.getPressure(0); - - int relative = Config.mouseMode == Config.MouseMode.External? 0: 1; - - int sdlMouseButton = 0; - if(event.getButtonState() == MotionEvent.BUTTON_PRIMARY) - sdlMouseButton = Config.SDL_MOUSE_LEFT; - else if(event.getButtonState() == MotionEvent.BUTTON_SECONDARY) - sdlMouseButton = Config.SDL_MOUSE_RIGHT; - else if(event.getButtonState() == MotionEvent.BUTTON_TERTIARY) - sdlMouseButton = Config.SDL_MOUSE_MIDDLE; - - - if (event.getAction() == MotionEvent.ACTION_MOVE) { - - if (mouseUp) { - old_x = x; - old_y = y; - mouseUp = false; - } - if (action == MotionEvent.ACTION_MOVE) { - if(Config.mouseMode == Config.MouseMode.External) { - //Log.d("SDL", "onTouch Absolute Move by=" + action + ", X,Y=" + (x) + "," + (y) + " P=" + p); - LimboActivity.vmexecutor.onLimboMouse(0, MotionEvent.ACTION_MOVE,0, x , y ); - }else { - //Log.d("SDL", "onTouch Relative Moving by=" + action + ", X,Y=" + (x - -// old_x) + "," + (y - old_y) + " P=" + p); - LimboActivity.vmexecutor.onLimboMouse(0, MotionEvent.ACTION_MOVE,1, (x - old_x) * sensitivity_mult, (y - old_y) * sensitivity_mult); - } - - } - // save current - old_x = x; - old_y = y; - - } - else if (event.getAction() == event.ACTION_UP ) { - //Log.d("SDL", "onTouch Up: " + sdlMouseButton); - //XXX: it seems that the Button state is not available when Button up so - // we should release all mouse buttons to be safe since we don't know which one fired the event - if(sdlMouseButton == Config.SDL_MOUSE_MIDDLE - ||sdlMouseButton == Config.SDL_MOUSE_RIGHT - ) { - LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_UP, relative, x, y); - } else if (sdlMouseButton != 0) { - LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_UP, relative, x, y); - } else { // if we don't have inforamtion about which button we can make some guesses - - //Or only the last one pressed - if (lastMouseButtonDown > 0) { - if(lastMouseButtonDown == Config.SDL_MOUSE_MIDDLE - ||lastMouseButtonDown == Config.SDL_MOUSE_RIGHT - ) { - LimboActivity.vmexecutor.onLimboMouse(lastMouseButtonDown, MotionEvent.ACTION_UP, relative,x, y); - }else - LimboActivity.vmexecutor.onLimboMouse(lastMouseButtonDown, MotionEvent.ACTION_UP, relative, x, y); - } else { - //ALl buttons - if (Config.mouseMode == Config.MouseMode.Trackpad) { - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1, 0, 0); - } else if (Config.mouseMode == Config.MouseMode.External) { - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 0, x, y); - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_UP, 0, x, y); - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_UP, 0, x, y); - } - } - } - lastMouseButtonDown = -1; - mouseUp = true; - } - else if (event.getAction() == event.ACTION_DOWN - && Config.mouseMode == Config.MouseMode.External - ) { - - //XXX: Some touch events for touchscreen mode are primary so we force left mouse button - if(sdlMouseButton == 0 && MotionEvent.TOOL_TYPE_FINGER == event.getToolType(0)) { - sdlMouseButton = Config.SDL_MOUSE_LEFT; - } - - LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_DOWN, relative, x, y); - lastMouseButtonDown = sdlMouseButton; - } - return true; - } - - public boolean onTouch(View v, MotionEvent event) { - boolean res = false; - if(Config.mouseMode == Config.MouseMode.External){ - res = onTouchProcess(v,event); - res = onTouchEventProcess(event); - } - return res; - } - - public boolean onTouchEvent(MotionEvent event) { - return false; - } - - public boolean onTouchEventProcess(MotionEvent event) { - // Log.v("onTouchEvent", - // "Action=" + event.getAction() + ", X,Y=" + event.getX() + "," - // + event.getY() + " P=" + event.getPressure()); - // MK - if (event.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - if (!firstTouch) { - firstTouch = true; - } - if (event.getPointerCount() > 1) { - - // XXX: Limbo Legacy enable Right Click with 2 finger touch - // Log.v("Right Click", - // "Action=" + event.getAction() + ", X,Y=" + event.getX() - // + "," + event.getY() + " P=" + event.getPressure()); - // rightClick(event); - return true; - } else - return gestureDetector.onTouchEvent(event); - } - } - - public AudioManager am; - protected int maxVolume; - - protected void setupVolume() { - if (am == null) { - am = (AudioManager) mSingleton.getSystemService(Context.AUDIO_SERVICE); - maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); - } - } - - public void setVolume(int volume) { - if(am!=null) - am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0); - } - - protected int getCurrentVolume() { - int volumeTmp = 0; - if(am!=null) - volumeTmp = am.getStreamVolume(AudioManager.STREAM_MUSIC); - return volumeTmp; - } - - - //XXX: We want to suspend only when app is calling onPause() - @Override - public void onWindowFocusChanged(boolean hasFocus) { - - } - - public boolean rightClick(final MotionEvent e, final int i) { - Thread t = new Thread(new Runnable() { - public void run() { - Log.d("SDL", "Mouse Right Click"); - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_DOWN, 1, -1, -1); - try { - Thread.sleep(100); - } catch (InterruptedException ex) { + private void sendKeyAsync(final KeyEvent event, final int keyCode, final int action, + final boolean down) { + new Thread(new Runnable() { + @Override + public void run() { + synchronized (sendKeyLock) { + long now = System.currentTimeMillis(); + if (!handleMissingKeys(keyCode, action)) { + if (down) { + sendNativeKey(event, keyCode, true); + } else { + sendNativeKey(event, keyCode, false); + } + } + } + } + }).start(); + } + + // Touch events + public boolean onTouchProcess(View v, MotionEvent event) { + sendMouseActionAsync(v, event, event.getAction()); + return true; + } + + final Object sendMouseButtonLock = new Object(); + final Object sendMouseMoveLock = new Object(); + + public void sendMouseActionAsync(View v, final MotionEvent event, final int action) { + new Thread(new Runnable() { + @Override + public void run() { + + float x = event.getX(0); + float y = event.getY(0); + float p = event.getPressure(0); + + if (action == MotionEvent.ACTION_MOVE) { + synchronized (sendMouseMoveLock) { + if (mouseUp) { + old_x = x; + old_y = y; + mouseUp = false; + } + if (action == MotionEvent.ACTION_MOVE) { + if (Config.mouseMode == Config.MouseMode.External) { + //Log.d("SDL", "onTouch absolute delta =" + action + ", X,Y=" + (x) + "," + (y) + " P=" + p); + LimboActivity.vmexecutor.onLimboMouse(0, MotionEvent.ACTION_MOVE, 0, x, y); + } else { + //Log.d("SDL", "onTouch relative delta =" + action + ", X,Y=" + (x-old_x) + "," + (y - old_y) + " P=" + p); + LimboActivity.vmexecutor.onLimboMouse(0, MotionEvent.ACTION_MOVE, 1, (x - old_x) * sensitivity_mult, (y - old_y) * sensitivity_mult); + } + } + // save current + old_x = x; + old_y = y; + } + } + + processMouseButton(event, action, x, y); + } + }).start(); + } + + private void processMouseButton(MotionEvent event, int action, float x, float y) { + synchronized (sendMouseButtonLock) { + int relative = Config.mouseMode == Config.MouseMode.External ? 0 : 1; + int sdlMouseButton = 0; + if (event.getButtonState() == MotionEvent.BUTTON_PRIMARY) + sdlMouseButton = Config.SDL_MOUSE_LEFT; + else if (event.getButtonState() == MotionEvent.BUTTON_SECONDARY) + sdlMouseButton = Config.SDL_MOUSE_RIGHT; + else if (event.getButtonState() == MotionEvent.BUTTON_TERTIARY) + sdlMouseButton = Config.SDL_MOUSE_MIDDLE; + + if (action == MotionEvent.ACTION_UP) { + + delay(mouseButtonDelay); + //Log.d("SDL", "onTouch Up: " + sdlMouseButton); + //XXX: it seems that the Button state is not available when Button up so + // we should release all mouse buttons to be safe since we don't know which one fired the event + if (sdlMouseButton == Config.SDL_MOUSE_MIDDLE + || sdlMouseButton == Config.SDL_MOUSE_RIGHT + ) { + LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_UP, relative, x, y); + } else if (sdlMouseButton != 0) { + LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_UP, relative, x, y); + } else { // if we don't have inforamtion about which button we can make some guesses + + //Or only the last one pressed + if (lastMouseButtonDown > 0) { + if (lastMouseButtonDown == Config.SDL_MOUSE_MIDDLE + || lastMouseButtonDown == Config.SDL_MOUSE_RIGHT + ) { + LimboActivity.vmexecutor.onLimboMouse(lastMouseButtonDown, MotionEvent.ACTION_UP, relative, x, y); + } else + LimboActivity.vmexecutor.onLimboMouse(lastMouseButtonDown, MotionEvent.ACTION_UP, relative, x, y); + } else { + //ALl buttons + if (Config.mouseMode == Config.MouseMode.Trackpad) { + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1, 0, 0); + } else if (Config.mouseMode == Config.MouseMode.External) { + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 0, x, y); + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_UP, 0, x, y); + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_UP, 0, x, y); + } + } + } + lastMouseButtonDown = -1; + mouseUp = true; + + } else if (event.getAction() == MotionEvent.ACTION_DOWN && Config.mouseMode == Config.MouseMode.External) { + + //XXX: Some touch events for touchscreen mode are primary so we force left mouse button + if (sdlMouseButton == 0 && MotionEvent.TOOL_TYPE_FINGER == event.getToolType(0)) { + sdlMouseButton = Config.SDL_MOUSE_LEFT; + } + + LimboActivity.vmexecutor.onLimboMouse(sdlMouseButton, MotionEvent.ACTION_DOWN, relative, x, y); + lastMouseButtonDown = sdlMouseButton; + } + } + } + + public boolean onTouch(View v, MotionEvent event) { + boolean res = false; + if (Config.mouseMode == Config.MouseMode.External) { + res = onTouchProcess(v, event); + res = onTouchEventProcess(event); + } + return res; + } + + public boolean onTouchEvent(MotionEvent event) { + return false; + } + + public boolean onTouchEventProcess(MotionEvent event) { + // Log.v("onTouchEvent", + // "Action=" + event.getAction() + ", X,Y=" + event.getX() + "," + // + event.getY() + " P=" + event.getPressure()); + // MK + if (event.getAction() == MotionEvent.ACTION_CANCEL) + return true; + + if (!firstTouch) { + firstTouch = true; + } + if (event.getPointerCount() > 1) { + + // XXX: Limbo Legacy enable Right Click with 2 finger touch + // Log.v("Right Click", + // "Action=" + event.getAction() + ", X,Y=" + event.getX() + // + "," + event.getY() + " P=" + event.getPressure()); + // rightClick(event); + return true; + } else + return gestureDetector.onTouchEvent(event); + } + } + + public AudioManager am; + protected int maxVolume; + + protected void setupVolume() { + if (am == null) { + am = (AudioManager) mSingleton.getSystemService(Context.AUDIO_SERVICE); + maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + } + } + + public void setVolume(int volume) { + if (am != null) + am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0); + } + + protected int getCurrentVolume() { + int volumeTmp = 0; + if (am != null) + volumeTmp = am.getStreamVolume(AudioManager.STREAM_MUSIC); + return volumeTmp; + } + + + //XXX: We want to suspend only when app is calling onPause() + @Override + public void onWindowFocusChanged(boolean hasFocus) { + + } + + public boolean rightClick(final MotionEvent e, final int i) { + Thread t = new Thread(new Runnable() { + public void run() { + Log.d("SDL", "Mouse Right Click"); + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_DOWN, 1, -1, -1); + try { + Thread.sleep(100); + } catch (InterruptedException ex) { // Log.v("SDLSurface", "Interrupted: " + ex); - } - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_UP, 1, -1, -1); - } - }); - t.start(); - return true; - - } - - public boolean middleClick(final MotionEvent e, final int i) { - Thread t = new Thread(new Runnable() { - public void run() { + } + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_RIGHT, MotionEvent.ACTION_UP, 1, -1, -1); + } + }); + t.start(); + return true; + + } + + public boolean middleClick(final MotionEvent e, final int i) { + Thread t = new Thread(new Runnable() { + public void run() { Log.d("SDL", "Mouse Middle Click"); - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_DOWN, 1,-1, -1); - try { - Thread.sleep(100); - } catch (InterruptedException ex) { + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_DOWN, 1, -1, -1); + try { + Thread.sleep(100); + } catch (InterruptedException ex) { // Log.v("SDLSurface", "Interrupted: " + ex); - } - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_UP, 1,-1, -1); - } - }); - t.start(); - return true; - - } - - private void doubleClick(final MotionEvent event, final int pointer_id) { - - Thread t = new Thread(new Runnable() { - public void run() { - //Log.d("SDL", "Mouse Double Click"); - for (int i = 0; i < 2; i++) { - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_DOWN, 1, 0, 0); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - // Log.v("doubletap", "Could not sleep"); - } - LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1,0, 0); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - // Log.v("doubletap", "Could not sleep"); - } - } - } - }); - t.start(); - } - - - int lastMouseButtonDown = -1; - public float old_x = 0; - public float old_y = 0; - private boolean mouseUp = true; - private float sensitivity_mult = (float) 1.0; - private boolean firstTouch = false; - - - - private class GestureListener extends GestureDetector.SimpleOnGestureListener { - - @Override - public boolean onDown(MotionEvent event) { - // Log.v("onDown", "Action=" + event.getAction() + ", X,Y=" + event.getX() - // + "," + event.getY() + " P=" + event.getPressure()); - return true; - } - - @Override - public void onLongPress(MotionEvent event) { - // Log.d("SDL", "Long Press Action=" + event.getAction() + ", X,Y=" - // + event.getX() + "," + event.getY() + " P=" - // + event.getPressure()); - if(Config.mouseMode == Config.MouseMode.External) - return; - - if(Config.enableDragOnLongPress) - dragPointer(event); - } - - public boolean onSingleTapConfirmed(MotionEvent event) { - float x1 = event.getX(); - float y1 = event.getY(); - - if(Config.mouseMode == Config.MouseMode.External) - return true; + } + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_MIDDLE, MotionEvent.ACTION_UP, 1, -1, -1); + } + }); + t.start(); + return true; + + } + + private void doubleClick(final MotionEvent event, final int pointer_id) { + + Thread t = new Thread(new Runnable() { + public void run() { + //Log.d("SDL", "Mouse Double Click"); + for (int i = 0; i < 2; i++) { + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_DOWN, 1, 0, 0); + try { + Thread.sleep(100); + } catch (InterruptedException ex) { + // Log.v("doubletap", "Could not sleep"); + } + LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_UP, 1, 0, 0); + try { + Thread.sleep(100); + } catch (InterruptedException ex) { + // Log.v("doubletap", "Could not sleep"); + } + } + } + }); + t.start(); + } + + + int lastMouseButtonDown = -1; + public float old_x = 0; + public float old_y = 0; + private boolean mouseUp = true; + private float sensitivity_mult = (float) 1.0; + private boolean firstTouch = false; + + + private class GestureListener extends GestureDetector.SimpleOnGestureListener { + + @Override + public boolean onDown(MotionEvent event) { + // Log.v("onDown", "Action=" + event.getAction() + ", X,Y=" + event.getX() + // + "," + event.getY() + " P=" + event.getPressure()); + return true; + } + + @Override + public void onLongPress(MotionEvent event) { + // Log.d("SDL", "Long Press Action=" + event.getAction() + ", X,Y=" + // + event.getX() + "," + event.getY() + " P=" + // + event.getPressure()); + if (Config.mouseMode == Config.MouseMode.External) + return; + + if (Config.enableDragOnLongPress) + dragPointer(event); + } + + public boolean onSingleTapConfirmed(MotionEvent event) { + float x1 = event.getX(); + float y1 = event.getY(); + + if (Config.mouseMode == Config.MouseMode.External) + return true; // Log.d("onSingleTapConfirmed", "Tapped at: (" + x1 + "," + y1 + // ")"); - for (int i = 0; i < event.getPointerCount(); i++) { - int action = event.getAction(); - float x = event.getX(i); - float y = event.getY(i); - float p = event.getPressure(i); - - //Log.v("onSingleTapConfirmed", "Action=" + action + ", X,Y=" + x + "," + y + " P=" + p); - if (event.getAction() == event.ACTION_DOWN - && MotionEvent.TOOL_TYPE_FINGER == event.getToolType(0)) { - //Log.d("SDL", "onTouch Down: " + event.getButtonState()); - LimboSDLActivity.singleClick(event, i); - } - } - return true; - - } - - // event when double tap occurs - @Override - public boolean onDoubleTap(MotionEvent event) { + for (int i = 0; i < event.getPointerCount(); i++) { + int action = event.getAction(); + float x = event.getX(i); + float y = event.getY(i); + float p = event.getPressure(i); + + //Log.v("onSingleTapConfirmed", "Action=" + action + ", X,Y=" + x + "," + y + " P=" + p); + if (event.getAction() == event.ACTION_DOWN + && MotionEvent.TOOL_TYPE_FINGER == event.getToolType(0)) { + //Log.d("SDL", "onTouch Down: " + event.getButtonState()); + singleClick(event, i); + } + } + return true; + + } + + // event when double tap occurs + @Override + public boolean onDoubleTap(MotionEvent event) { // Log.d("onDoubleTap", "Tapped at: (" + event.getX() + "," + event.getY() + ")"); - if(Config.mouseMode == Config.MouseMode.External - //&& MotionEvent.TOOL_TYPE_MOUSE == event.getToolType(0) - ) - return true; + if (Config.mouseMode == Config.MouseMode.External + //&& MotionEvent.TOOL_TYPE_MOUSE == event.getToolType(0) + ) + return true; - if(!Config.enableDragOnLongPress) - processDoubleTap(event); + if (!Config.enableDragOnLongPress) + processDoubleTap(event); else doubleClick(event, 0); - return true; - } - } + return true; + } + } private void dragPointer(MotionEvent event) { LimboActivity.vmexecutor.onLimboMouse(Config.SDL_MOUSE_LEFT, MotionEvent.ACTION_DOWN, 1, 0, 0); - Vibrator v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); + Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (v.hasVibrator()) { - v.vibrate(100); + v.vibrate(50); } - } + } private void processDoubleTap(final MotionEvent event) { @@ -1934,89 +1911,92 @@ public void run() { if (!mouseUp) { dragPointer(event); } else { - // Log.v("onDoubleTap", "Action=" + action + ", X,Y=" + x + "," + y + " P=" + p); - doubleClick(event, 0); + // Log.v("onDoubleTap", "Action=" + action + ", X,Y=" + x + "," + y + " P=" + p); + doubleClick(event, 0); } } }); t.start(); - } + } class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener { - private LimboSDLSurface mSurface; - - @Override - public boolean onGenericMotion(View v, MotionEvent event) { - float x, y; - int action; - - switch (event.getSource()) { - case InputDevice.SOURCE_JOYSTICK: - case InputDevice.SOURCE_GAMEPAD: - case InputDevice.SOURCE_DPAD: - SDLControllerManager.handleJoystickMotionEvent(event); - return true; - - case InputDevice.SOURCE_MOUSE: - if(Config.mouseMode == Config.MouseMode.Trackpad) - break; + private LimboSDLSurface mSurface; + + @Override + public boolean onGenericMotion(View v, MotionEvent event) { + float x, y; + int action; + + switch (event.getSource()) { + case InputDevice.SOURCE_JOYSTICK: + case InputDevice.SOURCE_GAMEPAD: + case InputDevice.SOURCE_DPAD: + SDLControllerManager.handleJoystickMotionEvent(event); + return true; + + case InputDevice.SOURCE_MOUSE: + if (Config.mouseMode == Config.MouseMode.Trackpad) + break; - action = event.getActionMasked(); + action = event.getActionMasked(); // Log.d("SDL", "onGenericMotion, action = " + action + "," + event.getX() + ", " + event.getY()); - switch (action) { - case MotionEvent.ACTION_SCROLL: - x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0); - y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0); + switch (action) { + case MotionEvent.ACTION_SCROLL: + x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0); + y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0); // Log.d("SDL", "Mouse Scroll: " + x + "," + y); - LimboActivity.vmexecutor.onLimboMouse(0, action, 0, x, y); - return true; - - case MotionEvent.ACTION_HOVER_MOVE: - if(Config.processMouseHistoricalEvents) { - final int historySize = event.getHistorySize(); - for (int h = 0; h < historySize; h++) { - float ex = event.getHistoricalX(h); - float ey = event.getHistoricalY(h); - float ep = event.getHistoricalPressure(h); - processHoverMouse(ex, ey, ep, action); - } - } - - float ex = event.getX(); - float ey = event.getY(); - float ep = event.getPressure(); - processHoverMouse(ex, ey, ep, action); - return true; - - case MotionEvent.ACTION_UP: - - default: - break; - } - break; - - default: - break; - } - - // Event was not managed - return false; - } - - private void processHoverMouse(float x,float y,float p, int action) { - - + LimboActivity.vmexecutor.onLimboMouse(0, action, 0, x, y); + return true; + + case MotionEvent.ACTION_HOVER_MOVE: + if (Config.processMouseHistoricalEvents) { + final int historySize = event.getHistorySize(); + for (int h = 0; h < historySize; h++) { + float ex = event.getHistoricalX(h); + float ey = event.getHistoricalY(h); + float ep = event.getHistoricalPressure(h); + processHoverMouse(ex, ey, ep, action); + } + } + + float ex = event.getX(); + float ey = event.getY(); + float ep = event.getPressure(); + processHoverMouse(ex, ey, ep, action); + return true; + + case MotionEvent.ACTION_UP: + + default: + break; + } + break; - if(Config.mouseMode == Config.MouseMode.External) { - //Log.d("SDL", "Mouse Hover: " + x + "," + y); - LimboActivity.vmexecutor.onLimboMouse(0, action, 0, x, y); - } - } + default: + break; + } - } + // Event was not managed + return false; + } - GestureDetector gestureDetector; + private void processHoverMouse(float x, float y, float p, int action) { + if (Config.mouseMode == Config.MouseMode.External) { + //Log.d("SDL", "Mouse Hover: " + x + "," + y); + LimboActivity.vmexecutor.onLimboMouse(0, action, 0, x, y); + } + } + } + final static Object sendNativeKeyLock = new Object(); + private static void sendNativeKey(KeyEvent event, int keycode, boolean down) { + synchronized (sendNativeKeyLock) { + if (down) + SDLActivity.onNativeKeyDown(keycode); + else + SDLActivity.onNativeKeyUp(keycode); + } + } } From 152d2e2a5d16d78f9866356ea534111438f480ac Mon Sep 17 00:00:00 2001 From: limboemu Date: Sat, 4 Sep 2021 15:06:03 +0300 Subject: [PATCH 002/154] remove vnc client --- .../androidVNC/AbstractBitmapData.java | 203 -- .../androidVNC/AbstractBitmapDrawable.java | 100 - .../AbstractGestureInputHandler.java | 88 - .../androidVNC/AbstractInputHandler.java | 54 - .../android/androidVNC/AbstractScaling.java | 121 - .../android/androidVNC/BitmapImplHint.java | 7 - .../java/android/androidVNC/COLORMODEL.java | 89 - .../android/androidVNC/CapabilityInfo.java | 88 - .../android/androidVNC/CapsContainer.java | 104 - .../android/androidVNC/ColorModel256.java | 266 --- .../java/android/androidVNC/ColorModel64.java | 267 --- .../java/android/androidVNC/ColorModel8.java | 266 --- .../android/androidVNC/CompactBitmapData.java | 110 - .../android/androidVNC/ConnectionBean.java | 181 -- .../androidVNC/ConnectionSettable.java | 12 - .../src/main/java/android/androidVNC/DH.java | 183 -- .../androidVNC/DPadMouseKeyHandler.java | 117 - .../java/android/androidVNC/DesCipher.java | 539 ----- .../androidVNC/FitToScreenScaling.java | 57 - .../androidVNC/FullBufferBitmapData.java | 221 -- .../java/android/androidVNC/InStream.java | 155 -- .../android/androidVNC/LargeBitmapData.java | 319 --- .../java/android/androidVNC/MemInStream.java | 33 - .../java/android/androidVNC/MetaKeyBase.java | 50 - .../java/android/androidVNC/MetaKeyBean.java | 267 --- .../java/android/androidVNC/MetaList.java | 77 - .../java/android/androidVNC/MouseMover.java | 54 - .../android/androidVNC/OneToOneScaling.java | 57 - .../main/java/android/androidVNC/Panner.java | 104 - .../android/androidVNC/RepeaterDialog.java | 59 - .../java/android/androidVNC/RfbProto.java | 1416 ----------- .../main/java/android/androidVNC/Utils.java | 75 - .../java/android/androidVNC/VncCanvas.java | 2083 ----------------- .../android/androidVNC/VncCanvasActivity.java | 1854 --------------- .../java/android/androidVNC/VncConstants.java | 8 - .../java/android/androidVNC/ZlibInStream.java | 112 - .../java/android/androidVNC/ZoomScaling.java | 187 -- .../java/android/androidVNC/androidVNC.java | 306 --- .../android/bc/BCActivityManagerDefault.java | 21 - .../android/bc/BCActivityManagerV5.java | 21 - .../com/antlersoft/android/bc/BCFactory.java | 191 -- .../android/bc/BCHapticDefault.java | 33 - .../antlersoft/android/bc/BCMotionEvent4.java | 24 - .../antlersoft/android/bc/BCMotionEvent5.java | 22 - .../android/bc/BCStorageContext7.java | 31 - .../android/bc/BCStorageContext8.java | 24 - .../android/bc/IBCActivityManager.java | 13 - .../com/antlersoft/android/bc/IBCHaptic.java | 20 - .../antlersoft/android/bc/IBCMotionEvent.java | 24 - .../android/bc/IBCStorageContext.java | 26 - .../android/drawing/OverlappingCopy.java | 136 -- .../antlersoft/android/drawing/RectList.java | 550 ----- .../com/antlersoft/util/ByteBufferStack.java | 83 - .../java/com/antlersoft/util/ObjectPool.java | 58 - .../com/antlersoft/util/SafeObjectPool.java | 29 - 55 files changed, 11595 deletions(-) delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapData.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapDrawable.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/AbstractGestureInputHandler.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/AbstractInputHandler.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/AbstractScaling.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/BitmapImplHint.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/COLORMODEL.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/CapabilityInfo.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/CapsContainer.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ColorModel256.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ColorModel64.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ColorModel8.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/CompactBitmapData.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ConnectionBean.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ConnectionSettable.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/DH.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/DPadMouseKeyHandler.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/DesCipher.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/FitToScreenScaling.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/FullBufferBitmapData.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/InStream.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/LargeBitmapData.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/MemInStream.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/MetaKeyBase.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/MetaKeyBean.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/MetaList.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/MouseMover.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/OneToOneScaling.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/Panner.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/RepeaterDialog.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/RfbProto.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/Utils.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/VncCanvas.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/VncCanvasActivity.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/VncConstants.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ZlibInStream.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/ZoomScaling.java delete mode 100644 limbo-android-lib/src/main/java/android/androidVNC/androidVNC.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerDefault.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerV5.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCFactory.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCHapticDefault.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent4.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent5.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext7.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext8.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCActivityManager.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCHaptic.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCMotionEvent.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCStorageContext.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/drawing/OverlappingCopy.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/android/drawing/RectList.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/util/ByteBufferStack.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/util/ObjectPool.java delete mode 100644 limbo-android-lib/src/main/java/com/antlersoft/util/SafeObjectPool.java diff --git a/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapData.java b/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapData.java deleted file mode 100644 index d18f6345c..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapData.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import java.io.IOException; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; -import android.widget.ImageView; - -/** - * Abstract interface between the VncCanvas and the bitmap and pixel data - * buffers that actually contain the data. This allows for implementations that - * use smaller bitmaps or buffers to save memory. - * - * @author Michael A. MacDonald - * - */ -abstract class AbstractBitmapData { - int framebufferwidth; - int framebufferheight; - int bitmapwidth; - int bitmapheight; - RfbProto rfb; - Bitmap mbitmap; - int bitmapPixels[]; - Canvas memGraphics; - boolean waitingForInput; - VncCanvas vncCanvas; - private AbstractBitmapDrawable drawable; - - AbstractBitmapData(RfbProto p, VncCanvas c) { - rfb = p; - vncCanvas = c; - framebufferwidth = rfb.framebufferWidth; - framebufferheight = rfb.framebufferHeight; - } - - synchronized void doneWaiting() { - waitingForInput = false; - } - - final void invalidateMousePosition() { - if (vncCanvas.connection.getUseLocalCursor()) { - if (drawable == null) - drawable = createDrawable(); - drawable.setCursorRect(vncCanvas.mouseX, vncCanvas.mouseY); - vncCanvas.invalidate(drawable.cursorRect); - } - } - - /** - * - * @return The smallest scale supported by the implementation; the scale at - * which the bitmap would be smaller than the screen - */ - float getMinimumScale() { - double scale = 0.75; - int displayWidth = vncCanvas.getWidth(); - int displayHeight = vncCanvas.getHeight(); - for (; scale >= 0; scale -= 0.25) { - if (scale * bitmapwidth < displayWidth - || scale * bitmapheight < displayHeight) - break; - } - return (float) (scale + 0.25); - } - - /** - * Send a request through the protocol to get the data for the currently - * held bitmap - * - * @param incremental - * True if we want incremental update; false for full update - */ - abstract void writeFullUpdateRequest(boolean incremental) - throws IOException; - - /** - * Determine if a rectangle in full-frame coordinates can be drawn in the - * existing buffer - * - * @param x - * Top left x - * @param y - * Top left y - * @param w - * width (pixels) - * @param h - * height (pixels) - * @return True if entire rectangle fits into current screen buffer, false - * otherwise - */ - abstract boolean validDraw(int x, int y, int w, int h); - - /** - * Return an offset in the bitmapPixels array of a point in full-frame - * coordinates - * - * @param x - * @param y - * @return Offset in bitmapPixels array of color data for that point - */ - abstract int offset(int x, int y); - - /** - * Update pixels in the bitmap with data from the bitmapPixels array, - * positioned in full-frame coordinates - * - * @param x - * Top left x - * @param y - * Top left y - * @param w - * width (pixels) - * @param h - * height (pixels) - */ - abstract void updateBitmap(int x, int y, int w, int h); - - /** - * Create drawable appropriate for this data - * - * @return drawable - */ - abstract AbstractBitmapDrawable createDrawable(); - - /** - * Call in UI thread; tell ImageView we've changed - * - * @param v - * ImageView displaying bitmap data - */ - void updateView(ImageView v) { - if (drawable == null) - drawable = createDrawable(); - v.setImageDrawable(drawable); - v.invalidate(); - } - - /** - * Copy a rectangle from one part of the bitmap to another - * - * @param src - * Rectangle in full-frame coordinates to be copied - * @param dest - * Destination rectangle in full-frame coordinates - * @param paint - * Paint specifier - */ - abstract void copyRect(Rect src, Rect dest, Paint paint); - - /** - * Draw a rectangle in the bitmap with coordinates given in full frame - * - * @param x - * Top left x - * @param y - * Top left y - * @param w - * width (pixels) - * @param h - * height (pixels) - * @param paint - * How to draw - */ - abstract void drawRect(int x, int y, int w, int h, Paint paint); - - /** - * Scroll position has changed. - *

- * This method is called in the UI thread-- it updates internal status, but - * does not change the bitmap data or send a network request until - * syncScroll is called - * - * @param newx - * Position of left edge of visible part in full-frame - * coordinates - * @param newy - * Position of top edge of visible part in full-frame coordinates - */ - abstract void scrollChanged(int newx, int newy); - - /** - * Sync scroll -- called from network thread; copies scroll changes from UI - * to network state - */ - abstract void syncScroll(); - - /** - * Release resources - */ - void dispose() { - if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) - if (mbitmap != null) - mbitmap.recycle(); - memGraphics = null; - bitmapPixels = null; - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapDrawable.java b/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapDrawable.java deleted file mode 100644 index a311cce8a..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/AbstractBitmapDrawable.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.PixelFormat; -import android.graphics.Rect; -import android.graphics.drawable.DrawableContainer; - -/** - * @author Michael A. MacDonald - * - */ -public class AbstractBitmapDrawable extends DrawableContainer { - Rect cursorRect; - Rect clipRect; - - AbstractBitmapData data; - - static final Paint _defaultPaint; - static final Paint _whitePaint; - static final Paint _blackPaint; - - static { - _defaultPaint = new Paint(); - _whitePaint = new Paint(); - _whitePaint.setColor(0xffffffff); - _blackPaint = new Paint(); - _blackPaint.setColor(0xff000000); - } - - AbstractBitmapDrawable(AbstractBitmapData data) - { - this.data = data; - cursorRect = new Rect(); - clipRect = new Rect(); - } - - void draw(Canvas canvas, int xoff, int yoff) - { - canvas.drawBitmap(data.mbitmap, xoff, yoff, _defaultPaint); - if(data.vncCanvas.connection.getUseLocalCursor()) - { - setCursorRect(data.vncCanvas.mouseX, data.vncCanvas.mouseY); - clipRect.set(cursorRect); - if (canvas.clipRect(cursorRect)) - { - drawCursor(canvas); - } - } - } - - void drawCursor(Canvas canvas) - { - canvas.drawRect(cursorRect,_whitePaint); - canvas.drawRect((float)cursorRect.left + 1, (float)cursorRect.top + 1, (float)cursorRect.right - 1, (float)cursorRect.bottom - 1, _blackPaint); - } - - void setCursorRect(int mouseX, int mouseY) - { - cursorRect.left = mouseX - 2; - cursorRect.right = cursorRect.left + 4; - cursorRect.top = mouseY - 2; - cursorRect.bottom = cursorRect.top + 4; - } - - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#getIntrinsicHeight() - */ - @Override - public int getIntrinsicHeight() { - return data.framebufferheight; - } - - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#getIntrinsicWidth() - */ - @Override - public int getIntrinsicWidth() { - return data.framebufferwidth; - } - - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#getOpacity() - */ - @Override - public int getOpacity() { - return PixelFormat.OPAQUE; - } - - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#isStateful() - */ - @Override - public boolean isStateful() { - return false; - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/AbstractGestureInputHandler.java b/limbo-android-lib/src/main/java/android/androidVNC/AbstractGestureInputHandler.java deleted file mode 100644 index 8ed2e70e9..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/AbstractGestureInputHandler.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import android.view.GestureDetector; -import android.view.MotionEvent; - -/** - * An AbstractInputHandler that uses GestureDetector to detect standard gestures in touch events - * - * @author Michael A. MacDonald - */ -abstract class AbstractGestureInputHandler extends GestureDetector.SimpleOnGestureListener implements AbstractInputHandler { - protected GestureDetector gestures = new GestureDetector(this); - private VncCanvasActivity activity; - - float xInitialFocus; - float yInitialFocus; - boolean inScaling; - - private static final String TAG = "AbstractGestureInputHandler"; - - AbstractGestureInputHandler(VncCanvasActivity c) - { - activity = c; - gestures.setOnDoubleTapListener(this); - } - - @Override - public boolean onTouchEvent(MotionEvent evt) { - //MK - if(evt.getAction()==MotionEvent.ACTION_CANCEL) - return true; - - return gestures.onTouchEvent(evt); - } - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.OnScaleGestureListener#onScale(com.antlersoft.android.bc.IBCScaleGestureDetector) - */ -// @Override -// public boolean onScale(IBCScaleGestureDetector detector) { -// boolean consumed = true; -// //if (detector.) -// //Log.i(TAG,"Focus("+detector.getFocusX()+","+detector.getFocusY()+") scaleFactor = "+detector.getScaleFactor()); -// // Calculate focus shift -// float fx = detector.getFocusX(); -// float fy = detector.getFocusY(); -// double xfs = fx - xInitialFocus; -// double yfs = fy - yInitialFocus; -// double fs = Math.sqrt(xfs * xfs + yfs * yfs); -// if (Math.abs(1.0 - detector.getScaleFactor())<0.02) -// consumed = false; -// if (fs * 2< Math.abs(detector.getCurrentSpan() - detector.getPreviousSpan())) -// { -// inScaling = true; -// if (consumed) -// { -// //Log.i(TAG,"Adjust scaling "+detector.getScaleFactor()); -// if (activity.vncCanvas != null && activity.vncCanvas.scaling != null) -// activity.vncCanvas.scaling.adjust(activity, detector.getScaleFactor(), fx, fy); -// } -// } -// return consumed; -// } -// -// /* (non-Javadoc) -// * @see com.antlersoft.android.bc.OnScaleGestureListener#onScaleBegin(com.antlersoft.android.bc.IBCScaleGestureDetector) -// */ -// @Override -// public boolean onScaleBegin(IBCScaleGestureDetector detector) { -// xInitialFocus = detector.getFocusX(); -// yInitialFocus = detector.getFocusY(); -// inScaling = false; -// //Log.i(TAG,"scale begin ("+xInitialFocus+","+yInitialFocus+")"); -// return true; -// } -// -// /* (non-Javadoc) -// * @see com.antlersoft.android.bc.OnScaleGestureListener#onScaleEnd(com.antlersoft.android.bc.IBCScaleGestureDetector) -// */ -// @Override -// public void onScaleEnd(IBCScaleGestureDetector detector) { -// //Log.i(TAG,"scale end"); -// inScaling = false; -// } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/AbstractInputHandler.java b/limbo-android-lib/src/main/java/android/androidVNC/AbstractInputHandler.java deleted file mode 100644 index 47e49dc35..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/AbstractInputHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import android.view.KeyEvent; -import android.view.MotionEvent; - -/** - * The VncCanvasActivity has several different ways of handling input from the touchscreen, - * keyboard, buttons and trackball. These will be represented by different implementations - * of this interface. Putting the different modes in different classes - * will keep the logic clean. The relevant Activity callbacks in VncCanvasActivity - * are forwarded to methods in AbstractInputHandler. - *

- * It is expected that the implementations will be contained within - * VncCanvasActivity, so they can do things like super.VncCanvasActivity.onXXX to invoke - * default behavior. - * @author Michael A. MacDonald - * - */ -public interface AbstractInputHandler { - /** - * Note: Menu key code is handled before this is called - * @see android.app.Activity#onKeyDown(int keyCode, KeyEvent evt) - */ - boolean onKeyDown(int keyCode, KeyEvent evt); - /** - * Note: Menu key code is handled before this is called - * @see android.app.Activity#onKeyUp(int keyCode, KeyEvent evt) - */ - boolean onKeyUp(int keyCode, KeyEvent evt); - /* (non-Javadoc) - * @see android.app.Activity#onTrackballEvent(android.view.MotionEvent) - */ - boolean onTrackballEvent( MotionEvent evt); - /* (non-Javadoc) - * @see android.app.Activity#onTrackballEvent(android.view.MotionEvent) - */ - boolean onTouchEvent( MotionEvent evt); - - /** - * Return a user-friendly description for this mode; it will be displayed in a toaster - * when changing modes. - * @return - */ - public CharSequence getHandlerDescription(); - - /** - * Return an internal name for this handler; this name will be stable across language - * and version changes - */ - String getName(); -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/AbstractScaling.java b/limbo-android-lib/src/main/java/android/androidVNC/AbstractScaling.java deleted file mode 100644 index 3b4c3ed4b..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/AbstractScaling.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import com.limbo.emu.lib.R; - -import android.widget.ImageView; -/** - * @author Michael A. MacDonald - * - * A scaling mode for the VncCanvas; based on ImageView.ScaleType - */ -public abstract class AbstractScaling { - private static final int scaleModeIds[] = { R.id.itemFitToScreen, R.id.itemOneToOne, R.id.itemZoomable }; - - private static AbstractScaling[] scalings; - - public static AbstractScaling getById(int id) - { - if ( scalings==null) - { - scalings=new AbstractScaling[scaleModeIds.length]; - } - for ( int i=0; i(64, (float)0.25); - orderedList = new Vector(32, 8); - } - - public void add(CapabilityInfo capinfo) { - Integer key = new Integer(capinfo.getCode()); - infoMap.put(key, capinfo); - } - - public void add(int code, String vendor, String name, String desc) { - Integer key = new Integer(code); - infoMap.put(key, new CapabilityInfo(code, vendor, name, desc)); - } - - public boolean isKnown(int code) { - return infoMap.containsKey(new Integer(code)); - } - - public CapabilityInfo getInfo(int code) { - return (CapabilityInfo)infoMap.get(new Integer(code)); - } - - public String getDescription(int code) { - CapabilityInfo capinfo = (CapabilityInfo)infoMap.get(new Integer(code)); - if (capinfo == null) - return null; - - return capinfo.getDescription(); - } - - public boolean enable(CapabilityInfo other) { - Integer key = new Integer(other.getCode()); - CapabilityInfo capinfo = (CapabilityInfo)infoMap.get(key); - if (capinfo == null) - return false; - - boolean enabled = capinfo.enableIfEquals(other); - if (enabled) - orderedList.addElement(key); - - return enabled; - } - - public boolean isEnabled(int code) { - CapabilityInfo capinfo = (CapabilityInfo)infoMap.get(new Integer(code)); - if (capinfo == null) - return false; - - return capinfo.isEnabled(); - } - - public int numEnabled() { - return orderedList.size(); - } - - public int getByOrder(int idx) { - int code; - try { - code = ((Integer)orderedList.elementAt(idx)).intValue(); - } catch (ArrayIndexOutOfBoundsException e) { - code = 0; - } - return code; - } - - // Protected data - - protected Hashtable infoMap; - protected Vector orderedList; -} - diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel256.java b/limbo-android-lib/src/main/java/android/androidVNC/ColorModel256.java deleted file mode 100644 index f759fe34a..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel256.java +++ /dev/null @@ -1,266 +0,0 @@ -package android.androidVNC; - -public class ColorModel256 { - - public final static int [] colors; - - static { - colors = new int[256]; - colors[0]=0xff000000; - colors[1]=0xff240000; - colors[2]=0xff490000; - colors[3]=0xff6d0000; - colors[4]=0xff920000; - colors[5]=0xffb60000; - colors[6]=0xffdb0000; - colors[7]=0xffff0000; - colors[8]=0xff002400; - colors[9]=0xff242400; - colors[10]=0xff492400; - colors[11]=0xff6d2400; - colors[12]=0xff922400; - colors[13]=0xffb62400; - colors[14]=0xffdb2400; - colors[15]=0xffff2400; - colors[16]=0xff004900; - colors[17]=0xff244900; - colors[18]=0xff494900; - colors[19]=0xff6d4900; - colors[20]=0xff924900; - colors[21]=0xffb64900; - colors[22]=0xffdb4900; - colors[23]=0xffff4900; - colors[24]=0xff006d00; - colors[25]=0xff246d00; - colors[26]=0xff496d00; - colors[27]=0xff6d6d00; - colors[28]=0xff926d00; - colors[29]=0xffb66d00; - colors[30]=0xffdb6d00; - colors[31]=0xffff6d00; - colors[32]=0xff009200; - colors[33]=0xff249200; - colors[34]=0xff499200; - colors[35]=0xff6d9200; - colors[36]=0xff929200; - colors[37]=0xffb69200; - colors[38]=0xffdb9200; - colors[39]=0xffff9200; - colors[40]=0xff00b600; - colors[41]=0xff24b600; - colors[42]=0xff49b600; - colors[43]=0xff6db600; - colors[44]=0xff92b600; - colors[45]=0xffb6b600; - colors[46]=0xffdbb600; - colors[47]=0xffffb600; - colors[48]=0xff00db00; - colors[49]=0xff24db00; - colors[50]=0xff49db00; - colors[51]=0xff6ddb00; - colors[52]=0xff92db00; - colors[53]=0xffb6db00; - colors[54]=0xffdbdb00; - colors[55]=0xffffdb00; - colors[56]=0xff00ff00; - colors[57]=0xff24ff00; - colors[58]=0xff49ff00; - colors[59]=0xff6dff00; - colors[60]=0xff92ff00; - colors[61]=0xffb6ff00; - colors[62]=0xffdbff00; - colors[63]=0xffffff00; - colors[64]=0xff000055; - colors[65]=0xff240055; - colors[66]=0xff490055; - colors[67]=0xff6d0055; - colors[68]=0xff920055; - colors[69]=0xffb60055; - colors[70]=0xffdb0055; - colors[71]=0xffff0055; - colors[72]=0xff002455; - colors[73]=0xff242455; - colors[74]=0xff492455; - colors[75]=0xff6d2455; - colors[76]=0xff922455; - colors[77]=0xffb62455; - colors[78]=0xffdb2455; - colors[79]=0xffff2455; - colors[80]=0xff004955; - colors[81]=0xff244955; - colors[82]=0xff494955; - colors[83]=0xff6d4955; - colors[84]=0xff924955; - colors[85]=0xffb64955; - colors[86]=0xffdb4955; - colors[87]=0xffff4955; - colors[88]=0xff006d55; - colors[89]=0xff246d55; - colors[90]=0xff496d55; - colors[91]=0xff6d6d55; - colors[92]=0xff926d55; - colors[93]=0xffb66d55; - colors[94]=0xffdb6d55; - colors[95]=0xffff6d55; - colors[96]=0xff009255; - colors[97]=0xff249255; - colors[98]=0xff499255; - colors[99]=0xff6d9255; - colors[100]=0xff929255; - colors[101]=0xffb69255; - colors[102]=0xffdb9255; - colors[103]=0xffff9255; - colors[104]=0xff00b655; - colors[105]=0xff24b655; - colors[106]=0xff49b655; - colors[107]=0xff6db655; - colors[108]=0xff92b655; - colors[109]=0xffb6b655; - colors[110]=0xffdbb655; - colors[111]=0xffffb655; - colors[112]=0xff00db55; - colors[113]=0xff24db55; - colors[114]=0xff49db55; - colors[115]=0xff6ddb55; - colors[116]=0xff92db55; - colors[117]=0xffb6db55; - colors[118]=0xffdbdb55; - colors[119]=0xffffdb55; - colors[120]=0xff00ff55; - colors[121]=0xff24ff55; - colors[122]=0xff49ff55; - colors[123]=0xff6dff55; - colors[124]=0xff92ff55; - colors[125]=0xffb6ff55; - colors[126]=0xffdbff55; - colors[127]=0xffffff55; - colors[128]=0xff0000aa; - colors[129]=0xff2400aa; - colors[130]=0xff4900aa; - colors[131]=0xff6d00aa; - colors[132]=0xff9200aa; - colors[133]=0xffb600aa; - colors[134]=0xffdb00aa; - colors[135]=0xffff00aa; - colors[136]=0xff0024aa; - colors[137]=0xff2424aa; - colors[138]=0xff4924aa; - colors[139]=0xff6d24aa; - colors[140]=0xff9224aa; - colors[141]=0xffb624aa; - colors[142]=0xffdb24aa; - colors[143]=0xffff24aa; - colors[144]=0xff0049aa; - colors[145]=0xff2449aa; - colors[146]=0xff4949aa; - colors[147]=0xff6d49aa; - colors[148]=0xff9249aa; - colors[149]=0xffb649aa; - colors[150]=0xffdb49aa; - colors[151]=0xffff49aa; - colors[152]=0xff006daa; - colors[153]=0xff246daa; - colors[154]=0xff496daa; - colors[155]=0xff6d6daa; - colors[156]=0xff926daa; - colors[157]=0xffb66daa; - colors[158]=0xffdb6daa; - colors[159]=0xffff6daa; - colors[160]=0xff0092aa; - colors[161]=0xff2492aa; - colors[162]=0xff4992aa; - colors[163]=0xff6d92aa; - colors[164]=0xff9292aa; - colors[165]=0xffb692aa; - colors[166]=0xffdb92aa; - colors[167]=0xffff92aa; - colors[168]=0xff00b6aa; - colors[169]=0xff24b6aa; - colors[170]=0xff49b6aa; - colors[171]=0xff6db6aa; - colors[172]=0xff92b6aa; - colors[173]=0xffb6b6aa; - colors[174]=0xffdbb6aa; - colors[175]=0xffffb6aa; - colors[176]=0xff00dbaa; - colors[177]=0xff24dbaa; - colors[178]=0xff49dbaa; - colors[179]=0xff6ddbaa; - colors[180]=0xff92dbaa; - colors[181]=0xffb6dbaa; - colors[182]=0xffdbdbaa; - colors[183]=0xffffdbaa; - colors[184]=0xff00ffaa; - colors[185]=0xff24ffaa; - colors[186]=0xff49ffaa; - colors[187]=0xff6dffaa; - colors[188]=0xff92ffaa; - colors[189]=0xffb6ffaa; - colors[190]=0xffdbffaa; - colors[191]=0xffffffaa; - colors[192]=0xff0000ff; - colors[193]=0xff2400ff; - colors[194]=0xff4900ff; - colors[195]=0xff6d00ff; - colors[196]=0xff9200ff; - colors[197]=0xffb600ff; - colors[198]=0xffdb00ff; - colors[199]=0xffff00ff; - colors[200]=0xff0024ff; - colors[201]=0xff2424ff; - colors[202]=0xff4924ff; - colors[203]=0xff6d24ff; - colors[204]=0xff9224ff; - colors[205]=0xffb624ff; - colors[206]=0xffdb24ff; - colors[207]=0xffff24ff; - colors[208]=0xff0049ff; - colors[209]=0xff2449ff; - colors[210]=0xff4949ff; - colors[211]=0xff6d49ff; - colors[212]=0xff9249ff; - colors[213]=0xffb649ff; - colors[214]=0xffdb49ff; - colors[215]=0xffff49ff; - colors[216]=0xff006dff; - colors[217]=0xff246dff; - colors[218]=0xff496dff; - colors[219]=0xff6d6dff; - colors[220]=0xff926dff; - colors[221]=0xffb66dff; - colors[222]=0xffdb6dff; - colors[223]=0xffff6dff; - colors[224]=0xff0092ff; - colors[225]=0xff2492ff; - colors[226]=0xff4992ff; - colors[227]=0xff6d92ff; - colors[228]=0xff9292ff; - colors[229]=0xffb692ff; - colors[230]=0xffdb92ff; - colors[231]=0xffff92ff; - colors[232]=0xff00b6ff; - colors[233]=0xff24b6ff; - colors[234]=0xff49b6ff; - colors[235]=0xff6db6ff; - colors[236]=0xff92b6ff; - colors[237]=0xffb6b6ff; - colors[238]=0xffdbb6ff; - colors[239]=0xffffb6ff; - colors[240]=0xff00dbff; - colors[241]=0xff24dbff; - colors[242]=0xff49dbff; - colors[243]=0xff6ddbff; - colors[244]=0xff92dbff; - colors[245]=0xffb6dbff; - colors[246]=0xffdbdbff; - colors[247]=0xffffdbff; - colors[248]=0xff00ffff; - colors[249]=0xff24ffff; - colors[250]=0xff49ffff; - colors[251]=0xff6dffff; - colors[252]=0xff92ffff; - colors[253]=0xffb6ffff; - colors[254]=0xffdbffff; - colors[255]=0xffffffff; - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel64.java b/limbo-android-lib/src/main/java/android/androidVNC/ColorModel64.java deleted file mode 100644 index 7236da828..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel64.java +++ /dev/null @@ -1,267 +0,0 @@ -package android.androidVNC; - -public class ColorModel64 { - - public final static int [] colors; - - static { - colors = new int[256]; - colors[0]=0xff000000; - colors[1]=0xff000055; - colors[2]=0xff0000aa; - colors[3]=0xff0000ff; - colors[4]=0xff005500; - colors[5]=0xff005555; - colors[6]=0xff0055aa; - colors[7]=0xff0055ff; - colors[8]=0xff00aa00; - colors[9]=0xff00aa55; - colors[10]=0xff00aaaa; - colors[11]=0xff00aaff; - colors[12]=0xff00ff00; - colors[13]=0xff00ff55; - colors[14]=0xff00ffaa; - colors[15]=0xff00ffff; - colors[16]=0xff550000; - colors[17]=0xff550055; - colors[18]=0xff5500aa; - colors[19]=0xff5500ff; - colors[20]=0xff555500; - colors[21]=0xff555555; - colors[22]=0xff5555aa; - colors[23]=0xff5555ff; - colors[24]=0xff55aa00; - colors[25]=0xff55aa55; - colors[26]=0xff55aaaa; - colors[27]=0xff55aaff; - colors[28]=0xff55ff00; - colors[29]=0xff55ff55; - colors[30]=0xff55ffaa; - colors[31]=0xff55ffff; - colors[32]=0xffaa0000; - colors[33]=0xffaa0055; - colors[34]=0xffaa00aa; - colors[35]=0xffaa00ff; - colors[36]=0xffaa5500; - colors[37]=0xffaa5555; - colors[38]=0xffaa55aa; - colors[39]=0xffaa55ff; - colors[40]=0xffaaaa00; - colors[41]=0xffaaaa55; - colors[42]=0xffaaaaaa; - colors[43]=0xffaaaaff; - colors[44]=0xffaaff00; - colors[45]=0xffaaff55; - colors[46]=0xffaaffaa; - colors[47]=0xffaaffff; - colors[48]=0xffff0000; - colors[49]=0xffff0055; - colors[50]=0xffff00aa; - colors[51]=0xffff00ff; - colors[52]=0xffff5500; - colors[53]=0xffff5555; - colors[54]=0xffff55aa; - colors[55]=0xffff55ff; - colors[56]=0xffffaa00; - colors[57]=0xffffaa55; - colors[58]=0xffffaaaa; - colors[59]=0xffffaaff; - colors[60]=0xffffff00; - colors[61]=0xffffff55; - colors[62]=0xffffffaa; - colors[63]=0xffffffff; - colors[64]=0xff000000; - colors[65]=0xff000055; - colors[66]=0xff0000aa; - colors[67]=0xff0000ff; - colors[68]=0xff005500; - colors[69]=0xff005555; - colors[70]=0xff0055aa; - colors[71]=0xff0055ff; - colors[72]=0xff00aa00; - colors[73]=0xff00aa55; - colors[74]=0xff00aaaa; - colors[75]=0xff00aaff; - colors[76]=0xff00ff00; - colors[77]=0xff00ff55; - colors[78]=0xff00ffaa; - colors[79]=0xff00ffff; - colors[80]=0xff550000; - colors[81]=0xff550055; - colors[82]=0xff5500aa; - colors[83]=0xff5500ff; - colors[84]=0xff555500; - colors[85]=0xff555555; - colors[86]=0xff5555aa; - colors[87]=0xff5555ff; - colors[88]=0xff55aa00; - colors[89]=0xff55aa55; - colors[90]=0xff55aaaa; - colors[91]=0xff55aaff; - colors[92]=0xff55ff00; - colors[93]=0xff55ff55; - colors[94]=0xff55ffaa; - colors[95]=0xff55ffff; - colors[96]=0xffaa0000; - colors[97]=0xffaa0055; - colors[98]=0xffaa00aa; - colors[99]=0xffaa00ff; - colors[100]=0xffaa5500; - colors[101]=0xffaa5555; - colors[102]=0xffaa55aa; - colors[103]=0xffaa55ff; - colors[104]=0xffaaaa00; - colors[105]=0xffaaaa55; - colors[106]=0xffaaaaaa; - colors[107]=0xffaaaaff; - colors[108]=0xffaaff00; - colors[109]=0xffaaff55; - colors[110]=0xffaaffaa; - colors[111]=0xffaaffff; - colors[112]=0xffff0000; - colors[113]=0xffff0055; - colors[114]=0xffff00aa; - colors[115]=0xffff00ff; - colors[116]=0xffff5500; - colors[117]=0xffff5555; - colors[118]=0xffff55aa; - colors[119]=0xffff55ff; - colors[120]=0xffffaa00; - colors[121]=0xffffaa55; - colors[122]=0xffffaaaa; - colors[123]=0xffffaaff; - colors[124]=0xffffff00; - colors[125]=0xffffff55; - colors[126]=0xffffffaa; - colors[127]=0xffffffff; - colors[128]=0xff000000; - colors[129]=0xff000055; - colors[130]=0xff0000aa; - colors[131]=0xff0000ff; - colors[132]=0xff005500; - colors[133]=0xff005555; - colors[134]=0xff0055aa; - colors[135]=0xff0055ff; - colors[136]=0xff00aa00; - colors[137]=0xff00aa55; - colors[138]=0xff00aaaa; - colors[139]=0xff00aaff; - colors[140]=0xff00ff00; - colors[141]=0xff00ff55; - colors[142]=0xff00ffaa; - colors[143]=0xff00ffff; - colors[144]=0xff550000; - colors[145]=0xff550055; - colors[146]=0xff5500aa; - colors[147]=0xff5500ff; - colors[148]=0xff555500; - colors[149]=0xff555555; - colors[150]=0xff5555aa; - colors[151]=0xff5555ff; - colors[152]=0xff55aa00; - colors[153]=0xff55aa55; - colors[154]=0xff55aaaa; - colors[155]=0xff55aaff; - colors[156]=0xff55ff00; - colors[157]=0xff55ff55; - colors[158]=0xff55ffaa; - colors[159]=0xff55ffff; - colors[160]=0xffaa0000; - colors[161]=0xffaa0055; - colors[162]=0xffaa00aa; - colors[163]=0xffaa00ff; - colors[164]=0xffaa5500; - colors[165]=0xffaa5555; - colors[166]=0xffaa55aa; - colors[167]=0xffaa55ff; - colors[168]=0xffaaaa00; - colors[169]=0xffaaaa55; - colors[170]=0xffaaaaaa; - colors[171]=0xffaaaaff; - colors[172]=0xffaaff00; - colors[173]=0xffaaff55; - colors[174]=0xffaaffaa; - colors[175]=0xffaaffff; - colors[176]=0xffff0000; - colors[177]=0xffff0055; - colors[178]=0xffff00aa; - colors[179]=0xffff00ff; - colors[180]=0xffff5500; - colors[181]=0xffff5555; - colors[182]=0xffff55aa; - colors[183]=0xffff55ff; - colors[184]=0xffffaa00; - colors[185]=0xffffaa55; - colors[186]=0xffffaaaa; - colors[187]=0xffffaaff; - colors[188]=0xffffff00; - colors[189]=0xffffff55; - colors[190]=0xffffffaa; - colors[191]=0xffffffff; - colors[192]=0xff000000; - colors[193]=0xff000055; - colors[194]=0xff0000aa; - colors[195]=0xff0000ff; - colors[196]=0xff005500; - colors[197]=0xff005555; - colors[198]=0xff0055aa; - colors[199]=0xff0055ff; - colors[200]=0xff00aa00; - colors[201]=0xff00aa55; - colors[202]=0xff00aaaa; - colors[203]=0xff00aaff; - colors[204]=0xff00ff00; - colors[205]=0xff00ff55; - colors[206]=0xff00ffaa; - colors[207]=0xff00ffff; - colors[208]=0xff550000; - colors[209]=0xff550055; - colors[210]=0xff5500aa; - colors[211]=0xff5500ff; - colors[212]=0xff555500; - colors[213]=0xff555555; - colors[214]=0xff5555aa; - colors[215]=0xff5555ff; - colors[216]=0xff55aa00; - colors[217]=0xff55aa55; - colors[218]=0xff55aaaa; - colors[219]=0xff55aaff; - colors[220]=0xff55ff00; - colors[221]=0xff55ff55; - colors[222]=0xff55ffaa; - colors[223]=0xff55ffff; - colors[224]=0xffaa0000; - colors[225]=0xffaa0055; - colors[226]=0xffaa00aa; - colors[227]=0xffaa00ff; - colors[228]=0xffaa5500; - colors[229]=0xffaa5555; - colors[230]=0xffaa55aa; - colors[231]=0xffaa55ff; - colors[232]=0xffaaaa00; - colors[233]=0xffaaaa55; - colors[234]=0xffaaaaaa; - colors[235]=0xffaaaaff; - colors[236]=0xffaaff00; - colors[237]=0xffaaff55; - colors[238]=0xffaaffaa; - colors[239]=0xffaaffff; - colors[240]=0xffff0000; - colors[241]=0xffff0055; - colors[242]=0xffff00aa; - colors[243]=0xffff00ff; - colors[244]=0xffff5500; - colors[245]=0xffff5555; - colors[246]=0xffff55aa; - colors[247]=0xffff55ff; - colors[248]=0xffffaa00; - colors[249]=0xffffaa55; - colors[250]=0xffffaaaa; - colors[251]=0xffffaaff; - colors[252]=0xffffff00; - colors[253]=0xffffff55; - colors[254]=0xffffffaa; - colors[255]=0xffffffff; - - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel8.java b/limbo-android-lib/src/main/java/android/androidVNC/ColorModel8.java deleted file mode 100644 index 0c1b2de7b..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ColorModel8.java +++ /dev/null @@ -1,266 +0,0 @@ -package android.androidVNC; - -public class ColorModel8 { - - public final static int [] colors; - - static { - colors = new int[256]; - colors[0]=0xff000000; - colors[1]=0xff0000ff; - colors[2]=0xff00ff00; - colors[3]=0xff00ffff; - colors[4]=0xffff0000; - colors[5]=0xffff00ff; - colors[6]=0xffffff00; - colors[7]=0xffffffff; - colors[8]=0xff000000; - colors[9]=0xff0000ff; - colors[10]=0xff00ff00; - colors[11]=0xff00ffff; - colors[12]=0xffff0000; - colors[13]=0xffff00ff; - colors[14]=0xffffff00; - colors[15]=0xffffffff; - colors[16]=0xff000000; - colors[17]=0xff0000ff; - colors[18]=0xff00ff00; - colors[19]=0xff00ffff; - colors[20]=0xffff0000; - colors[21]=0xffff00ff; - colors[22]=0xffffff00; - colors[23]=0xffffffff; - colors[24]=0xff000000; - colors[25]=0xff0000ff; - colors[26]=0xff00ff00; - colors[27]=0xff00ffff; - colors[28]=0xffff0000; - colors[29]=0xffff00ff; - colors[30]=0xffffff00; - colors[31]=0xffffffff; - colors[32]=0xff000000; - colors[33]=0xff0000ff; - colors[34]=0xff00ff00; - colors[35]=0xff00ffff; - colors[36]=0xffff0000; - colors[37]=0xffff00ff; - colors[38]=0xffffff00; - colors[39]=0xffffffff; - colors[40]=0xff000000; - colors[41]=0xff0000ff; - colors[42]=0xff00ff00; - colors[43]=0xff00ffff; - colors[44]=0xffff0000; - colors[45]=0xffff00ff; - colors[46]=0xffffff00; - colors[47]=0xffffffff; - colors[48]=0xff000000; - colors[49]=0xff0000ff; - colors[50]=0xff00ff00; - colors[51]=0xff00ffff; - colors[52]=0xffff0000; - colors[53]=0xffff00ff; - colors[54]=0xffffff00; - colors[55]=0xffffffff; - colors[56]=0xff000000; - colors[57]=0xff0000ff; - colors[58]=0xff00ff00; - colors[59]=0xff00ffff; - colors[60]=0xffff0000; - colors[61]=0xffff00ff; - colors[62]=0xffffff00; - colors[63]=0xffffffff; - colors[64]=0xff000000; - colors[65]=0xff0000ff; - colors[66]=0xff00ff00; - colors[67]=0xff00ffff; - colors[68]=0xffff0000; - colors[69]=0xffff00ff; - colors[70]=0xffffff00; - colors[71]=0xffffffff; - colors[72]=0xff000000; - colors[73]=0xff0000ff; - colors[74]=0xff00ff00; - colors[75]=0xff00ffff; - colors[76]=0xffff0000; - colors[77]=0xffff00ff; - colors[78]=0xffffff00; - colors[79]=0xffffffff; - colors[80]=0xff000000; - colors[81]=0xff0000ff; - colors[82]=0xff00ff00; - colors[83]=0xff00ffff; - colors[84]=0xffff0000; - colors[85]=0xffff00ff; - colors[86]=0xffffff00; - colors[87]=0xffffffff; - colors[88]=0xff000000; - colors[89]=0xff0000ff; - colors[90]=0xff00ff00; - colors[91]=0xff00ffff; - colors[92]=0xffff0000; - colors[93]=0xffff00ff; - colors[94]=0xffffff00; - colors[95]=0xffffffff; - colors[96]=0xff000000; - colors[97]=0xff0000ff; - colors[98]=0xff00ff00; - colors[99]=0xff00ffff; - colors[100]=0xffff0000; - colors[101]=0xffff00ff; - colors[102]=0xffffff00; - colors[103]=0xffffffff; - colors[104]=0xff000000; - colors[105]=0xff0000ff; - colors[106]=0xff00ff00; - colors[107]=0xff00ffff; - colors[108]=0xffff0000; - colors[109]=0xffff00ff; - colors[110]=0xffffff00; - colors[111]=0xffffffff; - colors[112]=0xff000000; - colors[113]=0xff0000ff; - colors[114]=0xff00ff00; - colors[115]=0xff00ffff; - colors[116]=0xffff0000; - colors[117]=0xffff00ff; - colors[118]=0xffffff00; - colors[119]=0xffffffff; - colors[120]=0xff000000; - colors[121]=0xff0000ff; - colors[122]=0xff00ff00; - colors[123]=0xff00ffff; - colors[124]=0xffff0000; - colors[125]=0xffff00ff; - colors[126]=0xffffff00; - colors[127]=0xffffffff; - colors[128]=0xff000000; - colors[129]=0xff0000ff; - colors[130]=0xff00ff00; - colors[131]=0xff00ffff; - colors[132]=0xffff0000; - colors[133]=0xffff00ff; - colors[134]=0xffffff00; - colors[135]=0xffffffff; - colors[136]=0xff000000; - colors[137]=0xff0000ff; - colors[138]=0xff00ff00; - colors[139]=0xff00ffff; - colors[140]=0xffff0000; - colors[141]=0xffff00ff; - colors[142]=0xffffff00; - colors[143]=0xffffffff; - colors[144]=0xff000000; - colors[145]=0xff0000ff; - colors[146]=0xff00ff00; - colors[147]=0xff00ffff; - colors[148]=0xffff0000; - colors[149]=0xffff00ff; - colors[150]=0xffffff00; - colors[151]=0xffffffff; - colors[152]=0xff000000; - colors[153]=0xff0000ff; - colors[154]=0xff00ff00; - colors[155]=0xff00ffff; - colors[156]=0xffff0000; - colors[157]=0xffff00ff; - colors[158]=0xffffff00; - colors[159]=0xffffffff; - colors[160]=0xff000000; - colors[161]=0xff0000ff; - colors[162]=0xff00ff00; - colors[163]=0xff00ffff; - colors[164]=0xffff0000; - colors[165]=0xffff00ff; - colors[166]=0xffffff00; - colors[167]=0xffffffff; - colors[168]=0xff000000; - colors[169]=0xff0000ff; - colors[170]=0xff00ff00; - colors[171]=0xff00ffff; - colors[172]=0xffff0000; - colors[173]=0xffff00ff; - colors[174]=0xffffff00; - colors[175]=0xffffffff; - colors[176]=0xff000000; - colors[177]=0xff0000ff; - colors[178]=0xff00ff00; - colors[179]=0xff00ffff; - colors[180]=0xffff0000; - colors[181]=0xffff00ff; - colors[182]=0xffffff00; - colors[183]=0xffffffff; - colors[184]=0xff000000; - colors[185]=0xff0000ff; - colors[186]=0xff00ff00; - colors[187]=0xff00ffff; - colors[188]=0xffff0000; - colors[189]=0xffff00ff; - colors[190]=0xffffff00; - colors[191]=0xffffffff; - colors[192]=0xff000000; - colors[193]=0xff0000ff; - colors[194]=0xff00ff00; - colors[195]=0xff00ffff; - colors[196]=0xffff0000; - colors[197]=0xffff00ff; - colors[198]=0xffffff00; - colors[199]=0xffffffff; - colors[200]=0xff000000; - colors[201]=0xff0000ff; - colors[202]=0xff00ff00; - colors[203]=0xff00ffff; - colors[204]=0xffff0000; - colors[205]=0xffff00ff; - colors[206]=0xffffff00; - colors[207]=0xffffffff; - colors[208]=0xff000000; - colors[209]=0xff0000ff; - colors[210]=0xff00ff00; - colors[211]=0xff00ffff; - colors[212]=0xffff0000; - colors[213]=0xffff00ff; - colors[214]=0xffffff00; - colors[215]=0xffffffff; - colors[216]=0xff000000; - colors[217]=0xff0000ff; - colors[218]=0xff00ff00; - colors[219]=0xff00ffff; - colors[220]=0xffff0000; - colors[221]=0xffff00ff; - colors[222]=0xffffff00; - colors[223]=0xffffffff; - colors[224]=0xff000000; - colors[225]=0xff0000ff; - colors[226]=0xff00ff00; - colors[227]=0xff00ffff; - colors[228]=0xffff0000; - colors[229]=0xffff00ff; - colors[230]=0xffffff00; - colors[231]=0xffffffff; - colors[232]=0xff000000; - colors[233]=0xff0000ff; - colors[234]=0xff00ff00; - colors[235]=0xff00ffff; - colors[236]=0xffff0000; - colors[237]=0xffff00ff; - colors[238]=0xffffff00; - colors[239]=0xffffffff; - colors[240]=0xff000000; - colors[241]=0xff0000ff; - colors[242]=0xff00ff00; - colors[243]=0xff00ffff; - colors[244]=0xffff0000; - colors[245]=0xffff00ff; - colors[246]=0xffffff00; - colors[247]=0xffffffff; - colors[248]=0xff000000; - colors[249]=0xff0000ff; - colors[250]=0xff00ff00; - colors[251]=0xff00ffff; - colors[252]=0xffff0000; - colors[253]=0xffff00ff; - colors[254]=0xffffff00; - colors[255]=0xffffffff; - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/CompactBitmapData.java b/limbo-android-lib/src/main/java/android/androidVNC/CompactBitmapData.java deleted file mode 100644 index 25e53c48e..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/CompactBitmapData.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import java.io.IOException; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; - -import com.max2idea.android.limbo.main.Config; - -/** - * @author Michael A. MacDonald - * - */ -class CompactBitmapData extends AbstractBitmapData { - - class CompactBitmapDrawable extends AbstractBitmapDrawable - { - CompactBitmapDrawable() - { - super(CompactBitmapData.this); - } - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#draw(android.graphics.Canvas) - */ - @Override - public void draw(Canvas canvas) { - draw(canvas, 0, 0); - } - } - - CompactBitmapData(RfbProto rfb, VncCanvas c) - { - super(rfb,c); - bitmapwidth=framebufferwidth; - bitmapheight=framebufferheight; - - mbitmap = Bitmap.createBitmap(rfb.framebufferWidth, rfb.framebufferHeight, Config.bitmapConfig); - memGraphics = new Canvas(mbitmap); - bitmapPixels = new int[rfb.framebufferWidth * rfb.framebufferHeight]; - } - - @Override - void writeFullUpdateRequest(boolean incremental) throws IOException { - rfb.writeFramebufferUpdateRequest(0, 0, framebufferwidth, framebufferheight, incremental); - } - - @Override - boolean validDraw(int x, int y, int w, int h) { - return true; - } - - @Override - int offset(int x, int y) { - return y * bitmapwidth + x; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#createDrawable() - */ - @Override - AbstractBitmapDrawable createDrawable() { - return new CompactBitmapDrawable(); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#updateBitmap(int, int, int, int) - */ - @Override - void updateBitmap(int x, int y, int w, int h) { - mbitmap.setPixels(bitmapPixels, offset(x,y), bitmapwidth, x, y, w, h); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#copyRect(android.graphics.Rect, android.graphics.Rect, android.graphics.Paint) - */ - @Override - void copyRect(Rect src, Rect dest, Paint paint) { - memGraphics.drawBitmap(mbitmap, src, dest, paint); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#drawRect(int, int, int, int, android.graphics.Paint) - */ - @Override - void drawRect(int x, int y, int w, int h, Paint paint) { - memGraphics.drawRect(x, y, x + w, y + h, paint); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#scrollChanged(int, int) - */ - @Override - void scrollChanged(int newx, int newy) { - // Don't need to do anything here - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#syncScroll() - */ - @Override - void syncScroll() { - // Don't need anything here either - - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ConnectionBean.java b/limbo-android-lib/src/main/java/android/androidVNC/ConnectionBean.java deleted file mode 100644 index c62b54485..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ConnectionBean.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import com.max2idea.android.limbo.main.Config; - -import android.widget.ImageView.ScaleType; - -/** - * @author Michael A. MacDonald - * - */ -public class ConnectionBean { - - private String address = "localhost"; - private String password = ""; - private int port = 5901; - private String colorModel = COLORMODEL.C64.nameString(); - private String InputMode = VncCanvasActivity.TOUCH_ZOOM_MODE; - private String scaleMode = ""; - private String nickname = "limbo"; - private long forceFull = 0; - private boolean useLocalCursor = false; - private boolean followMouse = true; - private String userName; - private long id = 0; - - public ConnectionBean() { - setAddress(Config.defaultVNCHost); - setUserName(Config.defaultVNCUsername); - setPassword(Config.defaultVNCPasswd); - setPort(Config.defaultVNCPort + 5900); - setColorModel(Config.defaultVNCColorMode); - if (Config.enable_qemu_fullScreen) - setScaleMode(Config.defaultFullscreenScaleMode); - else - setScaleMode(Config.defaultScaleModeCenter); - setInputMode(Config.defaultInputMode); - } - - private void setUserName(String string) { - - this.userName = string; - - } - - public void setInputMode(String touchZoomMode) { - - this.InputMode = touchZoomMode; - - } - - void setPort(int i) { - - this.port = i; - } - - void setColorModel(String nameString) { - - this.colorModel = nameString; - - } - - void setAddress(String string) { - - this.address = string; - } - - void setPassword(String string) { - - this.password = string; - } - - public long get_Id() { - - return 0; - } - - ScaleType getScaleMode() { - return ScaleType.valueOf(getScaleModeAsString()); - } - - private String getScaleModeAsString() { - - return scaleMode; - } - - void setScaleMode(ScaleType value) { - setScaleModeAsString(value.toString()); - } - - private void setScaleModeAsString(String string) { - - this.scaleMode = string; - - } - - public String getAddress() { - - return this.address; - } - - public void setNickname(String address2) { - - this.nickname = address2; - } - - public int getPort() { - - return port; - } - - public String getInputMode() { - - return this.InputMode; - } - - public String getPassword() { - - return this.password; - } - - public long getForceFull() { - - return this.forceFull; - } - - public boolean getUseLocalCursor() { - - return this.useLocalCursor; - } - - public String getNickname() { - - return nickname; - } - - public String getColorModel() { - - return this.colorModel; - } - - public void setForceFull(long l) { - - this.forceFull = l; - } - - public void setUseLocalCursor(boolean checked) { - - this.setUseLocalCursor(checked); - } - - public void setFollowMouse(boolean b) { - - this.followMouse = b; - - } - - public boolean getFollowMouse() { - - return this.followMouse; - } - - public String getUserName() { - - return userName; - } - - public void setConnectionId(long get_Id) { - - this.id = get_Id; - - } - - public boolean getFollowPan() { - - return false; - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ConnectionSettable.java b/limbo-android-lib/src/main/java/android/androidVNC/ConnectionSettable.java deleted file mode 100644 index dfc64cc02..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ConnectionSettable.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * - */ -package android.androidVNC; - -/** - * @author mike - * - */ -interface ConnectionSettable { - void setConnection(ConnectionBean connection); -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/DH.java b/limbo-android-lib/src/main/java/android/androidVNC/DH.java deleted file mode 100644 index aaf6b1099..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/DH.java +++ /dev/null @@ -1,183 +0,0 @@ -package android.androidVNC; -// CRYPTO LIBRARY FOR EXCHANGING KEYS -// USING THE DIFFIE-HELLMAN KEY EXCHANGE PROTOCOL - -// The diffie-hellman can be used to securely exchange keys -// between parties, where a third party eavesdropper given -// the values being transmitted cannot determine the key. - -// Implemented by Lee Griffiths, Jan 2004. -// This software is freeware, you may use it to your discretion, -// however by doing so you take full responsibility for any damage -// it may cause. - -// Hope you find it useful, even if you just use some of the functions -// out of it like the prime number generator and the XtoYmodN function. - -// It would be great if you could send me emails to: lee.griffiths@first4internet.co.uk -// with any suggestions, comments, or questions! - -// Enjoy. - -// Adopted to ms-logon for ultravnc and ported to Java by marscha, 2006. - -//import java.lang.Math; - -public class DH { - - public DH() { - maxNum = (((long) 1) << DH_MAX_BITS) - 1; - } - - public DH(long generator, long modulus) throws Exception { - maxNum = (((long) 1) << DH_MAX_BITS) - 1; - if (generator >= maxNum || modulus >= maxNum) - throw new Exception("Modulus or generator too large."); - gen = generator; - mod = modulus; - } - - private long rng(long limit) { - return (long) (java.lang.Math.random() * limit); - } - - //Performs the miller-rabin primality test on a guessed prime n. - //trials is the number of attempts to verify this, because the function - //is not 100% accurate it may be a composite. However setting the trial - //value to around 5 should guarantee success even with very large primes - private boolean millerRabin (long n, int trials) { - long a = 0; - - for (int i = 0; i < trials; i++) { - a = rng(n - 3) + 2;// gets random value in [2..n-1] - if (XpowYmodN(a, n - 1, n) != 1) return false; //n composite, return false - } - return true; // n probably prime - } - - //Generates a large prime number by - //choosing a randomly large integer, and ensuring the value is odd - //then uses the miller-rabin primality test on it to see if it is prime - //if not the value gets increased until it is prime - private long generatePrime() { - long prime = 0; - - do { - long start = rng(maxNum); - prime = tryToGeneratePrime(start); - } while (prime == 0); - return prime; - } - - private long tryToGeneratePrime(long prime) { - //ensure it is an odd number - if ((prime & 1) == 0) - prime += 1; - - long cnt = 0; - while (!millerRabin(prime, 25) && (cnt++ < DH_RANGE) && prime < maxNum) { - prime += 2; - if ((prime % 3) == 0) prime += 2; - } - return (cnt >= DH_RANGE || prime >= maxNum) ? 0 : prime; - } - - //Raises X to the power Y in modulus N - //the values of X, Y, and N can be massive, and this can be - //achieved by first calculating X to the power of 2 then - //using power chaining over modulus N - private long XpowYmodN(long x, long y, long N) { - long result = 1; - final long oneShift63 = ((long) 1) << 63; - - for (int i = 0; i < 64; y <<= 1, i++){ - result = result * result % N; - if ((y & oneShift63) != 0) - result = result * x % N; - } - return result; - } - - public void createKeys() { - gen = generatePrime(); - mod = generatePrime(); - - if (gen > mod) { - long swap = gen; - gen = mod; - mod = swap; - } - } - - public long createInterKey() { - priv = rng(maxNum); - return pub = XpowYmodN(gen,priv,mod); - } - - public long createEncryptionKey(long interKey) throws Exception { - if (interKey >= maxNum){ - throw new Exception("interKey too large"); - } - return key = XpowYmodN(interKey,priv,mod); - } - - - public long getValue(int flags) { - switch (flags) { - case DH_MOD: - return mod; - case DH_GEN: - return gen; - case DH_PRIV: - return priv; - case DH_PUB: - return pub; - case DH_KEY: - return key; - default: - return (long) 0; - } - } - - public int bits(long number){ - for (int i = 0; i < 64; i++){ - number /= 2; - if (number < 2) return i; - } - return 0; - } - - public static byte[] longToBytes(long number) { - byte[] bytes = new byte[8]; - for (int i = 0; i < 8; i++) { - bytes[i] = (byte) (0xff & (number >> (8 * (7 - i)))); - } - return bytes; - } - - public static long bytesToLong(byte[] bytes) { - long result = 0; - for (int i = 0; i < 8; i++) { - result <<= 8; - result += (byte) bytes[i]; - } - return result; - } - - private long gen; - private long mod; - private long priv; - private long pub; - private long key; - private long maxNum; - - private static final int DH_MAX_BITS = 31; - private static final int DH_RANGE = 100; - - private static final int DH_MOD = 1; - private static final int DH_GEN = 2; - private static final int DH_PRIV = 3; - private static final int DH_PUB = 4; - private static final int DH_KEY = 5; - -} \ No newline at end of file diff --git a/limbo-android-lib/src/main/java/android/androidVNC/DPadMouseKeyHandler.java b/limbo-android-lib/src/main/java/android/androidVNC/DPadMouseKeyHandler.java deleted file mode 100644 index 5f75df509..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/DPadMouseKeyHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package android.androidVNC; - -import android.graphics.PointF; -import android.os.Handler; -import android.view.KeyEvent; -import android.view.MotionEvent; - -/** - * Input handlers delegate to this class to handle keystrokes; this detects keystrokes - * from the DPad and uses them to perform mouse actions; other keystrokes are passed to - * VncCanvasActivity.defaultKeyXXXHandler - * - * @author Michael A. MacDonald - * - */ -class DPadMouseKeyHandler { - private MouseMover mouseMover; - private boolean mouseDown; - private VncCanvasActivity activity; - private VncCanvas canvas; - private boolean isMoving; - - DPadMouseKeyHandler(VncCanvasActivity activity, Handler handler) - { - this.activity = activity; - canvas = activity.vncCanvas; - mouseMover = new MouseMover(activity, handler); - } - - public boolean onKeyDown(int keyCode, KeyEvent evt) { - int xv = 0; - int yv = 0; - boolean result = true; - switch (keyCode) { -// case KeyEvent.KEYCODE_DPAD_LEFT: -// xv = -1; -// break; -// case KeyEvent.KEYCODE_DPAD_RIGHT: -// xv = 1; -// break; -// case KeyEvent.KEYCODE_DPAD_UP: -// yv = -1; -// break; -// case KeyEvent.KEYCODE_DPAD_DOWN: -// yv = 1; -// break; -// case KeyEvent.KEYCODE_DPAD_CENTER: -// if (!mouseDown) { -// mouseDown = true; -// result = canvas.processPointerEvent(canvas.mouseX, canvas.mouseY, MotionEvent.ACTION_DOWN, evt.getMetaState(), mouseDown, canvas.cameraButtonDown); -// } -// break; - default: - result = activity.defaultKeyDownHandler(keyCode, evt); - break; - } - if ((xv != 0 || yv != 0) && !isMoving) { - final int x = xv; - final int y = yv; - isMoving = true; - mouseMover.start(x, y, new Panner.VelocityUpdater() { - - /* - * (non-Javadoc) - * - * @see android.androidVNC.Panner.VelocityUpdater#updateVelocity(android.graphics.Point, - * long) - */ - @Override - public boolean updateVelocity(PointF p, long interval) { - double scale = (1.2 * (double) interval / 50.0); - if (Math.abs(p.x) < 500) - p.x += (int) (scale * x); - if (Math.abs(p.y) < 500) - p.y += (int) (scale * y); - return true; - } - - }); - canvas.processPointerEvent(canvas.mouseX + x, canvas.mouseY + y, MotionEvent.ACTION_MOVE, evt.getMetaState(), - mouseDown, canvas.cameraButtonDown, false, false); - - } - return result; - } - - public boolean onKeyUp(int keyCode, KeyEvent evt) { - boolean result = false; - - switch (keyCode) { -// case KeyEvent.KEYCODE_DPAD_LEFT: -// case KeyEvent.KEYCODE_DPAD_RIGHT: -// case KeyEvent.KEYCODE_DPAD_UP: -// case KeyEvent.KEYCODE_DPAD_DOWN: -// mouseMover.stop(); -// isMoving = false; -// result = true; -// break; - case KeyEvent.KEYCODE_DPAD_CENTER: - if (mouseDown) { - mouseDown = false; - result = canvas.processPointerEvent(canvas.mouseX, canvas.mouseY, MotionEvent.ACTION_UP, evt.getMetaState(), - mouseDown, canvas.cameraButtonDown, false, false); - } else { - result = true; - } - break; - default: - result = activity.defaultKeyUpHandler(keyCode, evt); - break; - } - return result; - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/DesCipher.java b/limbo-android-lib/src/main/java/android/androidVNC/DesCipher.java deleted file mode 100644 index 2d7bed357..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/DesCipher.java +++ /dev/null @@ -1,539 +0,0 @@ -// -// This DES class has been extracted from package Acme.Crypto for use in VNC. -// The bytebit[] array has been reversed so that the most significant bit -// in each byte of the key is ignored, not the least significant. Also the -// unnecessary odd parity code has been removed. -// -// These changes are: -// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. -// -// This software 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. -// - -// DesCipher - the DES encryption method -// -// The meat of this code is by Dave Zimmerman , and is: -// -// Copyright (c) 1996 Widget Workshop, Inc. All Rights Reserved. -// -// Permission to use, copy, modify, and distribute this software -// and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and -// without fee is hereby granted, provided that this copyright notice is kept -// intact. -// -// WIDGET WORKSHOP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY -// OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -// PARTICULAR PURPOSE, OR NON-INFRINGEMENT. WIDGET WORKSHOP SHALL NOT BE LIABLE -// FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR -// DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. -// -// THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE -// CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE -// PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT -// NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE -// SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE -// SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE -// PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). WIDGET WORKSHOP -// SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR -// HIGH RISK ACTIVITIES. -// -// -// The rest is: -// -// Copyright (C) 1996 by Jef Poskanzer . All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// SUCH DAMAGE. -// -// Visit the ACME Labs Java page for up-to-date versions of this and other -// fine Java utilities: http://www.acme.com/java/ - -/// The DES encryption method. -//

-// This is surprisingly fast, for pure Java. On a SPARC 20, wrapped -// in Acme.Crypto.EncryptedOutputStream or Acme.Crypto.EncryptedInputStream, -// it does around 7000 bytes/second. -//

-// Most of this code is by Dave Zimmerman , and is -// Copyright (c) 1996 Widget Workshop, Inc. See the source file for details. -//

-// Fetch the software.
-// Fetch the entire Acme package. -//

-// @see Des3Cipher -// @see EncryptedOutputStream -// @see EncryptedInputStream - -package android.androidVNC; - -//- import java.io.*; - - -public class DesCipher - { - - // Constructor, byte-array key. - public DesCipher( byte[] key ) - { - setKey( key ); - } - - // Key routines. - - private int[] encryptKeys = new int[32]; - private int[] decryptKeys = new int[32]; - - /// Set the key. - public void setKey( byte[] key ) - { - deskey( key, true, encryptKeys ); - deskey( key, false, decryptKeys ); - } - - // Turn an 8-byte key into internal keys. - private void deskey( byte[] keyBlock, boolean encrypting, int[] KnL ) - { - int i, j, l, m, n; - int[] pc1m = new int[56]; - int[] pcr = new int[56]; - int[] kn = new int[32]; - - for ( j = 0; j < 56; ++j ) - { - l = pc1[j]; - m = l & 07; - pc1m[j] = ( (keyBlock[l >>> 3] & bytebit[m]) != 0 )? 1: 0; - } - - for ( i = 0; i < 16; ++i ) - { - if ( encrypting ) - m = i << 1; - else - m = (15-i) << 1; - n = m+1; - kn[m] = kn[n] = 0; - for ( j = 0; j < 28; ++j ) - { - l = j+totrot[i]; - if ( l < 28 ) - pcr[j] = pc1m[l]; - else - pcr[j] = pc1m[l-28]; - } - for ( j=28; j < 56; ++j ) - { - l = j+totrot[i]; - if ( l < 56 ) - pcr[j] = pc1m[l]; - else - pcr[j] = pc1m[l-28]; - } - for ( j = 0; j < 24; ++j ) - { - if ( pcr[pc2[j]] != 0 ) - kn[m] |= bigbyte[j]; - if ( pcr[pc2[j+24]] != 0 ) - kn[n] |= bigbyte[j]; - } - } - cookey( kn, KnL ); - } - - private void cookey( int[] raw, int KnL[] ) - { - int raw0, raw1; - int rawi, KnLi; - int i; - - for ( i = 0, rawi = 0, KnLi = 0; i < 16; ++i ) - { - raw0 = raw[rawi++]; - raw1 = raw[rawi++]; - KnL[KnLi] = (raw0 & 0x00fc0000) << 6; - KnL[KnLi] |= (raw0 & 0x00000fc0) << 10; - KnL[KnLi] |= (raw1 & 0x00fc0000) >>> 10; - KnL[KnLi] |= (raw1 & 0x00000fc0) >>> 6; - ++KnLi; - KnL[KnLi] = (raw0 & 0x0003f000) << 12; - KnL[KnLi] |= (raw0 & 0x0000003f) << 16; - KnL[KnLi] |= (raw1 & 0x0003f000) >>> 4; - KnL[KnLi] |= (raw1 & 0x0000003f); - ++KnLi; - } - } - - - // Block encryption routines. - - private int[] tempInts = new int[2]; - - /// Encrypt a block of eight bytes. - public void encrypt( byte[] clearText, int clearOff, byte[] cipherText, int cipherOff ) - { - squashBytesToInts( clearText, clearOff, tempInts, 0, 2 ); - des( tempInts, tempInts, encryptKeys ); - spreadIntsToBytes( tempInts, 0, cipherText, cipherOff, 2 ); - } - - /// Decrypt a block of eight bytes. - public void decrypt( byte[] cipherText, int cipherOff, byte[] clearText, int clearOff ) - { - squashBytesToInts( cipherText, cipherOff, tempInts, 0, 2 ); - des( tempInts, tempInts, decryptKeys ); - spreadIntsToBytes( tempInts, 0, clearText, clearOff, 2 ); - } - - // Encrypt a text which is a multiple of 8 bytes. - public void encryptText(byte[] clearText, byte[] cipherText, byte[] key) - { - int i, j; - - for(i=0; i<8; i++) - { - clearText[i] ^= key[i]; - } - encrypt(clearText, 0, cipherText, 0); - for(i=8; i0; i-=8) - { - decrypt(cipherText, i, clearText, i); - for(j=0; j<8; j++) - { - clearText[i+j] ^= cipherText[i+j-8]; - } - } - /* i = 0 */ - decrypt(cipherText, 0, clearText, 0); - for(i=0; i<8; i++) - { - clearText[i] ^= key[i]; - } - } - - // The DES function. - private void des( int[] inInts, int[] outInts, int[] keys ) - { - int fval, work, right, leftt; - int round; - int keysi = 0; - - leftt = inInts[0]; - right = inInts[1]; - - work = ((leftt >>> 4) ^ right) & 0x0f0f0f0f; - right ^= work; - leftt ^= (work << 4); - - work = ((leftt >>> 16) ^ right) & 0x0000ffff; - right ^= work; - leftt ^= (work << 16); - - work = ((right >>> 2) ^ leftt) & 0x33333333; - leftt ^= work; - right ^= (work << 2); - - work = ((right >>> 8) ^ leftt) & 0x00ff00ff; - leftt ^= work; - right ^= (work << 8); - right = (right << 1) | ((right >>> 31) & 1); - - work = (leftt ^ right) & 0xaaaaaaaa; - leftt ^= work; - right ^= work; - leftt = (leftt << 1) | ((leftt >>> 31) & 1); - - for ( round = 0; round < 8; ++round ) - { - work = (right << 28) | (right >>> 4); - work ^= keys[keysi++]; - fval = SP7[ work & 0x0000003f ]; - fval |= SP5[(work >>> 8) & 0x0000003f ]; - fval |= SP3[(work >>> 16) & 0x0000003f ]; - fval |= SP1[(work >>> 24) & 0x0000003f ]; - work = right ^ keys[keysi++]; - fval |= SP8[ work & 0x0000003f ]; - fval |= SP6[(work >>> 8) & 0x0000003f ]; - fval |= SP4[(work >>> 16) & 0x0000003f ]; - fval |= SP2[(work >>> 24) & 0x0000003f ]; - leftt ^= fval; - work = (leftt << 28) | (leftt >>> 4); - work ^= keys[keysi++]; - fval = SP7[ work & 0x0000003f ]; - fval |= SP5[(work >>> 8) & 0x0000003f ]; - fval |= SP3[(work >>> 16) & 0x0000003f ]; - fval |= SP1[(work >>> 24) & 0x0000003f ]; - work = leftt ^ keys[keysi++]; - fval |= SP8[ work & 0x0000003f ]; - fval |= SP6[(work >>> 8) & 0x0000003f ]; - fval |= SP4[(work >>> 16) & 0x0000003f ]; - fval |= SP2[(work >>> 24) & 0x0000003f ]; - right ^= fval; - } - - right = (right << 31) | (right >>> 1); - work = (leftt ^ right) & 0xaaaaaaaa; - leftt ^= work; - right ^= work; - leftt = (leftt << 31) | (leftt >>> 1); - work = ((leftt >>> 8) ^ right) & 0x00ff00ff; - right ^= work; - leftt ^= (work << 8); - work = ((leftt >>> 2) ^ right) & 0x33333333; - right ^= work; - leftt ^= (work << 2); - work = ((right >>> 16) ^ leftt) & 0x0000ffff; - leftt ^= work; - right ^= (work << 16); - work = ((right >>> 4) ^ leftt) & 0x0f0f0f0f; - leftt ^= work; - right ^= (work << 4); - outInts[0] = right; - outInts[1] = leftt; - } - - - // Tables, permutations, S-boxes, etc. - - private static byte[] bytebit = { - (byte)0x01, (byte)0x02, (byte)0x04, (byte)0x08, - (byte)0x10, (byte)0x20, (byte)0x40, (byte)0x80 - }; - private static int[] bigbyte = { - 0x800000, 0x400000, 0x200000, 0x100000, - 0x080000, 0x040000, 0x020000, 0x010000, - 0x008000, 0x004000, 0x002000, 0x001000, - 0x000800, 0x000400, 0x000200, 0x000100, - 0x000080, 0x000040, 0x000020, 0x000010, - 0x000008, 0x000004, 0x000002, 0x000001 - }; - private static byte[] pc1 = { - (byte)56, (byte)48, (byte)40, (byte)32, (byte)24, (byte)16, (byte) 8, - (byte) 0, (byte)57, (byte)49, (byte)41, (byte)33, (byte)25, (byte)17, - (byte) 9, (byte) 1, (byte)58, (byte)50, (byte)42, (byte)34, (byte)26, - (byte)18, (byte)10, (byte) 2, (byte)59, (byte)51, (byte)43, (byte)35, - (byte)62, (byte)54, (byte)46, (byte)38, (byte)30, (byte)22, (byte)14, - (byte) 6, (byte)61, (byte)53, (byte)45, (byte)37, (byte)29, (byte)21, - (byte)13, (byte) 5, (byte)60, (byte)52, (byte)44, (byte)36, (byte)28, - (byte)20, (byte)12, (byte) 4, (byte)27, (byte)19, (byte)11, (byte)3 - }; - private static int[] totrot = { - 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 - }; - - private static byte[] pc2 = { - (byte)13, (byte)16, (byte)10, (byte)23, (byte) 0, (byte) 4, - (byte) 2, (byte)27, (byte)14, (byte) 5, (byte)20, (byte) 9, - (byte)22, (byte)18, (byte)11, (byte)3 , (byte)25, (byte) 7, - (byte)15, (byte) 6, (byte)26, (byte)19, (byte)12, (byte) 1, - (byte)40, (byte)51, (byte)30, (byte)36, (byte)46, (byte)54, - (byte)29, (byte)39, (byte)50, (byte)44, (byte)32, (byte)47, - (byte)43, (byte)48, (byte)38, (byte)55, (byte)33, (byte)52, - (byte)45, (byte)41, (byte)49, (byte)35, (byte)28, (byte)31, - }; - - private static int[] SP1 = { - 0x01010400, 0x00000000, 0x00010000, 0x01010404, - 0x01010004, 0x00010404, 0x00000004, 0x00010000, - 0x00000400, 0x01010400, 0x01010404, 0x00000400, - 0x01000404, 0x01010004, 0x01000000, 0x00000004, - 0x00000404, 0x01000400, 0x01000400, 0x00010400, - 0x00010400, 0x01010000, 0x01010000, 0x01000404, - 0x00010004, 0x01000004, 0x01000004, 0x00010004, - 0x00000000, 0x00000404, 0x00010404, 0x01000000, - 0x00010000, 0x01010404, 0x00000004, 0x01010000, - 0x01010400, 0x01000000, 0x01000000, 0x00000400, - 0x01010004, 0x00010000, 0x00010400, 0x01000004, - 0x00000400, 0x00000004, 0x01000404, 0x00010404, - 0x01010404, 0x00010004, 0x01010000, 0x01000404, - 0x01000004, 0x00000404, 0x00010404, 0x01010400, - 0x00000404, 0x01000400, 0x01000400, 0x00000000, - 0x00010004, 0x00010400, 0x00000000, 0x01010004 - }; - private static int[] SP2 = { - 0x80108020, 0x80008000, 0x00008000, 0x00108020, - 0x00100000, 0x00000020, 0x80100020, 0x80008020, - 0x80000020, 0x80108020, 0x80108000, 0x80000000, - 0x80008000, 0x00100000, 0x00000020, 0x80100020, - 0x00108000, 0x00100020, 0x80008020, 0x00000000, - 0x80000000, 0x00008000, 0x00108020, 0x80100000, - 0x00100020, 0x80000020, 0x00000000, 0x00108000, - 0x00008020, 0x80108000, 0x80100000, 0x00008020, - 0x00000000, 0x00108020, 0x80100020, 0x00100000, - 0x80008020, 0x80100000, 0x80108000, 0x00008000, - 0x80100000, 0x80008000, 0x00000020, 0x80108020, - 0x00108020, 0x00000020, 0x00008000, 0x80000000, - 0x00008020, 0x80108000, 0x00100000, 0x80000020, - 0x00100020, 0x80008020, 0x80000020, 0x00100020, - 0x00108000, 0x00000000, 0x80008000, 0x00008020, - 0x80000000, 0x80100020, 0x80108020, 0x00108000 - }; - private static int[] SP3 = { - 0x00000208, 0x08020200, 0x00000000, 0x08020008, - 0x08000200, 0x00000000, 0x00020208, 0x08000200, - 0x00020008, 0x08000008, 0x08000008, 0x00020000, - 0x08020208, 0x00020008, 0x08020000, 0x00000208, - 0x08000000, 0x00000008, 0x08020200, 0x00000200, - 0x00020200, 0x08020000, 0x08020008, 0x00020208, - 0x08000208, 0x00020200, 0x00020000, 0x08000208, - 0x00000008, 0x08020208, 0x00000200, 0x08000000, - 0x08020200, 0x08000000, 0x00020008, 0x00000208, - 0x00020000, 0x08020200, 0x08000200, 0x00000000, - 0x00000200, 0x00020008, 0x08020208, 0x08000200, - 0x08000008, 0x00000200, 0x00000000, 0x08020008, - 0x08000208, 0x00020000, 0x08000000, 0x08020208, - 0x00000008, 0x00020208, 0x00020200, 0x08000008, - 0x08020000, 0x08000208, 0x00000208, 0x08020000, - 0x00020208, 0x00000008, 0x08020008, 0x00020200 - }; - private static int[] SP4 = { - 0x00802001, 0x00002081, 0x00002081, 0x00000080, - 0x00802080, 0x00800081, 0x00800001, 0x00002001, - 0x00000000, 0x00802000, 0x00802000, 0x00802081, - 0x00000081, 0x00000000, 0x00800080, 0x00800001, - 0x00000001, 0x00002000, 0x00800000, 0x00802001, - 0x00000080, 0x00800000, 0x00002001, 0x00002080, - 0x00800081, 0x00000001, 0x00002080, 0x00800080, - 0x00002000, 0x00802080, 0x00802081, 0x00000081, - 0x00800080, 0x00800001, 0x00802000, 0x00802081, - 0x00000081, 0x00000000, 0x00000000, 0x00802000, - 0x00002080, 0x00800080, 0x00800081, 0x00000001, - 0x00802001, 0x00002081, 0x00002081, 0x00000080, - 0x00802081, 0x00000081, 0x00000001, 0x00002000, - 0x00800001, 0x00002001, 0x00802080, 0x00800081, - 0x00002001, 0x00002080, 0x00800000, 0x00802001, - 0x00000080, 0x00800000, 0x00002000, 0x00802080 - }; - private static int[] SP5 = { - 0x00000100, 0x02080100, 0x02080000, 0x42000100, - 0x00080000, 0x00000100, 0x40000000, 0x02080000, - 0x40080100, 0x00080000, 0x02000100, 0x40080100, - 0x42000100, 0x42080000, 0x00080100, 0x40000000, - 0x02000000, 0x40080000, 0x40080000, 0x00000000, - 0x40000100, 0x42080100, 0x42080100, 0x02000100, - 0x42080000, 0x40000100, 0x00000000, 0x42000000, - 0x02080100, 0x02000000, 0x42000000, 0x00080100, - 0x00080000, 0x42000100, 0x00000100, 0x02000000, - 0x40000000, 0x02080000, 0x42000100, 0x40080100, - 0x02000100, 0x40000000, 0x42080000, 0x02080100, - 0x40080100, 0x00000100, 0x02000000, 0x42080000, - 0x42080100, 0x00080100, 0x42000000, 0x42080100, - 0x02080000, 0x00000000, 0x40080000, 0x42000000, - 0x00080100, 0x02000100, 0x40000100, 0x00080000, - 0x00000000, 0x40080000, 0x02080100, 0x40000100 - }; - private static int[] SP6 = { - 0x20000010, 0x20400000, 0x00004000, 0x20404010, - 0x20400000, 0x00000010, 0x20404010, 0x00400000, - 0x20004000, 0x00404010, 0x00400000, 0x20000010, - 0x00400010, 0x20004000, 0x20000000, 0x00004010, - 0x00000000, 0x00400010, 0x20004010, 0x00004000, - 0x00404000, 0x20004010, 0x00000010, 0x20400010, - 0x20400010, 0x00000000, 0x00404010, 0x20404000, - 0x00004010, 0x00404000, 0x20404000, 0x20000000, - 0x20004000, 0x00000010, 0x20400010, 0x00404000, - 0x20404010, 0x00400000, 0x00004010, 0x20000010, - 0x00400000, 0x20004000, 0x20000000, 0x00004010, - 0x20000010, 0x20404010, 0x00404000, 0x20400000, - 0x00404010, 0x20404000, 0x00000000, 0x20400010, - 0x00000010, 0x00004000, 0x20400000, 0x00404010, - 0x00004000, 0x00400010, 0x20004010, 0x00000000, - 0x20404000, 0x20000000, 0x00400010, 0x20004010 - }; - private static int[] SP7 = { - 0x00200000, 0x04200002, 0x04000802, 0x00000000, - 0x00000800, 0x04000802, 0x00200802, 0x04200800, - 0x04200802, 0x00200000, 0x00000000, 0x04000002, - 0x00000002, 0x04000000, 0x04200002, 0x00000802, - 0x04000800, 0x00200802, 0x00200002, 0x04000800, - 0x04000002, 0x04200000, 0x04200800, 0x00200002, - 0x04200000, 0x00000800, 0x00000802, 0x04200802, - 0x00200800, 0x00000002, 0x04000000, 0x00200800, - 0x04000000, 0x00200800, 0x00200000, 0x04000802, - 0x04000802, 0x04200002, 0x04200002, 0x00000002, - 0x00200002, 0x04000000, 0x04000800, 0x00200000, - 0x04200800, 0x00000802, 0x00200802, 0x04200800, - 0x00000802, 0x04000002, 0x04200802, 0x04200000, - 0x00200800, 0x00000000, 0x00000002, 0x04200802, - 0x00000000, 0x00200802, 0x04200000, 0x00000800, - 0x04000002, 0x04000800, 0x00000800, 0x00200002 - }; - private static int[] SP8 = { - 0x10001040, 0x00001000, 0x00040000, 0x10041040, - 0x10000000, 0x10001040, 0x00000040, 0x10000000, - 0x00040040, 0x10040000, 0x10041040, 0x00041000, - 0x10041000, 0x00041040, 0x00001000, 0x00000040, - 0x10040000, 0x10000040, 0x10001000, 0x00001040, - 0x00041000, 0x00040040, 0x10040040, 0x10041000, - 0x00001040, 0x00000000, 0x00000000, 0x10040040, - 0x10000040, 0x10001000, 0x00041040, 0x00040000, - 0x00041040, 0x00040000, 0x10041000, 0x00001000, - 0x00000040, 0x10040040, 0x00001000, 0x00041040, - 0x10001000, 0x00000040, 0x10000040, 0x10040000, - 0x10040040, 0x10000000, 0x00040000, 0x10001040, - 0x00000000, 0x10041040, 0x00040040, 0x10000040, - 0x10040000, 0x10001000, 0x10001040, 0x00000000, - 0x10041040, 0x00041000, 0x00041000, 0x00001040, - 0x00001040, 0x00040040, 0x10000000, 0x10041000 - }; - - // Routines taken from other parts of the Acme utilities. - - /// Squash bytes down to ints. - public static void squashBytesToInts( byte[] inBytes, int inOff, int[] outInts, int outOff, int intLen ) - { - for ( int i = 0; i < intLen; ++i ) - outInts[outOff + i] = - ( ( inBytes[inOff + i * 4 ] & 0xff ) << 24 ) | - ( ( inBytes[inOff + i * 4 + 1] & 0xff ) << 16 ) | - ( ( inBytes[inOff + i * 4 + 2] & 0xff ) << 8 ) | - ( inBytes[inOff + i * 4 + 3] & 0xff ); - } - - /// Spread ints into bytes. - public static void spreadIntsToBytes( int[] inInts, int inOff, byte[] outBytes, int outOff, int intLen ) - { - for ( int i = 0; i < intLen; ++i ) - { - outBytes[outOff + i * 4 ] = (byte) ( inInts[inOff + i] >>> 24 ); - outBytes[outOff + i * 4 + 1] = (byte) ( inInts[inOff + i] >>> 16 ); - outBytes[outOff + i * 4 + 2] = (byte) ( inInts[inOff + i] >>> 8 ); - outBytes[outOff + i * 4 + 3] = (byte) inInts[inOff + i]; - } - } - } diff --git a/limbo-android-lib/src/main/java/android/androidVNC/FitToScreenScaling.java b/limbo-android-lib/src/main/java/android/androidVNC/FitToScreenScaling.java deleted file mode 100644 index 840f51cbd..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/FitToScreenScaling.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import com.limbo.emu.lib.R; - -import android.widget.ImageView.ScaleType; - -/** - * @author Michael A. MacDonald - */ -class FitToScreenScaling extends AbstractScaling { - - /** - * @param id - * @param scaleType - */ - FitToScreenScaling() { - super(R.id.itemFitToScreen, ScaleType.FIT_CENTER); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isAbleToPan() - */ - @Override - boolean isAbleToPan() { - return false; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isValidInputMode(int) - */ - @Override - boolean isValidInputMode(int mode) { - return mode == R.id.itemInputFitToScreen; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#getDefaultHandlerId() - */ - @Override - int getDefaultHandlerId() { - return R.id.itemInputFitToScreen; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#setCanvasScaleType(android.androidVNC.VncCanvas) - */ - @Override - public void setScaleTypeForActivity(VncCanvasActivity activity) { - super.setScaleTypeForActivity(activity); - activity.vncCanvas.absoluteXPosition = activity.vncCanvas.absoluteYPosition = 0; - activity.vncCanvas.scrollTo(0, 0); - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/FullBufferBitmapData.java b/limbo-android-lib/src/main/java/android/androidVNC/FullBufferBitmapData.java deleted file mode 100644 index 8fce6534f..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/FullBufferBitmapData.java +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package android.androidVNC; - -import java.io.IOException; -import java.util.Arrays; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; -import android.widget.ImageView; - -import com.max2idea.android.limbo.main.Config; - -/** - * @author Michael A. MacDonald - * - */ -class FullBufferBitmapData extends AbstractBitmapData { - - int xoffset; - int yoffset; - - /** - * @author Michael A. MacDonald - * - */ - class Drawable extends AbstractBitmapDrawable { - - /** - * @param data - */ - public Drawable(AbstractBitmapData data) { - super(data); - // TODO Auto-generated constructor stub - } - - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#draw(android.graphics.Canvas) - */ - @Override - public void draw(Canvas canvas) { - if (vncCanvas.getScaleType() == ImageView.ScaleType.FIT_CENTER) - { - //canvas.drawBitmap(data.bitmapPixels, 0, data.framebufferwidth, xoffset, yoffset, framebufferwidth, framebufferheight, false, null); - - //XXX; Limbo: for Hardware accelerated surfaces we have to stop using the above deprecated method and use a bitmap-backed method - // this fixes the issue with Nougat Devices displaying black screen for 24bit color mode C24bit - Bitmap bitmapTmp = Bitmap.createBitmap(framebufferwidth, framebufferheight, Config.bitmapConfig); - bitmapTmp.setPixels(bitmapPixels, 0, data.framebufferwidth, 0, 0, framebufferwidth, framebufferheight); - canvas.drawBitmap(bitmapTmp, xoffset, yoffset, null); - - } - else - { - float scale = vncCanvas.getScale(); - int xo = xoffset < 0 ? 0 : xoffset; - int yo = yoffset < 0 ? 0 : yoffset; - /* - if (scale == 1 || scale <= 0) - { - */ - int drawWidth = vncCanvas.getVisibleWidth(); - if (drawWidth + xo > data.framebufferwidth) - drawWidth = data.framebufferwidth - xo; - int drawHeight = vncCanvas.getVisibleHeight(); - if (drawHeight + yo > data.framebufferheight) - drawHeight = data.framebufferheight - yo; - - - //canvas.drawBitmap(data.bitmapPixels, offset(xo, yo), data.framebufferwidth, xo, yo, drawWidth, drawHeight, false, null); - - //XXX; for Hardware accelerated surfaces we have to stop using the above deprecated method and use a bitmap-backed method - // this fixes the issue with Nougat Devices displaying black screen for 24bit color mode C24bit - Bitmap bitmapTmp = Bitmap.createBitmap(framebufferwidth, framebufferheight, Config.bitmapConfig); - bitmapTmp.setPixels(bitmapPixels, offset(xo, yo), data.framebufferwidth, 0, 0, drawWidth, drawHeight); - canvas.drawBitmap(bitmapTmp, xo, yo, null); - - /* - } - else - { - int scalewidth = (int)(vncCanvas.getVisibleWidth() / scale + 1); - if (scalewidth + xo > data.framebufferwidth) - scalewidth = data.framebufferwidth - xo; - int scaleheight = (int)(vncCanvas.getVisibleHeight() / scale + 1); - if (scaleheight + yo > data.framebufferheight) - scaleheight = data.framebufferheight - yo; - canvas.drawBitmap(data.bitmapPixels, offset(xo, yo), data.framebufferwidth, xo, yo, scalewidth, scaleheight, false, null); - } - */ - } - if(data.vncCanvas.connection.getUseLocalCursor()) - { - setCursorRect(data.vncCanvas.mouseX, data.vncCanvas.mouseY); - clipRect.set(cursorRect); - if (canvas.clipRect(cursorRect)) - { - drawCursor(canvas); - } - } - } - } - - /** - * Multiply this times total number of pixels to get estimate of process size with all buffers plus - * safety factor - */ - static final int CAPACITY_MULTIPLIER = 7; - - /** - * @param p - * @param c - */ - public FullBufferBitmapData(RfbProto p, VncCanvas c, int capacity) { - super(p, c); - framebufferwidth=rfb.framebufferWidth; - framebufferheight=rfb.framebufferHeight; - bitmapwidth=framebufferwidth; - bitmapheight=framebufferheight; - android.util.Log.i("FBBM", "bitmapsize = ("+bitmapwidth+","+bitmapheight+")"); - bitmapPixels = new int[framebufferwidth * framebufferheight]; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#copyRect(android.graphics.Rect, android.graphics.Rect, android.graphics.Paint) - */ - @Override - void copyRect(Rect src, Rect dest, Paint paint) { - // TODO copy rect working? - throw new RuntimeException( "copyrect Not implemented"); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#createDrawable() - */ - @Override - AbstractBitmapDrawable createDrawable() { - return new Drawable(this); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#drawRect(int, int, int, int, android.graphics.Paint) - */ - @Override - void drawRect(int x, int y, int w, int h, Paint paint) { - int color = paint.getColor(); - int offset = offset(x,y); - if (w > 10) - { - for (int j = 0; j < h; j++, offset += framebufferwidth) - { - Arrays.fill(bitmapPixels, offset, offset + w, color); - } - } - else - { - for (int j = 0; j < h; j++, offset += framebufferwidth - w) - { - for (int k = 0; k < w; k++, offset++) - { - bitmapPixels[offset] = color; - } - } - } - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#offset(int, int) - */ - @Override - int offset(int x, int y) { - return x + y * framebufferwidth; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#scrollChanged(int, int) - */ - @Override - void scrollChanged(int newx, int newy) { - xoffset = newx; - yoffset = newy; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#syncScroll() - */ - @Override - void syncScroll() { - // Don't need to do anything here - - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#updateBitmap(int, int, int, int) - */ - @Override - void updateBitmap(int x, int y, int w, int h) { - // Don't need to do anything here - - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#validDraw(int, int, int, int) - */ - @Override - boolean validDraw(int x, int y, int w, int h) { - return true; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#writeFullUpdateRequest(boolean) - */ - @Override - void writeFullUpdateRequest(boolean incremental) throws IOException { - rfb.writeFramebufferUpdateRequest(0, 0, framebufferwidth, framebufferheight, incremental); - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/InStream.java b/limbo-android-lib/src/main/java/android/androidVNC/InStream.java deleted file mode 100644 index cbbda0667..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/InStream.java +++ /dev/null @@ -1,155 +0,0 @@ -/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. - * - * This 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 software 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 software; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, - * USA. - */ - -// -// rdr::InStream marshalls data from a buffer stored in RDR (RFB Data -// Representation). -// -package android.androidVNC; - - -abstract public class InStream { - - // check() ensures there is buffer data for at least one item of size - // itemSize bytes. Returns the number of items in the buffer (up to a - // maximum of nItems). - - public final int check(int itemSize, int nItems) throws Exception { - if (ptr + itemSize * nItems > end) { - if (ptr + itemSize > end) - return overrun(itemSize, nItems); - - nItems = (end - ptr) / itemSize; - } - return nItems; - } - - public final void check(int itemSize) throws Exception { - if (ptr + itemSize > end) - overrun(itemSize, 1); - } - - // readU/SN() methods read unsigned and signed N-bit integers. - - public final int readS8() throws Exception { - check(1); return b[ptr++]; - } - - public final int readS16() throws Exception { - check(2); int b0 = b[ptr++]; - int b1 = b[ptr++] & 0xff; return b0 << 8 | b1; - } - - public final int readS32() throws Exception { - check(4); int b0 = b[ptr++]; - int b1 = b[ptr++] & 0xff; - int b2 = b[ptr++] & 0xff; - int b3 = b[ptr++] & 0xff; - return b0 << 24 | b1 << 16 | b2 << 8 | b3; - } - - public final int readU8() throws Exception { - return readS8() & 0xff; - } - - public final int readU16() throws Exception { - return readS16() & 0xffff; - } - - public final int readU32() throws Exception { - return readS32() & 0xffffffff; - } - - public final void skip(int bytes) throws Exception { - while (bytes > 0) { - int n = check(1, bytes); - ptr += n; - bytes -= n; - } - } - - // readBytes() reads an exact number of bytes into an array at an offset. - - public void readBytes(byte[] data, int offset, int length) throws Exception { - int offsetEnd = offset + length; - while (offset < offsetEnd) { - int n = check(1, offsetEnd - offset); - System.arraycopy(b, ptr, data, offset, n); - ptr += n; - offset += n; - } - } - - // readOpaqueN() reads a quantity "without byte-swapping". Because java has - // no byte-ordering, we just use big-endian. - - public final int readOpaque8() throws Exception { - return readU8(); - } - - public final int readOpaque16() throws Exception { - return readU16(); - } - - public final int readOpaque32() throws Exception { - return readU32(); - } - - public final int readOpaque24A() throws Exception { - check(3); int b0 = b[ptr++]; - int b1 = b[ptr++]; int b2 = b[ptr++]; - return b0 << 24 | b1 << 16 | b2 << 8; - } - - public final int readOpaque24B() throws Exception { - check(3); int b0 = b[ptr++]; - int b1 = b[ptr++]; int b2 = b[ptr++]; - return b0 << 16 | b1 << 8 | b2; - } - - // pos() returns the position in the stream. - - abstract public int pos(); - - // bytesAvailable() returns true if at least one byte can be read from the - // stream without blocking. i.e. if false is returned then readU8() would - // block. - - public boolean bytesAvailable() { return end != ptr; } - - // getbuf(), getptr(), getend() and setptr() are "dirty" methods which allow - // you to manipulate the buffer directly. This is useful for a stream which - // is a wrapper around an underlying stream. - - public final byte[] getbuf() { return b; } - public final int getptr() { return ptr; } - public final int getend() { return end; } - public final void setptr(int p) { ptr = p; } - - // overrun() is implemented by a derived class to cope with buffer overrun. - // It ensures there are at least itemSize bytes of buffer data. Returns - // the number of items in the buffer (up to a maximum of nItems). itemSize - // is supposed to be "small" (a few bytes). - - abstract protected int overrun(int itemSize, int nItems) throws Exception; - - protected InStream() {} - protected byte[] b; - protected int ptr; - protected int end; -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/LargeBitmapData.java b/limbo-android-lib/src/main/java/android/androidVNC/LargeBitmapData.java deleted file mode 100644 index 4a07c2d3d..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/LargeBitmapData.java +++ /dev/null @@ -1,319 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import java.io.IOException; - -import com.antlersoft.android.drawing.OverlappingCopy; -import com.antlersoft.android.drawing.RectList; -import com.antlersoft.util.ObjectPool; -import com.max2idea.android.limbo.main.Config; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Rect; - -/** - * @author Michael A. MacDonald - * - */ -class LargeBitmapData extends AbstractBitmapData { - - /** - * Multiply this times total number of pixels to get estimate of process size with all buffers plus - * safety factor - */ - static final int CAPACITY_MULTIPLIER = 21; - - int xoffset; - int yoffset; - int scrolledToX; - int scrolledToY; - private Rect bitmapRect; - private Paint defaultPaint; - private RectList invalidList; - private RectList pendingList; - - /** - * Pool of temporary rectangle objects. Need to synchronize externally access from - * multiple threads. - */ - private static ObjectPool rectPool = new ObjectPool() { - - /* (non-Javadoc) - * @see com.antlersoft.util.ObjectPool#itemForPool() - */ - @Override - protected Rect itemForPool() { - return new Rect(); - } - }; - - class LargeBitmapDrawable extends AbstractBitmapDrawable - { - LargeBitmapDrawable() - { - super(LargeBitmapData.this); - } - /* (non-Javadoc) - * @see android.graphics.drawable.DrawableContainer#draw(android.graphics.Canvas) - */ - @Override - public void draw(Canvas canvas) { - //android.util.Log.i("LBM", "Drawing "+xoffset+" "+yoffset); - int xoff, yoff; - synchronized ( LargeBitmapData.this ) - { - xoff=xoffset; - yoff=yoffset; - } - draw(canvas, xoff, yoff); - } - } - - /** - * - * @param p Protocol implementation - * @param c View that will display screen - * @param displayWidth - * @param displayHeight - * @param capacity Max process heap size in bytes - */ - LargeBitmapData(RfbProto p, VncCanvas c, int displayWidth, int displayHeight, int capacity) - { - super(p,c); - double scaleMultiplier = Math.sqrt((double)(capacity * 1024 * 1024) / (double)(CAPACITY_MULTIPLIER * framebufferwidth * framebufferheight)); - if (scaleMultiplier > 1) - scaleMultiplier = 1; - bitmapwidth=(int)((double)framebufferwidth * scaleMultiplier); - if (bitmapwidth < displayWidth) - bitmapwidth = displayWidth; - bitmapheight=(int)((double)framebufferheight * scaleMultiplier); - if (bitmapheight < displayHeight) - bitmapheight = displayHeight; - android.util.Log.i("LBM", "bitmapsize = ("+bitmapwidth+","+bitmapheight+")"); - mbitmap = Bitmap.createBitmap(bitmapwidth, bitmapheight, Config.bitmapConfig); - memGraphics = new Canvas(mbitmap); - bitmapPixels = new int[bitmapwidth * bitmapheight]; - invalidList = new RectList(rectPool); - pendingList = new RectList(rectPool); - bitmapRect=new Rect(0,0,bitmapwidth,bitmapheight); - defaultPaint = new Paint(); - } - - @Override - AbstractBitmapDrawable createDrawable() - { - return new LargeBitmapDrawable(); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#copyRect(android.graphics.Rect, android.graphics.Rect, android.graphics.Paint) - */ - @Override - void copyRect(Rect src, Rect dest, Paint paint) { - // TODO copy rect working? - throw new RuntimeException( "copyrect Not implemented"); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#drawRect(int, int, int, int, android.graphics.Paint) - */ - @Override - void drawRect(int x, int y, int w, int h, Paint paint) { - x-=xoffset; - y-=yoffset; - memGraphics.drawRect(x, y, x+w, y+h, paint); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#offset(int, int) - */ - @Override - int offset(int x, int y) { - return (y - yoffset) * bitmapwidth + x - xoffset; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#scrollChanged(int, int) - */ - @Override - synchronized void scrollChanged(int newx, int newy) { - //android.util.Log.i("LBM","scroll "+newx+" "+newy); - int newScrolledToX = scrolledToX; - int newScrolledToY = scrolledToY; - int visibleWidth = vncCanvas.getVisibleWidth(); - int visibleHeight = vncCanvas.getVisibleHeight(); - if (newx - xoffset < 0 ) - { - newScrolledToX = newx + visibleWidth / 2 - bitmapwidth / 2; - if (newScrolledToX < 0) - newScrolledToX = 0; - } - else if (newx - xoffset + visibleWidth > bitmapwidth) - { - newScrolledToX = newx + visibleWidth / 2 - bitmapwidth / 2; - if (newScrolledToX + bitmapwidth > framebufferwidth) - newScrolledToX = framebufferwidth - bitmapwidth; - } - if (newy - yoffset < 0 ) - { - newScrolledToY = newy + visibleHeight / 2 - bitmapheight / 2; - if (newScrolledToY < 0) - newScrolledToY = 0; - } - else if (newy - yoffset + visibleHeight > bitmapheight) - { - newScrolledToY = newy + visibleHeight / 2 - bitmapheight / 2; - if (newScrolledToY + bitmapheight > framebufferheight) - newScrolledToY = framebufferheight - bitmapheight; - } - if (newScrolledToX != scrolledToX || newScrolledToY != scrolledToY) - { - scrolledToX = newScrolledToX; - scrolledToY = newScrolledToY; - if ( waitingForInput) - syncScroll(); - } - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#updateBitmap(int, int, int, int) - */ - @Override - void updateBitmap(int x, int y, int w, int h) { - mbitmap.setPixels(bitmapPixels, offset(x,y), bitmapwidth, x-xoffset, y-yoffset, w, h); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#validDraw(int, int, int, int) - */ - @Override - synchronized boolean validDraw(int x, int y, int w, int h) { - //android.util.Log.i("LBM", "Validate Drawing "+x+" "+y+" "+w+" "+h+" "+xoffset+" "+yoffset+" "+(x-xoffset>=0 && x-xoffset+w<=bitmapwidth && y-yoffset>=0 && y-yoffset+h<=bitmapheight)); - boolean result = x-xoffset>=0 && x-xoffset+w<=bitmapwidth && y-yoffset>=0 && y-yoffset+h<=bitmapheight; - ObjectPool.Entry entry = rectPool.reserve(); - Rect r = entry.get(); - r.set(x, y, x+w, y+h); - pendingList.subtract(r); - if ( ! result) - { - invalidList.add(r); - } - else - invalidList.subtract(r); - rectPool.release(entry); - return result; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#writeFullUpdateRequest(boolean) - */ - @Override - synchronized void writeFullUpdateRequest(boolean incremental) throws IOException { - if (! incremental) { - ObjectPool.Entry entry = rectPool.reserve(); - Rect r = entry.get(); - r.left=xoffset; - r.top=yoffset; - r.right=xoffset + bitmapwidth; - r.bottom=yoffset + bitmapheight; - pendingList.add(r); - invalidList.add(r); - rectPool.release(entry); - } - rfb.writeFramebufferUpdateRequest(xoffset, yoffset, bitmapwidth, bitmapheight, incremental); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractBitmapData#syncScroll() - */ - @Override - synchronized void syncScroll() { - - int deltaX = xoffset - scrolledToX; - int deltaY = yoffset - scrolledToY; - xoffset=scrolledToX; - yoffset=scrolledToY; - bitmapRect.top=scrolledToY; - bitmapRect.bottom=scrolledToY+bitmapheight; - bitmapRect.left=scrolledToX; - bitmapRect.right=scrolledToX+bitmapwidth; - invalidList.intersect(bitmapRect); - if ( deltaX != 0 || deltaY != 0) - { - boolean didOverlapping = false; - if (Math.abs(deltaX) < bitmapwidth && Math.abs(deltaY) < bitmapheight) { - ObjectPool.Entry sourceEntry = rectPool.reserve(); - ObjectPool.Entry addedEntry = rectPool.reserve(); - try - { - Rect added = addedEntry.get(); - Rect sourceRect = sourceEntry.get(); - sourceRect.set(deltaX<0 ? -deltaX : 0, - deltaY<0 ? -deltaY : 0, - deltaX<0 ? bitmapwidth : bitmapwidth - deltaX, - deltaY < 0 ? bitmapheight : bitmapheight - deltaY); - if (! invalidList.testIntersect(sourceRect)) { - didOverlapping = true; - OverlappingCopy.Copy(mbitmap, memGraphics, defaultPaint, sourceRect, deltaX + sourceRect.left, deltaY + sourceRect.top, rectPool); - // Write request for side pixels - if (deltaX != 0) { - added.left = deltaX < 0 ? bitmapRect.right + deltaX : bitmapRect.left; - added.right = added.left + Math.abs(deltaX); - added.top = bitmapRect.top; - added.bottom = bitmapRect.bottom; - invalidList.add(added); - } - if (deltaY != 0) { - added.left = deltaX < 0 ? bitmapRect.left : bitmapRect.left + deltaX; - added.top = deltaY < 0 ? bitmapRect.bottom + deltaY : bitmapRect.top; - added.right = added.left + bitmapwidth - Math.abs(deltaX); - added.bottom = added.top + Math.abs(deltaY); - invalidList.add(added); - } - } - } - finally { - rectPool.release(addedEntry); - rectPool.release(sourceEntry); - } - } - if (! didOverlapping) - { - try - { - //android.util.Log.i("LBM","update req "+xoffset+" "+yoffset); - mbitmap.eraseColor(Color.GREEN); - writeFullUpdateRequest(false); - } - catch ( IOException ioe) - { - // TODO log this - } - } - } - int size = pendingList.getSize(); - for (int i=0; i { - public int keySym; - int mouseButtons; - int keyEvent; - String name; - boolean isMouse; - boolean isKeyEvent; - - MetaKeyBase(int mouseButtons, String name) - { - this.mouseButtons = mouseButtons; - this.name = name; - this.isMouse = true; - this.isKeyEvent = false; - } - - MetaKeyBase(String name, int keySym, int keyEvent) - { - this.name = name; - this.keySym = keySym; - this.keyEvent = keyEvent; - this.isMouse = false; - this.isKeyEvent = true; - } - - MetaKeyBase(String name, int keySym) - { - this.name = name; - this.keySym = keySym; - this.isMouse = false; - this.isKeyEvent = false; - } - - /* (non-Javadoc) - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(MetaKeyBase another) { - return name.compareTo(another.name); - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/MetaKeyBean.java b/limbo-android-lib/src/main/java/android/androidVNC/MetaKeyBean.java deleted file mode 100644 index c5d82b56e..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/MetaKeyBean.java +++ /dev/null @@ -1,267 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import java.util.ArrayList; -import java.util.HashMap; - -import android.view.KeyEvent; - -/** - * @author Michael A. MacDonald - * - */ -public class MetaKeyBean { - int keySym; - int metaFlags; - - static final ArrayList allKeys; - static final String[] allKeysNames; - public static final HashMap keysByKeyCode; - static final HashMap keysByMouseButton; - static final HashMap keysByKeySym; - static final MetaKeyBean keyCtrlAltDel; - static final MetaKeyBean keyCtrlC; - static final MetaKeyBean keyArrowLeft; - static final MetaKeyBean keyArrowRight; - static final MetaKeyBean keyArrowUp; - static final MetaKeyBean keyArrowDown; - - static { - allKeys = new ArrayList(); - - allKeys.add(new MetaKeyBase("Hangul", 0xff31)); - allKeys.add(new MetaKeyBase("Hangul_Start", 0xff32)); - allKeys.add(new MetaKeyBase("Hangul_End", 0xff33)); - allKeys.add(new MetaKeyBase("Hangul_Hanja", 0xff34)); - allKeys.add(new MetaKeyBase("Kana_Shift", 0xff2e)); - allKeys.add(new MetaKeyBase("Right_Alt", 0xffea)); - - allKeys.add(new MetaKeyBase(VncCanvas.MOUSE_BUTTON_LEFT, "Mouse Left")); - allKeys.add(new MetaKeyBase(VncCanvas.MOUSE_BUTTON_MIDDLE, - "Mouse Middle")); - allKeys.add(new MetaKeyBase(VncCanvas.MOUSE_BUTTON_RIGHT, "Mouse Right")); - allKeys.add(new MetaKeyBase(VncCanvas.MOUSE_BUTTON_SCROLL_DOWN, - "Mouse Scroll Down")); - allKeys.add(new MetaKeyBase(VncCanvas.MOUSE_BUTTON_SCROLL_UP, - "Mouse Scroll Up")); - - allKeys.add(new MetaKeyBase("Home", 0xFF50)); - allKeys.add(new MetaKeyBase("Arrow Left", 0xFF51)); - allKeys.add(new MetaKeyBase("Arrow Up", 0xFF52)); - allKeys.add(new MetaKeyBase("Arrow Right", 0xFF53)); - allKeys.add(new MetaKeyBase("Arrow Down", 0xFF54)); - allKeys.add(new MetaKeyBase("Page Up", 0xFF55)); - allKeys.add(new MetaKeyBase("Page Down", 0xFF56)); - allKeys.add(new MetaKeyBase("End", 0xFF57)); - allKeys.add(new MetaKeyBase("Insert", 0xFF63)); - allKeys.add(new MetaKeyBase("Delete", 0xFFFF, KeyEvent.KEYCODE_DEL)); - allKeys.add(new MetaKeyBase("Num Lock", 0xFF7F)); - allKeys.add(new MetaKeyBase("Break", 0xFF6b)); - allKeys.add(new MetaKeyBase("Scroll Lock", 0xFF14)); - allKeys.add(new MetaKeyBase("Print Scrn", 0xFF15)); - allKeys.add(new MetaKeyBase("Escape", 0xFF1B)); - allKeys.add(new MetaKeyBase("Enter", 0xFF0D, KeyEvent.KEYCODE_ENTER)); - allKeys.add(new MetaKeyBase("Tab", 0xFF09, KeyEvent.KEYCODE_TAB)); - allKeys.add(new MetaKeyBase("BackSpace", 0xFF08)); - allKeys.add(new MetaKeyBase("Space", 0x020, KeyEvent.KEYCODE_SPACE)); - - StringBuilder sb = new StringBuilder(" "); - for (int i = 0; i < 26; i++) { - sb.setCharAt(0, (char) ('A' + i)); - allKeys.add(new MetaKeyBase(sb.toString(), 'a' + i, - KeyEvent.KEYCODE_A + i)); - } - - for (int i = 0; i < 10; i++) { - sb.setCharAt(0, (char) ('0' + i)); - allKeys.add(new MetaKeyBase(sb.toString(), '0' + i, - KeyEvent.KEYCODE_0 + i)); - } - - for (int i = 0; i < 12; i++) { - sb.setLength(0); - sb.append('F'); - if (i < 9) - sb.append(' '); - sb.append(Integer.toString(i + 1)); - allKeys.add(new MetaKeyBase(sb.toString(), 0xFFBE + i)); - } - - java.util.Collections.sort(allKeys); - allKeysNames = new String[allKeys.size()]; - keysByKeyCode = new HashMap(); - keysByMouseButton = new HashMap(); - keysByKeySym = new HashMap(); - for (int i = 0; i < allKeysNames.length; ++i) { - MetaKeyBase b = allKeys.get(i); - allKeysNames[i] = b.name; - if (b.isKeyEvent) - keysByKeyCode.put(b.keyEvent, b); - if (b.isMouse) - keysByMouseButton.put(b.mouseButtons, b); - else - keysByKeySym.put(b.keySym, b); - } - keyCtrlAltDel = new MetaKeyBean(0, VncCanvas.CTRL_MASK - | VncCanvas.ALT_MASK, keysByKeyCode.get(KeyEvent.KEYCODE_DEL)); - keyCtrlC = new MetaKeyBean(0, VncCanvas.CTRL_MASK, - keysByKeyCode.get(KeyEvent.KEYCODE_C)); - keyArrowLeft = new MetaKeyBean(0, 0, keysByKeySym.get(0xFF51)); - keyArrowUp = new MetaKeyBean(0, 0, keysByKeySym.get(0xFF52)); - keyArrowRight = new MetaKeyBean(0, 0, keysByKeySym.get(0xFF53)); - keyArrowDown = new MetaKeyBean(0, 0, keysByKeySym.get(0xFF54)); - } - - private boolean _regenDesc; - private boolean mouseClick; - - MetaKeyBean() { - } - - MetaKeyBean(MetaKeyBean toCopy) { - _regenDesc = true; - if (toCopy.isMouseClick()) - setMouseButtons(toCopy.getMouseButtons()); - else - setKeySym(toCopy.getKeySym()); - setMetaListId(toCopy.getMetaListId()); - setMetaFlags(toCopy.getMetaFlags()); - } - - private void setMetaListId(Object metaListId) { - - - } - - private Object getMetaListId() { - - return null; - } - - MetaKeyBean(long listId, int metaFlags, MetaKeyBase base) { - - setKeyBase(base); - setMetaFlags(metaFlags); - _regenDesc = true; - } - - public String getKeyDesc() { - if (_regenDesc) { - synchronized (this) { - if (_regenDesc) { - StringBuilder sb = new StringBuilder(); - int meta = getMetaFlags(); - if (0 != (meta & VncCanvas.SHIFT_MASK)) { - sb.append("Shift"); - } - if (0 != (meta & VncCanvas.CTRL_MASK)) { - if (sb.length() > 0) - sb.append('-'); - sb.append("Ctrl"); - } - if (0 != (meta & VncCanvas.ALT_MASK)) { - if (sb.length() > 0) - sb.append('-'); - sb.append("Alt"); - } - if (sb.length() > 0) - sb.append(' '); - MetaKeyBase base; - if (isMouseClick()) - base = keysByMouseButton.get(getMouseButtons()); - else - base = keysByKeySym.get(getKeySym()); - sb.append(base.name); - setKeyDesc(sb.toString()); - } - } - } - return getKeyDesc(); - } - - public void setKeyDesc(String arg_keyDesc) { - _regenDesc = false; - } - - public void setKeySym(int arg_keySym) { - if (arg_keySym != getKeySym() || isMouseClick()) { - setMouseClick(false); - _regenDesc = true; - - } - this.keySym = arg_keySym ; - } - - int getKeySym() { - - return keySym; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractMetaKeyBean#setMetaFlags(int) - */ - public void setMetaFlags(int arg_metaFlags) { - if (arg_metaFlags != getMetaFlags()) { - _regenDesc = true; - } - this.metaFlags = arg_metaFlags; - } - - int getMetaFlags() { - - return this.metaFlags; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractMetaKeyBean#setMouseButtons(int) - */ - public void setMouseButtons(int arg_mouseButtons) { - if (arg_mouseButtons != getMouseButtons() || !isMouseClick()) { - setMouseClick(true); - _regenDesc = true; - } - } - - private void setMouseClick(boolean b) { - - this.mouseClick = b; - } - - boolean isMouseClick() { - - return false; - } - - int getMouseButtons() { - - return 0; - } - - void setKeyBase(MetaKeyBase base) { - if (base.isMouse) { - setMouseButtons(base.mouseButtons); - } else { - setKeySym(base.keySym); - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object o) { - if (o instanceof MetaKeyBean) { - return getKeyDesc().equals(((MetaKeyBean) o).getKeyDesc()); - } - return false; - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/MetaList.java b/limbo-android-lib/src/main/java/android/androidVNC/MetaList.java deleted file mode 100644 index f4b3d8974..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/MetaList.java +++ /dev/null @@ -1,77 +0,0 @@ -// This class was generated from android.androidVNC.IMetaList by a tool -// Do not edit this file directly! PLX THX -package android.androidVNC; - -public class MetaList { - - public static final String GEN_TABLE_NAME = "META_LIST"; - public static final int GEN_COUNT = 2; - - // Field constants - public static final String GEN_FIELD__ID = "_id"; - public static final int GEN_ID__ID = 0; - public static final String GEN_FIELD_NAME = "NAME"; - public static final int GEN_ID_NAME = 1; - - // SQL Command for creating the table - public static String GEN_CREATE = "CREATE TABLE META_LIST (" + - "_id INTEGER PRIMARY KEY AUTOINCREMENT," + - "NAME TEXT" + - ")"; - - // Members corresponding to defined fields - private long gen__Id; - private java.lang.String gen_name; - - - public String Gen_tableName() { return GEN_TABLE_NAME; } - - // Field accessors - public long get_Id() { return gen__Id; } - public void set_Id(long arg__Id) { gen__Id = arg__Id; } - public java.lang.String getName() { return gen_name; } - public void setName(java.lang.String arg_name) { gen_name = arg_name; } - - public android.content.ContentValues Gen_getValues() { - android.content.ContentValues values=new android.content.ContentValues(); - values.put(GEN_FIELD__ID,Long.toString(this.gen__Id)); - values.put(GEN_FIELD_NAME,this.gen_name); - return values; - } - - /** - * Return an array that gives the column index in the cursor for each field defined - * @param cursor Database cursor over some columns, possibly including this table - * @return array of column indices; -1 if the column with that id is not in cursor - */ - public int[] Gen_columnIndices(android.database.Cursor cursor) { - int[] result=new int[GEN_COUNT]; - result[0] = cursor.getColumnIndex(GEN_FIELD__ID); - // Make compatible with database generated by older version of plugin with uppercase column name - if (result[0] == -1) { - result[0] = cursor.getColumnIndex("_ID"); - } - result[1] = cursor.getColumnIndex(GEN_FIELD_NAME); - return result; - } - - /** - * Populate one instance from a cursor - */ - public void Gen_populate(android.database.Cursor cursor,int[] columnIndices) { - if ( columnIndices[GEN_ID__ID] >= 0 && ! cursor.isNull(columnIndices[GEN_ID__ID])) { - gen__Id = cursor.getLong(columnIndices[GEN_ID__ID]); - } - if ( columnIndices[GEN_ID_NAME] >= 0 && ! cursor.isNull(columnIndices[GEN_ID_NAME])) { - gen_name = cursor.getString(columnIndices[GEN_ID_NAME]); - } - } - - /** - * Populate one instance from a ContentValues - */ - public void Gen_populate(android.content.ContentValues values) { - gen__Id = values.getAsLong(GEN_FIELD__ID); - gen_name = values.getAsString(GEN_FIELD_NAME); - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/MouseMover.java b/limbo-android-lib/src/main/java/android/androidVNC/MouseMover.java deleted file mode 100644 index 618ab0957..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/MouseMover.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2010 Michael A. MacDonald - */ -package android.androidVNC; - -import android.os.Handler; -import android.os.SystemClock; -import android.view.MotionEvent; - -/** - * Specialization of panner that moves the mouse instead of panning the screen - * - * @author Michael A. MacDonald - * - */ -class MouseMover extends Panner { - - public MouseMover(VncCanvasActivity act, Handler hand) { - super(act, hand); - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - long interval = SystemClock.uptimeMillis() - lastSent; - lastSent += interval; - double scale = (double)interval / 50.0; - VncCanvas canvas = activity.vncCanvas; - //Log.v(TAG, String.format("panning %f %d %d", scale, (int)((double)velocity.x * scale), (int)((double)velocity.y * scale))); - if ( canvas.processPointerEvent((int)(canvas.mouseX + ((double)velocity.x * scale)), - (int)(canvas.mouseY + ((double)velocity.y * scale)), - MotionEvent.ACTION_MOVE, 0, - false, false, false, false)) - { - if (updater.updateVelocity(velocity, interval)) - { - handler.postDelayed(this, 50); - } - else - { - //Log.v(TAG, "Updater requests stop"); - stop(); - } - } - else - { - //Log.v(TAG, "Panning failed"); - stop(); - } - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/OneToOneScaling.java b/limbo-android-lib/src/main/java/android/androidVNC/OneToOneScaling.java deleted file mode 100644 index 62461c87a..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/OneToOneScaling.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import com.limbo.emu.lib.R; - -import android.widget.ImageView.ScaleType; - -/** - * @author Michael A. MacDonald - */ -class OneToOneScaling extends AbstractScaling { - - /** - * @param id - * @param scaleType - */ - public OneToOneScaling() { - super(R.id.itemOneToOne,ScaleType.CENTER); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#getDefaultHandlerId() - */ - @Override - int getDefaultHandlerId() { - return R.id.itemInputTouchPanTrackballMouse; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isAbleToPan() - */ - @Override - boolean isAbleToPan() { - return true; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isValidInputMode(int) - */ - @Override - boolean isValidInputMode(int mode) { - return mode != R.id.itemInputFitToScreen; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#setScaleTypeForActivity(android.androidVNC.VncCanvasActivity) - */ - @Override - public void setScaleTypeForActivity(VncCanvasActivity activity) { - super.setScaleTypeForActivity(activity); - activity.vncCanvas.scrollToAbsolute(); - activity.vncCanvas.pan(0,0); - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/Panner.java b/limbo-android-lib/src/main/java/android/androidVNC/Panner.java deleted file mode 100644 index 4298f1ad8..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/Panner.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import android.graphics.PointF; -import android.os.Handler; -import android.os.SystemClock; - -/** - * Handles panning the screen continuously over a period of time - * @author Michael A. MacDonald - */ -class Panner implements Runnable { - - VncCanvasActivity activity; - Handler handler; - PointF velocity; - long lastSent; - VelocityUpdater updater; - - private static final String TAG = "PANNER"; - - /** - * Specify how the panning velocity changes over time - * @author Michael A. MacDonald - */ - interface VelocityUpdater { - /** - * Called approximately every 50 ms to update the velocity of panning - * @param p X and Y components to update - * @param interval Milliseconds since last update - * @return False if the panning should stop immediately; true otherwise - */ - boolean updateVelocity(PointF p, long interval); - } - - static class DefaultUpdater implements VelocityUpdater { - - static DefaultUpdater instance = new DefaultUpdater(); - - /** - * Don't change velocity - */ - @Override - public boolean updateVelocity(PointF p, long interval) { - return true; - } - - } - - Panner(VncCanvasActivity act, Handler hand) { - activity = act; - velocity = new PointF(); - handler = hand; - } - - void stop() - { - handler.removeCallbacks(this); - } - - void start(float xv, float yv, VelocityUpdater update) - { - if (update == null) - update = DefaultUpdater.instance; - updater = update; - velocity.x = xv; - velocity.y = yv; - //Log.v(TAG, String.format("pan start %f %f", velocity.x, velocity.y)); - lastSent = SystemClock.uptimeMillis(); - - handler.postDelayed(this, 50); - } - - /* (non-Javadoc) - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - long interval = SystemClock.uptimeMillis() - lastSent; - lastSent += interval; - double scale = (double)interval / 50.0; - //Log.v(TAG, String.format("panning %f %d %d", scale, (int)((double)velocity.x * scale), (int)((double)velocity.y * scale))); - if ( activity.vncCanvas.pan((int)((double)velocity.x * scale), (int)((double)velocity.y * scale))) - { - if (updater.updateVelocity(velocity, interval)) - { - handler.postDelayed(this, 50); - } - else - { - //Log.v(TAG, "Updater requests stop"); - stop(); - } - } - else - { - //Log.v(TAG, "Panning failed"); - stop(); - } - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/RepeaterDialog.java b/limbo-android-lib/src/main/java/android/androidVNC/RepeaterDialog.java deleted file mode 100644 index cd7213a6e..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/RepeaterDialog.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - */ -package android.androidVNC; - -import com.limbo.emu.lib.R; - -import android.app.Activity; -import android.app.Dialog; -import android.os.Bundle; -import android.text.Html; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; - -/** - * @author Michael A. MacDonald - * - */ -class RepeaterDialog extends Dialog { - private EditText _repeaterId; - androidVNC _configurationDialog; - - RepeaterDialog(androidVNC context) { - super(context); - setOwnerActivity((Activity)context); - _configurationDialog = context; - } - - /* (non-Javadoc) - * @see android.app.Dialog#onCreate(android.os.Bundle) - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setTitle(R.string.repeater_dialog_title); - - setContentView(R.layout.repeater_dialog); - _repeaterId=(EditText)findViewById(R.id.textRepeaterInfo); - ((TextView)findViewById(R.id.textRepeaterCaption)).setText(Html.fromHtml(getContext().getString(R.string.repeater_caption))); - ((Button)findViewById(R.id.buttonSaveRepeater)).setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - _configurationDialog.updateRepeaterInfo(true, _repeaterId.getText().toString()); - dismiss(); - } - }); - ((Button)findViewById(R.id.buttonClearRepeater)).setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - _configurationDialog.updateRepeaterInfo(false, ""); - dismiss(); - } - }); - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/RfbProto.java b/limbo-android-lib/src/main/java/android/androidVNC/RfbProto.java deleted file mode 100644 index 9fec1bbd2..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/RfbProto.java +++ /dev/null @@ -1,1416 +0,0 @@ -// -// Copyright (C) 2001-2004 HorizonLive.com, Inc. All Rights Reserved. -// Copyright (C) 2001-2006 Constantin Kaplinsky. All Rights Reserved. -// Copyright (C) 2000 Tridia Corporation. All Rights Reserved. -// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. -// -// This 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 software 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 software; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// - -// -// RfbProto.java -// - -package android.androidVNC; - -import android.net.LocalSocket; -import android.net.LocalSocketAddress; -import android.os.Handler; -import android.os.HandlerThread; -import android.util.Log; - -import com.max2idea.android.limbo.main.Config; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; - -//- import java.awt.*; -//- import java.awt.event.*; -//- import java.util.zip.*; - -/** - * Access the RFB protocol through a socket. - *

- * This class has no knowledge of the android-specific UI; it sees framebuffer updates - * and input events as defined in the RFB protocol. - * - */ -public class RfbProto { - - final static String TAG = "RfbProto"; - - final static String - versionMsg_3_3 = "RFB 003.003\n", - versionMsg_3_7 = "RFB 003.007\n", - versionMsg_3_8 = "RFB 003.008\n"; - - // Vendor signatures: standard VNC/RealVNC, TridiaVNC, and TightVNC - final static String - StandardVendor = "STDV", - TridiaVncVendor = "TRDV", - TightVncVendor = "TGHT"; - - // Security types - final static int - SecTypeInvalid = 0, - SecTypeNone = 1, - SecTypeVncAuth = 2, - SecTypeTight = 16, - SecTypeUltra34 = 0xfffffffa; - - // Supported tunneling types - final static int - NoTunneling = 0; - final static String - SigNoTunneling = "NOTUNNEL"; - - // Supported authentication types - final static int - AuthNone = 1, - AuthVNC = 2, - AuthUnixLogin = 129, - AuthUltra = 17; - final static String - SigAuthNone = "NOAUTH__", - SigAuthVNC = "VNCAUTH_", - SigAuthUnixLogin = "ULGNAUTH"; - - // VNC authentication results - final static int - VncAuthOK = 0, - VncAuthFailed = 1, - VncAuthTooMany = 2; - - // Server-to-client messages - final static int - FramebufferUpdate = 0, - SetColourMapEntries = 1, - Bell = 2, - ServerCutText = 3, - TextChat = 11; - - // Client-to-server messages - final static int - SetPixelFormat = 0, - FixColourMapEntries = 1, - SetEncodings = 2, - FramebufferUpdateRequest = 3, - KeyboardEvent = 4, - PointerEvent = 5, - ClientCutText = 6; - - // Supported encodings and pseudo-encodings - final static int - EncodingRaw = 0, - EncodingCopyRect = 1, - EncodingRRE = 2, - EncodingCoRRE = 4, - EncodingHextile = 5, - EncodingZlib = 6, - EncodingTight = 7, - EncodingZRLE = 16, - EncodingCompressLevel0 = 0xFFFFFF00, - EncodingQualityLevel0 = 0xFFFFFFE0, - EncodingXCursor = 0xFFFFFF10, - EncodingRichCursor = 0xFFFFFF11, - EncodingPointerPos = 0xFFFFFF18, - EncodingLastRect = 0xFFFFFF20, - EncodingNewFBSize = 0xFFFFFF21; - final static String - SigEncodingRaw = "RAW_____", - SigEncodingCopyRect = "COPYRECT", - SigEncodingRRE = "RRE_____", - SigEncodingCoRRE = "CORRE___", - SigEncodingHextile = "HEXTILE_", - SigEncodingZlib = "ZLIB____", - SigEncodingTight = "TIGHT___", - SigEncodingZRLE = "ZRLE____", - SigEncodingCompressLevel0 = "COMPRLVL", - SigEncodingQualityLevel0 = "JPEGQLVL", - SigEncodingXCursor = "X11CURSR", - SigEncodingRichCursor = "RCHCURSR", - SigEncodingPointerPos = "POINTPOS", - SigEncodingLastRect = "LASTRECT", - SigEncodingNewFBSize = "NEWFBSIZ"; - - final static int MaxNormalEncoding = 255; - - // Contstants used in the Hextile decoder - final static int - HextileRaw = 1, - HextileBackgroundSpecified = 2, - HextileForegroundSpecified = 4, - HextileAnySubrects = 8, - HextileSubrectsColoured = 16; - - // Contstants used in the Tight decoder - final static int TightMinToCompress = 12; - final static int - TightExplicitFilter = 0x04, - TightFill = 0x08, - TightJpeg = 0x09, - TightMaxSubencoding = 0x09, - TightFilterCopy = 0x00, - TightFilterPalette = 0x01, - TightFilterGradient = 0x02; - - // Constants used for UltraVNC chat extension - final static int - CHAT_OPEN = -1, - CHAT_CLOSE = -2, - CHAT_FINISHED = -3; - - String host; - int port; - Socket sock; - DataInputStream is; - LimboOutputStream os; - private OutputStream sos; - - //Limbo: need to send the network operations of the Main UI - // but also use a mechanism like IntentService to keep - // the network message queue intact - class LimboOutputStream { - - OutputStream os; - HandlerThread rfbQueueThread = null; - Handler handler = null; - - public LimboOutputStream(OutputStream sos) { - os = sos; - - rfbQueueThread = new HandlerThread("RfbQueue"); - rfbQueueThread.start(); - handler = new Handler(rfbQueueThread.getLooper()); - } - - public void write(final int data) throws IOException { - final int data0 = data; - - handler.post(new Runnable() { - @Override - public void run() { - try { - sos.write(data0); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - } - - public void write(final byte[] bytes) throws IOException { - final byte [] buffer0 = java.util.Arrays.copyOf(bytes, bytes.length); - - handler.post(new Runnable() { - @Override - public void run() { - try { - sos.write(buffer0); - } catch (IOException e) { - Log.w(TAG, "Error while sending VNC data"); - if(Config.debug) - e.printStackTrace(); - } - } - }); - } - - public void write(final byte[] buffer, final int offset, final int count) throws IOException { - final byte [] buffer0 = java.util.Arrays.copyOf(buffer, count); - final int offset0 = offset; - final int count0 = count; - - handler.post(new Runnable() { - @Override - public void run() { - try { - sos.write(buffer0, offset0, count0); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - } - - public void close() { - rfbQueueThread.interrupt(); - handler.removeCallbacks(null); - handler.getLooper().quit(); - } - - } - - DH dh; - long dh_resp; - - //- SessionRecorder rec; - boolean inNormalProtocol = false; - //- VncViewer viewer; - - // Java on UNIX does not call keyPressed() on some keys, for example - // swedish keys To prevent our workaround to produce duplicate - // keypresses on JVMs that actually works, keep track of if - // keyPressed() for a "broken" key was called or not. - boolean brokenKeyPressed = false; - - // This will be set to true on the first framebuffer update - // containing Zlib-, ZRLE- or Tight-encoded data. - boolean wereZlibUpdates = false; - - // This will be set to false if the startSession() was called after - // we have received at least one Zlib-, ZRLE- or Tight-encoded - // framebuffer update. - boolean recordFromBeginning = true; - - // This fields are needed to show warnings about inefficiently saved - // sessions only once per each saved session file. - boolean zlibWarningShown; - boolean tightWarningShown; - - // Before starting to record each saved session, we set this field - // to 0, and increment on each framebuffer update. We don't flush - // the SessionRecorder data into the file before the second update. - // This allows us to write initial framebuffer update with zero - // timestamp, to let the player show initial desktop before - // playback. - int numUpdatesInSession; - - // Measuring network throughput. - boolean timing; - long timeWaitedIn100us; - long timedKbits; - - // Protocol version and TightVNC-specific protocol options. - int serverMajor, serverMinor; - int clientMajor, clientMinor; - boolean protocolTightVNC; - CapsContainer tunnelCaps, authCaps; - CapsContainer serverMsgCaps, clientMsgCaps; - CapsContainer encodingCaps; - - // If true, informs that the RFB socket was closed. - private boolean closed; - - - // - // Constructor. Make TCP connection to RFB server. - // - - LocalSocket localSocket = null; - public static boolean allow_external = false; - - //-RfbProto(String h, int p, VncViewer v) throws IOException { - RfbProto(String h, int p) throws IOException{ - //- viewer = v; - host = h; - port = p; - - /* - if (viewer.socketFactory == null) { - sock = new Socket(host, port); - } else { - try { - Class factoryClass = Class.forName(viewer.socketFactory); - SocketFactory factory = (SocketFactory)factoryClass.newInstance(); - //- if (viewer.inAnApplet) - //- sock = factory.createSocket(host, port, viewer); - //- else - sock = factory.createSocket(host, port, viewer.mainArgs); - } - catch(Exception e) { - e.printStackTrace(); - throw new IOException(e.getMessage()); - } - } */ - //+ - - if(!allow_external) { - localSocket = new LocalSocket(); - String localVNCSocketPath = Config.getLocalVNCSocketPath(); - LocalSocketAddress localSocketAddr = new LocalSocketAddress(localVNCSocketPath, LocalSocketAddress.Namespace.FILESYSTEM); - localSocket.connect(localSocketAddr); - is = new DataInputStream(new BufferedInputStream(localSocket.getInputStream(), - 32768)); - sos = localSocket.getOutputStream(); - - } else { - sock = new Socket(host, port); - is = new DataInputStream(new BufferedInputStream(sock.getInputStream(), - 16384)); - sos = sock.getOutputStream(); - } - - os = new LimboOutputStream(sos); - - timing = false; - timeWaitedIn100us = 5; - timedKbits = 0; - } - - - synchronized void close() { - - try { - os.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - - try { - sock.close(); - closed = true; - //- System.out.println("RFB socket closed"); - Log.v(TAG, "RFB socket closed"); - /*- - if (rec != null) { - rec.close(); - rec = null; - - } */ - } catch (Exception e) { - e.printStackTrace(); - } - - - } - - synchronized boolean closed() { - return closed; - } - - // - // Read server's protocol version message - // - - void readVersionMsg() throws Exception { - - byte[] b = new byte[12]; - - readFully(b); - - if ((b[0] != 'R') || (b[1] != 'F') || (b[2] != 'B') || (b[3] != ' ') - || (b[4] < '0') || (b[4] > '9') || (b[5] < '0') || (b[5] > '9') - || (b[6] < '0') || (b[6] > '9') || (b[7] != '.') - || (b[8] < '0') || (b[8] > '9') || (b[9] < '0') || (b[9] > '9') - || (b[10] < '0') || (b[10] > '9') || (b[11] != '\n')) - { - Log.i(TAG,new String(b)); - throw new Exception("Host " + host + " port " + port + - " is not an RFB server"); - } - - serverMajor = (b[4] - '0') * 100 + (b[5] - '0') * 10 + (b[6] - '0'); - serverMinor = (b[8] - '0') * 100 + (b[9] - '0') * 10 + (b[10] - '0'); - - if (serverMajor < 3) { - throw new Exception("RFB server does not support protocol version 3"); - } - } - - - // - // Write our protocol version message - // - - synchronized void writeVersionMsg() throws IOException { - clientMajor = 3; - if (serverMajor > 3 || serverMinor >= 8) { - clientMinor = 8; - os.write(versionMsg_3_8.getBytes()); - } else if (serverMinor >= 7) { - clientMinor = 7; - os.write(versionMsg_3_7.getBytes()); - } else { - clientMinor = 3; - os.write(versionMsg_3_3.getBytes()); - } - protocolTightVNC = false; - } - - - // - // Negotiate the authentication scheme. - // - - int negotiateSecurity(int bitPref) throws Exception { - return (clientMinor >= 7) ? - selectSecurityType(bitPref) : readSecurityType(bitPref); - } - - // - // Read security type from the server (protocol version 3.3). - // - - int readSecurityType(int bitPref) throws Exception { - int secType = is.readInt(); - - switch (secType) { - case SecTypeInvalid: - readConnFailedReason(); - return SecTypeInvalid; // should never be executed - case SecTypeNone: - case SecTypeVncAuth: - return secType; - case SecTypeUltra34: - if((bitPref & 1) == 1) - return secType; - throw new Exception("Username required."); - default: - throw new Exception("Unknown security type from RFB server: " + secType); - } - } - - // - // Select security type from the server's list (protocol versions 3.7/3.8). - // - - int selectSecurityType(int bitPref) throws Exception { - int secType = SecTypeInvalid; - - // Read the list of security types. - int nSecTypes = is.readUnsignedByte(); - if (nSecTypes == 0) { - readConnFailedReason(); - return SecTypeInvalid; // should never be executed - } - byte[] secTypes = new byte[nSecTypes]; - readFully(secTypes); - - // Find out if the server supports TightVNC protocol extensions - for (int i = 0; i < nSecTypes; i++) { - if (secTypes[i] == SecTypeTight) { - protocolTightVNC = true; - os.write(SecTypeTight); - return SecTypeTight; - } - } - - // Find first supported security type. - for (int i = 0; i < nSecTypes; i++) { - if (secTypes[i] == SecTypeNone || secTypes[i] == SecTypeVncAuth) { - secType = secTypes[i]; - break; - } - } - - if (secType == SecTypeInvalid) { - throw new Exception("Server did not offer supported security type"); - } else { - os.write(secType); - } - - return secType; - } - - // - // Perform "no authentication". - // - - void authenticateNone() throws Exception { - if (clientMinor >= 8) - readSecurityResult("No authentication"); - } - - // - // Perform standard VNC Authentication. - // - - void authenticateVNC(String pw) throws Exception { - byte[] challenge = new byte[16]; - readFully(challenge); - - if (pw.length() > 8) - pw = pw.substring(0, 8); // Truncate to 8 chars - - // Truncate password on the first zero byte. - int firstZero = pw.indexOf(0); - if (firstZero != -1) - pw = pw.substring(0, firstZero); - - byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; - System.arraycopy(pw.getBytes(), 0, key, 0, pw.length()); - - DesCipher des = new DesCipher(key); - - des.encrypt(challenge, 0, challenge, 0); - des.encrypt(challenge, 8, challenge, 8); - - os.write(challenge); - - readSecurityResult("VNC authentication"); - } - - // - // Read security result. - // Throws an exception on authentication failure. - // - - void readSecurityResult(String authType) throws Exception { - int securityResult = is.readInt(); - - switch (securityResult) { - case VncAuthOK: - System.out.println(authType + ": success"); - break; - case VncAuthFailed: - if (clientMinor >= 8) - readConnFailedReason(); - throw new Exception(authType + ": failed"); - case VncAuthTooMany: - throw new Exception(authType + ": failed, too many tries"); - default: - throw new Exception(authType + ": unknown result " + securityResult); - } - } - - // - // Read the string describing the reason for a connection failure, - // and throw an exception. - // - - void readConnFailedReason() throws Exception { - int reasonLen = is.readInt(); - byte[] reason = new byte[reasonLen]; - readFully(reason); - String reasonString = new String(reason); - Log.v(TAG, reasonString); - throw new Exception(reasonString); - } - - void prepareDH() throws Exception - { - long gen = is.readLong(); - long mod = is.readLong(); - dh_resp = is.readLong(); - - dh = new DH(gen,mod); - long pub = dh.createInterKey(); - - os.write(DH.longToBytes(pub)); - } - - void authenticateDH(String us,String pw) throws Exception - { - long key = dh.createEncryptionKey(dh_resp); - - DesCipher des = new DesCipher(DH.longToBytes(key)); - - byte user[] = new byte[256]; - byte passwd[] = new byte[64]; - int i; - System.arraycopy(us.getBytes(),0,user,0,us.length()); - if(us.length() < 256) - { - for(i=us.length(); i<256; i++) - { - user[i]=0; - } - } - System.arraycopy(pw.getBytes(),0,passwd,0,pw.length()); - if(pw.length() < 64) - { - for(i=pw.length(); i<64; i++) - { - passwd[i]=0; - } - } - - des.encryptText(user,user,DH.longToBytes(key)); - des.encryptText(passwd,passwd,DH.longToBytes(key)); - - os.write(user); - os.write(passwd); - - readSecurityResult("VNC authentication"); - } - // - // Initialize capability lists (TightVNC protocol extensions). - // - - void initCapabilities() { - tunnelCaps = new CapsContainer(); - authCaps = new CapsContainer(); - serverMsgCaps = new CapsContainer(); - clientMsgCaps = new CapsContainer(); - encodingCaps = new CapsContainer(); - - // Supported authentication methods - authCaps.add(AuthNone, StandardVendor, SigAuthNone, - "No authentication"); - authCaps.add(AuthVNC, StandardVendor, SigAuthVNC, - "Standard VNC password authentication"); - - // Supported encoding types - encodingCaps.add(EncodingCopyRect, StandardVendor, - SigEncodingCopyRect, "Standard CopyRect encoding"); - encodingCaps.add(EncodingRRE, StandardVendor, - SigEncodingRRE, "Standard RRE encoding"); - encodingCaps.add(EncodingCoRRE, StandardVendor, - SigEncodingCoRRE, "Standard CoRRE encoding"); - encodingCaps.add(EncodingHextile, StandardVendor, - SigEncodingHextile, "Standard Hextile encoding"); - encodingCaps.add(EncodingZRLE, StandardVendor, - SigEncodingZRLE, "Standard ZRLE encoding"); - encodingCaps.add(EncodingZlib, TridiaVncVendor, - SigEncodingZlib, "Zlib encoding"); - encodingCaps.add(EncodingTight, TightVncVendor, - SigEncodingTight, "Tight encoding"); - - // Supported pseudo-encoding types - encodingCaps.add(EncodingCompressLevel0, TightVncVendor, - SigEncodingCompressLevel0, "Compression level"); - encodingCaps.add(EncodingQualityLevel0, TightVncVendor, - SigEncodingQualityLevel0, "JPEG quality level"); - encodingCaps.add(EncodingXCursor, TightVncVendor, - SigEncodingXCursor, "X-style cursor shape update"); - encodingCaps.add(EncodingRichCursor, TightVncVendor, - SigEncodingRichCursor, "Rich-color cursor shape update"); - encodingCaps.add(EncodingPointerPos, TightVncVendor, - SigEncodingPointerPos, "Pointer position update"); - encodingCaps.add(EncodingLastRect, TightVncVendor, - SigEncodingLastRect, "LastRect protocol extension"); - encodingCaps.add(EncodingNewFBSize, TightVncVendor, - SigEncodingNewFBSize, "Framebuffer size change"); - } - - // - // Setup tunneling (TightVNC protocol extensions) - // - - void setupTunneling() throws IOException { - int nTunnelTypes = is.readInt(); - if (nTunnelTypes != 0) { - readCapabilityList(tunnelCaps, nTunnelTypes); - - // We don't support tunneling yet. - writeInt(NoTunneling); - } - } - - // - // Negotiate authentication scheme (TightVNC protocol extensions) - // - - int negotiateAuthenticationTight() throws Exception { - int nAuthTypes = is.readInt(); - if (nAuthTypes == 0) - return AuthNone; - - readCapabilityList(authCaps, nAuthTypes); - for (int i = 0; i < authCaps.numEnabled(); i++) { - int authType = authCaps.getByOrder(i); - if (authType == AuthNone || authType == AuthVNC) { - writeInt(authType); - return authType; - } - } - throw new Exception("No suitable authentication scheme found"); - } - - // - // Read a capability list (TightVNC protocol extensions) - // - - void readCapabilityList(CapsContainer caps, int count) throws IOException { - int code; - byte[] vendor = new byte[4]; - byte[] name = new byte[8]; - for (int i = 0; i < count; i++) { - code = is.readInt(); - readFully(vendor); - readFully(name); - caps.enable(new CapabilityInfo(code, vendor, name)); - } - } - - // - // Write a 32-bit integer into the output stream. - // - - byte[] writeIntBuffer = new byte[4]; - void writeInt(int value) throws IOException { - writeIntBuffer[0] = (byte) ((value >> 24) & 0xff); - writeIntBuffer[1] = (byte) ((value >> 16) & 0xff); - writeIntBuffer[2] = (byte) ((value >> 8) & 0xff); - writeIntBuffer[3] = (byte) (value & 0xff); - os.write(writeIntBuffer); - } - - // - // Write the client initialisation message - // - - void writeClientInit() throws IOException { - /*- if (viewer.options.shareDesktop) { - os.write(1); - } else { - os.write(0); - } - viewer.options.disableShareDesktop(); - */ - os.write(0); - } - - - // - // Read the server initialisation message - // - - String desktopName; - public int framebufferWidth, framebufferHeight; - int bitsPerPixel, depth; - boolean bigEndian, trueColour; - int redMax, greenMax, blueMax, redShift, greenShift, blueShift; - - void readServerInit() throws IOException { - framebufferWidth = is.readUnsignedShort(); - framebufferHeight = is.readUnsignedShort(); - bitsPerPixel = is.readUnsignedByte(); - depth = is.readUnsignedByte(); - bigEndian = (is.readUnsignedByte() != 0); - trueColour = (is.readUnsignedByte() != 0); - redMax = is.readUnsignedShort(); - greenMax = is.readUnsignedShort(); - blueMax = is.readUnsignedShort(); - redShift = is.readUnsignedByte(); - greenShift = is.readUnsignedByte(); - blueShift = is.readUnsignedByte(); - byte[] pad = new byte[3]; - readFully(pad); - int nameLength = is.readInt(); - byte[] name = new byte[nameLength]; - readFully(name); - desktopName = new String(name); - - // Read interaction capabilities (TightVNC protocol extensions) - if (protocolTightVNC) { - int nServerMessageTypes = is.readUnsignedShort(); - int nClientMessageTypes = is.readUnsignedShort(); - int nEncodingTypes = is.readUnsignedShort(); - is.readUnsignedShort(); - readCapabilityList(serverMsgCaps, nServerMessageTypes); - readCapabilityList(clientMsgCaps, nClientMessageTypes); - readCapabilityList(encodingCaps, nEncodingTypes); - } - - inNormalProtocol = true; - } - - - // - // Create session file and write initial protocol messages into it. - // - /*- - void startSession(String fname) throws IOException { - rec = new SessionRecorder(fname); - rec.writeHeader(); - rec.write(versionMsg_3_3.getBytes()); - rec.writeIntBE(SecTypeNone); - rec.writeShortBE(framebufferWidth); - rec.writeShortBE(framebufferHeight); - byte[] fbsServerInitMsg = { - 32, 24, 0, 1, 0, - (byte)0xFF, 0, (byte)0xFF, 0, (byte)0xFF, - 16, 8, 0, 0, 0, 0 - }; - rec.write(fbsServerInitMsg); - rec.writeIntBE(desktopName.length()); - rec.write(desktopName.getBytes()); - numUpdatesInSession = 0; - - // FIXME: If there were e.g. ZRLE updates only, that should not - // affect recording of Zlib and Tight updates. So, actually - // we should maintain separate flags for Zlib, ZRLE and - // Tight, instead of one ``wereZlibUpdates'' variable. - // - if (wereZlibUpdates) - recordFromBeginning = false; - - zlibWarningShown = false; - tightWarningShown = false; - } - - // - // Close session file. - // - - void closeSession() throws IOException { - if (rec != null) { - rec.close(); - rec = null; - } - } - */ - - // - // Set new framebuffer size - // - - void setFramebufferSize(int width, int height) { - framebufferWidth = width; - framebufferHeight = height; - } - - - // - // Read the server message type - // - - int readServerMessageType() throws IOException { - int msgType = is.readUnsignedByte(); - - // If the session is being recorded: - /*- - if (rec != null) { - if (msgType == Bell) { // Save Bell messages in session files. - rec.writeByte(msgType); - if (numUpdatesInSession > 0) - rec.flush(); - } - } - */ - - return msgType; - } - - - // - // Read a FramebufferUpdate message - // - - int updateNRects; - - void readFramebufferUpdate() throws IOException { - is.readByte(); - updateNRects = is.readUnsignedShort(); - - // If the session is being recorded: - /*- - if (rec != null) { - rec.writeByte(FramebufferUpdate); - rec.writeByte(0); - rec.writeShortBE(updateNRects); - } - */ - - numUpdatesInSession++; - } - - // Read a FramebufferUpdate rectangle header - - int updateRectX, updateRectY, updateRectW, updateRectH, updateRectEncoding; - - void readFramebufferUpdateRectHdr() throws Exception { - updateRectX = is.readUnsignedShort(); - updateRectY = is.readUnsignedShort(); - updateRectW = is.readUnsignedShort(); - updateRectH = is.readUnsignedShort(); - updateRectEncoding = is.readInt(); - - if (updateRectEncoding == EncodingZlib || - updateRectEncoding == EncodingZRLE || - updateRectEncoding == EncodingTight) - wereZlibUpdates = true; - - // If the session is being recorded: - /*- - if (rec != null) { - if (numUpdatesInSession > 1) - rec.flush(); // Flush the output on each rectangle. - rec.writeShortBE(updateRectX); - rec.writeShortBE(updateRectY); - rec.writeShortBE(updateRectW); - rec.writeShortBE(updateRectH); - if (updateRectEncoding == EncodingZlib && !recordFromBeginning) { - // Here we cannot write Zlib-encoded rectangles because the - // decoder won't be able to reproduce zlib stream state. - if (!zlibWarningShown) { - System.out.println("Warning: Raw encoding will be used " + - "instead of Zlib in recorded session."); - zlibWarningShown = true; - } - rec.writeIntBE(EncodingRaw); - } else { - rec.writeIntBE(updateRectEncoding); - if (updateRectEncoding == EncodingTight && !recordFromBeginning && - !tightWarningShown) { - System.out.println("Warning: Re-compressing Tight-encoded " + - "updates for session recording."); - tightWarningShown = true; - } - } - } - */ - - if (updateRectEncoding != RfbProto.EncodingPointerPos && ( updateRectEncoding < 0 || updateRectEncoding > MaxNormalEncoding )) - return; - - if (updateRectX + updateRectW > framebufferWidth || - updateRectY + updateRectH > framebufferHeight) { - throw new Exception("Framebuffer update rectangle too large: " + - updateRectW + "x" + updateRectH + " at (" + - updateRectX + "," + updateRectY + ")"); - } - } - - // Read CopyRect source X and Y. - - int copyRectSrcX, copyRectSrcY; - - void readCopyRect() throws IOException { - copyRectSrcX = is.readUnsignedShort(); - copyRectSrcY = is.readUnsignedShort(); - - // If the session is being recorded: - /*- - if (rec != null) { - rec.writeShortBE(copyRectSrcX); - rec.writeShortBE(copyRectSrcY); - } - */ - } - - - // - // Read a ServerCutText message - // - - String readServerCutText() throws IOException { - byte[] pad = new byte[3]; - readFully(pad); - int len = is.readInt(); - byte[] text = new byte[len]; - readFully(text); - return new String(text); - } - - - // - // Read an integer in compact representation (1..3 bytes). - // Such format is used as a part of the Tight encoding. - // Also, this method records data if session recording is active and - // the viewer's recordFromBeginning variable is set to true. - // - - int readCompactLen() throws IOException { - int[] portion = new int[3]; - portion[0] = is.readUnsignedByte(); - int byteCount = 1; - int len = portion[0] & 0x7F; - if ((portion[0] & 0x80) != 0) { - portion[1] = is.readUnsignedByte(); - byteCount++; - len |= (portion[1] & 0x7F) << 7; - if ((portion[1] & 0x80) != 0) { - portion[2] = is.readUnsignedByte(); - byteCount++; - len |= (portion[2] & 0xFF) << 14; - } - } - /*- - if (rec != null && recordFromBeginning) - for (int i = 0; i < byteCount; i++) - rec.writeByte(portion[i]); - */ - return len; - } - - - // - // Write a FramebufferUpdateRequest message - // - - byte[] framebufferUpdateRequest = new byte[10]; - synchronized void writeFramebufferUpdateRequest(int x, int y, int w, int h, - boolean incremental) - throws IOException - { - framebufferUpdateRequest[0] = (byte) FramebufferUpdateRequest; - framebufferUpdateRequest[1] = (byte) (incremental ? 1 : 0); - framebufferUpdateRequest[2] = (byte) ((x >> 8) & 0xff); - framebufferUpdateRequest[3] = (byte) (x & 0xff); - framebufferUpdateRequest[4] = (byte) ((y >> 8) & 0xff); - framebufferUpdateRequest[5] = (byte) (y & 0xff); - framebufferUpdateRequest[6] = (byte) ((w >> 8) & 0xff); - framebufferUpdateRequest[7] = (byte) (w & 0xff); - framebufferUpdateRequest[8] = (byte) ((h >> 8) & 0xff); - framebufferUpdateRequest[9] = (byte) (h & 0xff); - - os.write(framebufferUpdateRequest); - } - - - // - // Write a SetPixelFormat message - // - - synchronized void writeSetPixelFormat(int bitsPerPixel, int depth, boolean bigEndian, - boolean trueColour, - int redMax, int greenMax, int blueMax, - int redShift, int greenShift, int blueShift, boolean fGreyScale) // sf@2005) - throws IOException - { - byte[] b = new byte[20]; - - b[0] = (byte) SetPixelFormat; - b[4] = (byte) bitsPerPixel; - b[5] = (byte) depth; - b[6] = (byte) (bigEndian ? 1 : 0); - b[7] = (byte) (trueColour ? 1 : 0); - b[8] = (byte) ((redMax >> 8) & 0xff); - b[9] = (byte) (redMax & 0xff); - b[10] = (byte) ((greenMax >> 8) & 0xff); - b[11] = (byte) (greenMax & 0xff); - b[12] = (byte) ((blueMax >> 8) & 0xff); - b[13] = (byte) (blueMax & 0xff); - b[14] = (byte) redShift; - b[15] = (byte) greenShift; - b[16] = (byte) blueShift; - b[17] = (byte) (fGreyScale ? 1 : 0); // sf@2005 - - os.write(b); - } - - - // - // Write a FixColourMapEntries message. The values in the red, green and - // blue arrays are from 0 to 65535. - // - - synchronized void writeFixColourMapEntries(int firstColour, int nColours, - int[] red, int[] green, int[] blue) - throws IOException - { - byte[] b = new byte[6 + nColours * 6]; - - b[0] = (byte) FixColourMapEntries; - b[2] = (byte) ((firstColour >> 8) & 0xff); - b[3] = (byte) (firstColour & 0xff); - b[4] = (byte) ((nColours >> 8) & 0xff); - b[5] = (byte) (nColours & 0xff); - - for (int i = 0; i < nColours; i++) { - b[6 + i * 6] = (byte) ((red[i] >> 8) & 0xff); - b[6 + i * 6 + 1] = (byte) (red[i] & 0xff); - b[6 + i * 6 + 2] = (byte) ((green[i] >> 8) & 0xff); - b[6 + i * 6 + 3] = (byte) (green[i] & 0xff); - b[6 + i * 6 + 4] = (byte) ((blue[i] >> 8) & 0xff); - b[6 + i * 6 + 5] = (byte) (blue[i] & 0xff); - } - - os.write(b); - } - - - // - // Write a SetEncodings message - // - - synchronized void writeSetEncodings(int[] encs, int len) throws IOException { - byte[] b = new byte[4 + 4 * len]; - - b[0] = (byte) SetEncodings; - b[2] = (byte) ((len >> 8) & 0xff); - b[3] = (byte) (len & 0xff); - - for (int i = 0; i < len; i++) { - b[4 + 4 * i] = (byte) ((encs[i] >> 24) & 0xff); - b[5 + 4 * i] = (byte) ((encs[i] >> 16) & 0xff); - b[6 + 4 * i] = (byte) ((encs[i] >> 8) & 0xff); - b[7 + 4 * i] = (byte) (encs[i] & 0xff); - } - - os.write(b); - } - - - // - // Write a ClientCutText message - // - - synchronized void writeClientCutText(String text) throws IOException { - byte[] b = new byte[8 + text.length()]; - - b[0] = (byte) ClientCutText; - b[4] = (byte) ((text.length() >> 24) & 0xff); - b[5] = (byte) ((text.length() >> 16) & 0xff); - b[6] = (byte) ((text.length() >> 8) & 0xff); - b[7] = (byte) (text.length() & 0xff); - - System.arraycopy(text.getBytes(), 0, b, 8, text.length()); - - os.write(b); - } - - - // - // A buffer for putting pointer and keyboard events before being sent. This - // is to ensure that multiple RFB events generated from a single Java Event - // will all be sent in a single network packet. The maximum possible - // length is 4 modifier down events, a single key event followed by 4 - // modifier up events i.e. 9 key events or 72 bytes. - // - - byte[] eventBuf = new byte[72]; - int eventBufLen; - - - /** - * Write a pointer event message. We may need to send modifier key events - * around it to set the correct modifier state. - * @param x - * @param y - * @param modifiers - * @param pointerMask - * @throws IOException - */ - synchronized void writePointerEvent( int x, int y, int modifiers, int pointerMask) throws IOException - { - eventBufLen = 0; - writeModifierKeyEvents(modifiers); - - eventBuf[eventBufLen++] = (byte) PointerEvent; - eventBuf[eventBufLen++] = (byte) pointerMask; - eventBuf[eventBufLen++] = (byte) ((x >> 8) & 0xff); - eventBuf[eventBufLen++] = (byte) (x & 0xff); - eventBuf[eventBufLen++] = (byte) ((y >> 8) & 0xff); - eventBuf[eventBufLen++] = (byte) (y & 0xff); - - // - // Always release all modifiers after an "up" event - // - - if (pointerMask == 0) { - writeModifierKeyEvents(0); - } - - os.write(eventBuf, 0, eventBufLen); - } - - void writeCtrlAltDel() throws IOException { - final int DELETE = 0xffff; - final int CTRLALT = VncCanvas.CTRL_MASK | VncCanvas.ALT_MASK; - try { - // Press - eventBufLen = 0; - writeModifierKeyEvents(CTRLALT); - writeKeyEvent(DELETE, true); - os.write(eventBuf, 0, eventBufLen); - - // Release - eventBufLen = 0; - writeModifierKeyEvents(CTRLALT); - writeKeyEvent(DELETE, false); - - // Reset VNC server modifiers state - writeModifierKeyEvents(0); - os.write(eventBuf, 0, eventBufLen); - } catch (IOException e) { - e.printStackTrace(); - } - } - - // - // Write a key event message. We may need to send modifier key events - // around it to set the correct modifier state. Also we need to translate - // from the Java key values to the X keysym values used by the RFB protocol. - // - public synchronized void writeKeyEvent(int keySym, int metaState, boolean down) throws IOException { -// Log.i("writeKeyEvent","key = " + keySym + " metastate = " + metaState + " down = " + down); - eventBufLen = 0; - if (down) - writeModifierKeyEvents(metaState); - if (keySym != 0) - writeKeyEvent(keySym, down); - - // Always release all modifiers after an "up" event - if (!down) - writeModifierKeyEvents(0); - - os.write(eventBuf, 0, eventBufLen); - } - - - - - // - // Add a raw key event with the given X keysym to eventBuf. - // - - private void writeKeyEvent(int keysym, boolean down) { - eventBuf[eventBufLen++] = (byte) KeyboardEvent; - eventBuf[eventBufLen++] = (byte) (down ? 1 : 0); - eventBuf[eventBufLen++] = (byte) 0; - eventBuf[eventBufLen++] = (byte) 0; - eventBuf[eventBufLen++] = (byte) ((keysym >> 24) & 0xff); - eventBuf[eventBufLen++] = (byte) ((keysym >> 16) & 0xff); - eventBuf[eventBufLen++] = (byte) ((keysym >> 8) & 0xff); - eventBuf[eventBufLen++] = (byte) (keysym & 0xff); - } - - - // - // Write key events to set the correct modifier state. - // - - int oldModifiers = 0; - - void writeModifierKeyEvents(int newModifiers) { - if ((newModifiers & VncCanvas.CTRL_MASK) != (oldModifiers & VncCanvas.CTRL_MASK)) - writeKeyEvent(0xffe3, (newModifiers & VncCanvas.CTRL_MASK) != 0); - - if ((newModifiers & VncCanvas.SHIFT_MASK) != (oldModifiers & VncCanvas.SHIFT_MASK)) - writeKeyEvent(0xffe1, (newModifiers & VncCanvas.SHIFT_MASK) != 0); - - if ((newModifiers & VncCanvas.META_MASK) != (oldModifiers & VncCanvas.META_MASK)) - writeKeyEvent(0xffe7, (newModifiers & VncCanvas.META_MASK) != 0); - - if ((newModifiers & VncCanvas.ALT_MASK) != (oldModifiers & VncCanvas.ALT_MASK)) - writeKeyEvent(0xffe9, (newModifiers & VncCanvas.ALT_MASK) != 0); - - oldModifiers = newModifiers; - } - // - // Compress and write the data into the recorded session file. This - // method assumes the recording is on (rec != null). - // - - - public void startTiming() { - timing = true; - - // Carry over up to 1s worth of previous rate for smoothing. - - if (timeWaitedIn100us > 10000) { - timedKbits = timedKbits * 10000 / timeWaitedIn100us; - timeWaitedIn100us = 10000; - } - } - - public void stopTiming() { - timing = false; - if (timeWaitedIn100us < timedKbits/2) - timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s - } - - public long kbitsPerSecond() { - return timedKbits * 10000 / timeWaitedIn100us; - } - - public long timeWaited() { - return timeWaitedIn100us; - } - - public void readFully(byte b[]) throws IOException { - readFully(b, 0, b.length); - } - - public void readFully(byte b[], int off, int len) throws IOException { - long before = 0; - timing = false; // for test - - if (timing) - before = System.currentTimeMillis(); - - is.readFully(b, off, len); - - if (timing) { - long after = System.currentTimeMillis(); - long newTimeWaited = (after - before) * 10; - int newKbits = len * 8 / 1000; - - // limit rate to between 10kbit/s and 40Mbit/s - - if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000; - if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4; - - timeWaitedIn100us += newTimeWaited; - timedKbits += newKbits; - } - } - - synchronized void writeOpenChat() throws Exception { - os.write(TextChat); // byte type - os.write(0); // byte pad 1 - os.write(0); // byte pad 2 - os.write(0); // byte pad 2 - writeInt(CHAT_OPEN); // int message length - } - - synchronized void writeCloseChat() throws Exception { - os.write(TextChat); // byte type - os.write(0); // byte pad 1 - os.write(0); // byte pad 2 - os.write(0); // byte pad 2 - writeInt(CHAT_CLOSE); // int message length - } - - synchronized void writeFinishedChat() throws Exception { - os.write(TextChat); // byte type - os.write(0); // byte pad 1 - os.write(0); // byte pad 2 - os.write(0); // byte pad 2 - writeInt(CHAT_FINISHED); // int message length - } - - String readTextChatMsg() throws Exception { - byte[] pad = new byte[3]; - readFully(pad); - int len = is.readInt(); - if (len == CHAT_OPEN) { - // Remote user requests chat - ///viewer.openChat(); - // Respond to chat request - writeOpenChat(); - return null; - } else if (len == CHAT_CLOSE) { - // Remote user ends chat - ///viewer.closeChat(); - return null; - } else if (len == CHAT_FINISHED) { - // Remote user says chat finished. - // Not sure why I should care about this state. - return null; - } else { - // Remote user sends message!! - if (len > 0) { - byte[] msg = new byte[len]; - readFully(msg); - return new String(msg); - } - } - return null; - } - - public synchronized void writeChatMessage(String msg) throws Exception { - os.write(TextChat); // byte type - os.write(0); // byte pad 1 - os.write(0); // byte pad 2 - os.write(0); // byte pad 2 - byte [] bytes = msg.getBytes("8859_1"); - byte [] outgoing = bytes; - if (bytes.length > 4096) { - outgoing = new byte[4096]; - System.arraycopy(bytes, 0, outgoing, 0, 4096); - } - writeInt(outgoing.length); // int message length - os.write(outgoing); // message - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/Utils.java b/limbo-android-lib/src/main/java/android/androidVNC/Utils.java deleted file mode 100644 index d18f5eb2c..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/Utils.java +++ /dev/null @@ -1,75 +0,0 @@ -package android.androidVNC; - -import android.app.Activity; -import android.app.ActivityManager; -import android.app.AlertDialog; -import android.app.ActivityManager.MemoryInfo; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnClickListener; -import android.content.Intent; -import android.net.Uri; -import android.text.Html; - -public class Utils { - - public static void showYesNoPrompt(Context _context, String title, String message, OnClickListener onYesListener, OnClickListener onNoListener) { - AlertDialog.Builder builder = new AlertDialog.Builder(_context); - builder.setTitle(title); - builder.setIcon(android.R.drawable.ic_dialog_info); // lame icon - builder.setMessage(message); - builder.setCancelable(false); - builder.setPositiveButton("Yes", onYesListener); - builder.setNegativeButton("No", onNoListener); - builder.show(); - } - - private static final Intent docIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/android-vnc-viewer/wiki/Documentation")); - - public static ActivityManager getActivityManager(Context context) - { - ActivityManager result = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); - if (result == null) - throw new UnsupportedOperationException("Could not retrieve ActivityManager"); - return result; - } - - public static MemoryInfo getMemoryInfo(Context _context) { - MemoryInfo info = new MemoryInfo(); - getActivityManager(_context).getMemoryInfo(info); - return info; - } - - public static void showDocumentation(Context c) { - c.startActivity(docIntent); - } - - private static int nextNoticeID = 0; - public static int nextNoticeID() { - nextNoticeID++; - return nextNoticeID; - } - - public static void showErrorMessage(Context _context, String message) { - showMessage(_context, "Error!", message, android.R.drawable.ic_dialog_alert, null); - } - - public static void showFatalErrorMessage(final Context _context, String message) { - showMessage(_context, "Error!", message, android.R.drawable.ic_dialog_alert, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - ((Activity) _context).finish(); - } - }); - } - - public static void showMessage(Context _context, String title, String message, int icon, DialogInterface.OnClickListener ackHandler) { - AlertDialog.Builder builder = new AlertDialog.Builder(_context); - builder.setTitle(title); - builder.setMessage(Html.fromHtml(message)); - builder.setCancelable(false); - builder.setPositiveButton("Acknowledged", ackHandler); - builder.setIcon(icon); - builder.show(); - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/VncCanvas.java b/limbo-android-lib/src/main/java/android/androidVNC/VncCanvas.java deleted file mode 100644 index e517d8e0d..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/VncCanvas.java +++ /dev/null @@ -1,2083 +0,0 @@ -// -// Copyright (C) 2010 Michael A. MacDonald -// Copyright (C) 2004 Horizon Wimba. All Rights Reserved. -// Copyright (C) 2001-2003 HorizonLive.com, Inc. All Rights Reserved. -// Copyright (C) 2001,2002 Constantin Kaplinsky. All Rights Reserved. -// Copyright (C) 2000 Tridia Corporation. All Rights Reserved. -// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. -// -// This 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 software 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 software; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -// USA. -// -// -// VncCanvas is a subclass of android.view.SurfaceView which draws a VNC -// desktop on it. -// -package android.androidVNC; - -import android.app.Activity; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Paint.Style; -import android.graphics.Point; -import android.graphics.Rect; -import android.os.Handler; -import android.util.AttributeSet; -import android.util.Log; -import android.view.Display; -import android.view.InputDevice; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.View; -import android.widget.ImageView; -import android.widget.Toast; - -import com.antlersoft.android.bc.BCFactory; -import com.max2idea.android.limbo.main.Config; -import com.max2idea.android.limbo.main.LimboVNCActivity; -import com.max2idea.android.limbo.utils.UIUtils; - -import org.libsdl.app.SDLActivity; - -import java.io.IOException; -import java.util.zip.Inflater; - -import androidx.appcompat.widget.AppCompatImageView; - -public class VncCanvas extends AppCompatImageView { - - private final static String TAG = "VncCanvas"; - private final static boolean LOCAL_LOGV = true; - public AbstractScaling scaling; - // Available to activity - public int mouseX, mouseY; - // Connection parameters - ConnectionBean connection; - // Runtime control flags - private boolean maintainConnection = true; - private boolean showDesktopInfo = true; - private boolean repaintsEnabled = true; - /** - * Use camera button as meta key for right mouse button - */ - boolean cameraButtonDown = false; - // Keep track when a seeming key press was the result of a menu shortcut - int lastKeyDown; - boolean afterMenu; - // Color Model settings - private COLORMODEL pendingColorModel = COLORMODEL.C24bit; - public COLORMODEL colorModel = null; - private int bytesPerPixel = 0; - private int[] colorPalette = null; - // VNC protocol connection - public RfbProto rfb; - // Internal bitmap data - AbstractBitmapData bitmapData; - public Handler handler = new Handler(); - // VNC Encoding parameters - private boolean useCopyRect = false; // TODO CopyRect is not working - private int preferredEncoding = -1; - // Unimplemented VNC encoding parameters - private boolean requestCursorUpdates = false; - private boolean ignoreCursorUpdates = true; - // Unimplemented TIGHT encoding parameters - private int compressLevel = -1; - private int jpegQuality = -1; - // Used to determine if encoding update is necessary - private int[] encodingsSaved = new int[20]; - private int nEncodingsSaved = 0; - // ZRLE encoder's data. - private byte[] zrleBuf; - private int[] zrleTilePixels; - private ZlibInStream zrleInStream; - // Zlib encoder's data. - private byte[] zlibBuf; - private Inflater zlibInflater; - private MouseScrollRunnable scrollRunnable; - private Paint handleRREPaint; - /** - * Position of the top left portion of the visible part of the - * screen, in full-frame coordinates - */ - int absoluteXPosition = 0, absoluteYPosition = 0; - public boolean mouseDown; - - /** - * Constructor used by the inflation apparatus - * - * @param context - */ - public VncCanvas(final Context context, AttributeSet attrs) { - super(context, attrs); - scrollRunnable = new MouseScrollRunnable(); - handleRREPaint = new Paint(); - handleRREPaint.setStyle(Style.FILL); - } - - public VncCanvas(Context context) { - super(context); - } - - public static int retries; - public static int MAX_RETRIES = 5; - - /** - * Create a view showing a VNC connection - * - * @param context - * Containing context (activity) - * @param bean - * Connection settings - * @param setModes - * Callback to run on UI thread after connection is set up - */ - void initializeVncCanvas(ConnectionBean bean, final Runnable setModes) { - connection = bean; - this.pendingColorModel = COLORMODEL.valueOf(bean.getColorModel()); - - setOnGenericMotionListener(new VNCGenericMotionListener_API12()); - setOnTouchListener(new VNCOnTouchListener()); - - // Startup the RFB thread with a nifty progess dialog - final ProgressDialog pd = ProgressDialog.show(getContext(), "Connecting to VM Console", "Please wait...", true, - true, new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - closeConnection(); - handler.post(new Runnable() { - public void run() { - Utils.showErrorMessage(getContext(), "VNC connection aborted!"); - } - }); - } - }); - final Display display = pd.getWindow().getWindowManager().getDefaultDisplay(); - Thread t = new Thread() { - - public void run() { - try { - int width = 0; - int height = 0; - Point size = new Point(); - display.getSize(size); - width = size.x; - height = size.y; - - connectAndAuthenticate(connection.getUserName(), connection.getPassword()); - doProtocolInitialisation(width, height); - handler.post(new Runnable() { - public void run() { - // pd.setMessage("Downloading first frame.\nPlease - // wait..."); - } - }); - processNormalProtocol(getContext(), pd, setModes); - } catch (Throwable e) { - if (maintainConnection) { - Log.e(TAG, e.toString()); - if(Config.debug) - e.printStackTrace(); - // Ensure we dismiss the progress dialog - // before we fatal error finish - if (pd.isShowing()) { - pd.dismiss(); - } - if (e instanceof OutOfMemoryError) { - // TODO Not sure if this will happen but... - // figure out how to gracefully notify the user - // Instantiating an alert dialog here doesn't work - // because we are out of memory. :( - } else if (e instanceof ArrayIndexOutOfBoundsException || e instanceof java.net.ConnectException - || e instanceof java.io.IOException) { - // Retry - if (retries < MAX_RETRIES) { - retries++; - reload(); - } - } else { - String error = "VNC connection failed!"; - if (e.getMessage() != null && (e.getMessage().indexOf("authentication") > -1)) { - error = "VNC authentication failed!"; - } - final String error_ = error + "
" + e.getLocalizedMessage(); - handler.post(new Runnable() { - public void run() { - Utils.showFatalErrorMessage(getContext(), error_); - } - }); - } - } - } - } - }; - t.start(); - } - - public void reload() { - Log.d(TAG, "Reconnecting..."); - Activity activity = ((Activity) getContext()); - Intent data = new Intent(); - activity.setResult(Config.VNC_RESET_RESULT_CODE, data); - activity.finish(); - - } - - void connectAndAuthenticate(String us, String pw) throws Exception { - Log.i(TAG, "Connecting to " + connection.getAddress() + ", port " + connection.getPort() + "..."); - - rfb = new RfbProto(connection.getAddress(), connection.getPort()); - if (LOCAL_LOGV) { - Log.v(TAG, "Connected to server"); - - } - - rfb.readVersionMsg(); - Log.i(TAG, "RFB server supports protocol version " + rfb.serverMajor + "." + rfb.serverMinor); - - rfb.writeVersionMsg(); - Log.i(TAG, "Using RFB protocol version " + rfb.clientMajor + "." + rfb.clientMinor); - - int bitPref = 0; - if (connection.getUserName().length() > 0) { - bitPref |= 1; - } - Log.d("debug", "bitPref=" + bitPref); - int secType = rfb.negotiateSecurity(bitPref); - int authType; - if (secType == RfbProto.SecTypeTight) { - rfb.initCapabilities(); - rfb.setupTunneling(); - authType = rfb.negotiateAuthenticationTight(); - } else if (secType == RfbProto.SecTypeUltra34) { - rfb.prepareDH(); - authType = RfbProto.AuthUltra; - } else { - authType = secType; - } - - switch (authType) { - case RfbProto.AuthNone: - Log.i(TAG, "No authentication needed"); - rfb.authenticateNone(); - break; - case RfbProto.AuthVNC: - Log.i(TAG, "VNC authentication needed"); - rfb.authenticateVNC(pw); - break; - case RfbProto.AuthUltra: - rfb.authenticateDH(us, pw); - break; - default: - throw new Exception("Unknown authentication scheme " + authType); - } - } - - void doProtocolInitialisation(int dx, int dy) throws IOException { - rfb.writeClientInit(); - rfb.readServerInit(); - - Log.i(TAG, "Desktop name is " + rfb.desktopName); - Log.i(TAG, "Desktop size is " + rfb.framebufferWidth + " x " + rfb.framebufferHeight); - - boolean useFull = false; - int capacity = BCFactory.getInstance().getBCActivityManager() - .getMemoryClass(Utils.getActivityManager(getContext())); - if (connection.getForceFull() == BitmapImplHint.AUTO) { - if (rfb.framebufferWidth * rfb.framebufferHeight * FullBufferBitmapData.CAPACITY_MULTIPLIER <= capacity - * 1024 * 1024) { - useFull = true; - } - } else { - useFull = (connection.getForceFull() == BitmapImplHint.FULL); - } - if (!useFull) { - bitmapData = new LargeBitmapData(rfb, this, dx, dy, capacity); - } else { - bitmapData = new FullBufferBitmapData(rfb, this, capacity); - } - mouseX = rfb.framebufferWidth / 2; - mouseY = rfb.framebufferHeight / 2; - - setPixelFormat(); - } - - private void setPixelFormat() throws IOException { - pendingColorModel.setPixelFormat(rfb); - bytesPerPixel = pendingColorModel.bpp(); - colorPalette = pendingColorModel.palette(); - colorModel = pendingColorModel; - pendingColorModel = null; - } - - public void setColorModel(COLORMODEL cm) { - // Only update if color model changes - if (colorModel == null || !colorModel.equals(cm)) { - pendingColorModel = cm; - } - } - - public boolean isColorModel(COLORMODEL cm) { - return (colorModel != null) && colorModel.equals(cm); - } - - private void mouseFollowPan() { - if (scaling.isAbleToPan()) { - int scrollx = absoluteXPosition; - int scrolly = absoluteYPosition; - int width = getVisibleWidth(); - int height = getVisibleHeight(); - // Log.i(TAG,"scrollx " + scrollx + " scrolly " + scrolly + - // " mouseX " + mouseX +" Y " + mouseY + " w " + width + " h " + - // height); - if (mouseX < scrollx || mouseX >= scrollx + width || mouseY < scrolly || mouseY >= scrolly + height) { - // Log.i(TAG,"warp to " + scrollx+width/2 + "," + scrolly + - // height/2); - warpMouse(scrollx + width / 2, scrolly + height / 2); - } - } - } - - public void processNormalProtocol(final Context context, ProgressDialog pd, final Runnable setModes) - throws Exception { - try { - bitmapData.writeFullUpdateRequest(false); - - handler.post(setModes); - connected(); - // - // main dispatch loop - // - while (maintainConnection) { - bitmapData.syncScroll(); - // Read message type from the server. - int msgType = rfb.readServerMessageType(); - bitmapData.doneWaiting(); - // Process the message depending on its type. - switch (msgType) { - case RfbProto.FramebufferUpdate: - rfb.readFramebufferUpdate(); - - for (int i = 0; i < rfb.updateNRects; i++) { - rfb.readFramebufferUpdateRectHdr(); - int rx = rfb.updateRectX, ry = rfb.updateRectY; - int rw = rfb.updateRectW, rh = rfb.updateRectH; - - if (rfb.updateRectEncoding == RfbProto.EncodingLastRect) { - Log.v(TAG, "rfb.EncodingLastRect"); - break; - } - - if (rfb.updateRectEncoding == RfbProto.EncodingNewFBSize) { - rfb.setFramebufferSize(rw, rh); - // - updateFramebufferSize(); - Log.v(TAG, "rfb.EncodingNewFBSize"); - reload(); - break; - } - - if (rfb.updateRectEncoding == RfbProto.EncodingXCursor - || rfb.updateRectEncoding == RfbProto.EncodingRichCursor) { - // - handleCursorShapeUpdate(rfb.updateRectEncoding, - // rx, - // ry, rw, rh); - Log.v(TAG, "rfb.EncodingCursor"); - continue; - - } - - if (rfb.updateRectEncoding == RfbProto.EncodingPointerPos) { - // This never actually happens - mouseX = rx; - mouseY = ry; - Log.v(TAG, "rfb.EncodingPointerPos"); - continue; - } - - rfb.startTiming(); - - switch (rfb.updateRectEncoding) { - case RfbProto.EncodingRaw: - handleRawRect(rx, ry, rw, rh); - break; - case RfbProto.EncodingCopyRect: - handleCopyRect(rx, ry, rw, rh); - Log.v(TAG, "CopyRect is Buggy!"); - break; - case RfbProto.EncodingRRE: - handleRRERect(rx, ry, rw, rh); - break; - case RfbProto.EncodingCoRRE: - handleCoRRERect(rx, ry, rw, rh); - break; - case RfbProto.EncodingHextile: - handleHextileRect(rx, ry, rw, rh); - break; - case RfbProto.EncodingZRLE: - handleZRLERect(rx, ry, rw, rh); - break; - case RfbProto.EncodingZlib: - handleZlibRect(rx, ry, rw, rh); - break; - default: - Log.e(TAG, "Unknown RFB rectangle encoding " + rfb.updateRectEncoding + " (0x" - + Integer.toHexString(rfb.updateRectEncoding) + ")"); - } - - rfb.stopTiming(); - - // Hide progress dialog - if (pd.isShowing()) { - pd.dismiss(); - } - } - - boolean fullUpdateNeeded = false; - - if (pendingColorModel != null) { - setPixelFormat(); - fullUpdateNeeded = true; - } - - setEncodings(true); - bitmapData.writeFullUpdateRequest(!fullUpdateNeeded); - - break; - - case RfbProto.SetColourMapEntries: - throw new Exception("Can't handle SetColourMapEntries message"); - - case RfbProto.Bell: - handler.post(new Runnable() { - public void run() { - UIUtils.toastShort(context, "VNC Beep"); - } - }); - break; - - case RfbProto.ServerCutText: - String s = rfb.readServerCutText(); - if (s != null && s.length() > 0) { - // TODO implement cut & paste - } - break; - - case RfbProto.TextChat: - // UltraVNC extension - String msg = rfb.readTextChatMsg(); - if (msg != null && msg.length() > 0) { - // TODO implement chat interface - } - break; - - default: - throw new Exception("Unknown RFB message type " + msgType); - } - } - } catch (Exception e) { - throw e; - } finally { - Log.v(TAG, "Closing VNC Connection"); - rfb.close(); - } - } - - /** - * Apply scroll offset and scaling to convert touch-space coordinates to the - * corresponding point on the full frame. - * - * @param e - * MotionEvent with the original, touch space coordinates. This - * event is altered in place. - * @return e -- The same event passed in, with the coordinates mapped - */ - MotionEvent changeTouchCoordinatesToFullFrame(MotionEvent e) { - // Log.v(TAG, String.format("tap at %f,%f", e.getX(), e.getY())); - float scale = getScale(); - - // Adjust coordinates for Android notification bar. - e.offsetLocation(0, -1f * getTop()); - - e.setLocation(absoluteXPosition + e.getX() / scale, absoluteYPosition + e.getY() / scale); - - return e; - } - - public void onDestroy() { - Log.v(TAG, "Cleaning up resources"); - if (bitmapData != null) { - bitmapData.dispose(); - } - bitmapData = null; - } - - /** - * Warp the mouse to x, y in the RFB coordinates - * - * @param x - * @param y - */ - void warpMouse(int x, int y) { - bitmapData.invalidateMousePosition(); - mouseX = x; - mouseY = y; - bitmapData.invalidateMousePosition(); - try { - rfb.writePointerEvent(x, y, 0, MOUSE_BUTTON_NONE); - } catch (IOException ioe) { - Log.w(TAG, ioe); - } - } - - /* - * f(x,s) is a function that returns the coordinate in screen/scroll space - * corresponding to the coordinate x in full-frame space with scaling s. - * - * This function returns the difference between f(x,s1) and f(x,s2) - * - * f(x,s) = (x - i/2) * s + ((i - w)/2)) * s = s (x - i/2 + i/2 + w/2) = s - * (x + w/2) - * - * - * f(x,s) = (x - ((i - w)/2)) * s - * - * @param oldscaling - * - * @param scaling - * - * @param imageDim - * - * @param windowDim - * - * @param offset - * - * @return - */ - /** - * Change to Canvas's scroll position to match the absoluteXPosition - */ - void scrollToAbsolute() { - float scale = getScale(); - try { - scrollTo((int) ((absoluteXPosition + ((float) getWidth() - getImageWidth()) / 2) * scale), - (int) ((absoluteYPosition + ((float) getHeight() - getImageHeight()) / 2) * scale)); - } catch (Exception e) { - Log.v("VNC", "Error: " + e.getMessage()); - } - } - - /** - * Make sure mouse is visible on displayable part of screen - */ - void panToMouse() { - if (!connection.getFollowMouse()) { - return; - } - - if (scaling != null && !scaling.isAbleToPan()) { - return; - } - - int x = mouseX; - int y = mouseY; - boolean panned = false; - int w = getVisibleWidth(); - int h = getVisibleHeight(); - int iw = getImageWidth(); - int ih = getImageHeight(); - - int newX = absoluteXPosition; - int newY = absoluteYPosition; - - if (x - newX >= w - 5) { - newX = x - w + 5; - if (newX + w > iw) { - newX = iw - w; - } - } else if (x < newX + 5) { - newX = x - 5; - if (newX < 0) { - newX = 0; - } - } - if (newX != absoluteXPosition) { - absoluteXPosition = newX; - panned = true; - } - if (y - newY >= h - 5) { - newY = y - h + 5; - if (newY + h > ih) { - newY = ih - h; - } - } else if (y < newY + 5) { - newY = y - 5; - if (newY < 0) { - newY = 0; - } - } - if (newY != absoluteYPosition) { - absoluteYPosition = newY; - panned = true; - } - if (panned) { - scrollToAbsolute(); - } - } - - /** - * Pan by a number of pixels (relative pan) - * - * @param dX - * @param dY - * @return True if the pan changed the view (did not move view out of - * bounds); false otherwise - */ - boolean pan(int dX, int dY) { - - double scale = getScale(); - - double sX = (double) dX / scale; - double sY = (double) dY / scale; - - if (absoluteXPosition + sX < 0) // dX = diff to 0 - { - sX = -absoluteXPosition; - } - if (absoluteYPosition + sY < 0) { - sY = -absoluteYPosition; - } - - // Prevent panning right or below desktop image - - Point outSize = new Point(); - int height = 0; - int width = 0; - VncCanvasActivity.display.getSize(outSize); - height = outSize.y; - width = outSize.x; - - if (absoluteXPosition + getVisibleWidth() + sX > getImageWidth()) { - sX = getImageWidth() - getVisibleWidth() - absoluteXPosition; - } - if (absoluteYPosition + getVisibleHeight() + sY > getImageHeight() + height * .6) { - sY = getImageHeight() + height * .6 - getVisibleHeight() - absoluteYPosition; - } - - absoluteXPosition += sX; - absoluteYPosition += sY; - if (sX != 0.0 || sY != 0.0) { - scrollToAbsolute(); - return true; - } - return false; - } - - /* - * (non-Javadoc) - * - * @see android.view.View#onScrollChanged(int, int, int, int) - */ - @Override - protected void onScrollChanged(int l, int t, int oldl, int oldt) { - super.onScrollChanged(l, t, oldl, oldt); - bitmapData.scrollChanged(absoluteXPosition, absoluteYPosition); - mouseFollowPan(); - } - - void handleRawRect(int x, int y, int w, int h) throws IOException { - handleRawRect(x, y, w, h, true); - } - - byte[] handleRawRectBuffer = new byte[128]; - - void handleRawRect(int x, int y, int w, int h, boolean paint) throws IOException { - boolean valid = bitmapData.validDraw(x, y, w, h); - int[] pixels = bitmapData.bitmapPixels; - if (bytesPerPixel == 1) { - // 1 byte per pixel. Use palette lookup table. - if (w > handleRawRectBuffer.length) { - handleRawRectBuffer = new byte[w]; - } - int i, offset; - for (int dy = y; dy < y + h; dy++) { - rfb.readFully(handleRawRectBuffer, 0, w); - if (!valid) { - continue; - } - offset = bitmapData.offset(x, dy); - for (i = 0; i < w; i++) { - pixels[offset + i] = colorPalette[0xFF & handleRawRectBuffer[i]]; - } - } - } else { - // 4 bytes per pixel (argb) 24-bit color - - final int l = w * 4; - if (l > handleRawRectBuffer.length) { - handleRawRectBuffer = new byte[l]; - } - int i, offset; - for (int dy = y; dy < y + h; dy++) { - rfb.readFully(handleRawRectBuffer, 0, l); - if (!valid) { - continue; - } - offset = bitmapData.offset(x, dy); - for (i = 0; i < w; i++) { - final int idx = i * 4; - pixels[offset + i] = // 0xFF << 24 | - (handleRawRectBuffer[idx + 2] & 0xff) << 16 | (handleRawRectBuffer[idx + 1] & 0xff) << 8 - | (handleRawRectBuffer[idx] & 0xff); - } - } - } - - if (!valid) { - return; - } - - bitmapData.updateBitmap(x, y, w, h); - - if (paint) { - reDraw(); - } - } - - private Runnable reDraw = new Runnable() { - public void run() { - if (showDesktopInfo) { - // Show a Toast with the desktop info on first frame draw. - showDesktopInfo = false; - showConnectionInfo(); - } - if (bitmapData != null) { - bitmapData.updateView(VncCanvas.this); - } - } - }; - - private void reDraw() { - if (repaintsEnabled) { - handler.post(reDraw); - } - } - - public void disableRepaints() { - repaintsEnabled = false; - } - - public void enableRepaints() { - repaintsEnabled = true; - } - - public void showConnectionInfo() { - String msg = rfb.desktopName; - int idx = rfb.desktopName.indexOf("("); - if (idx > -1) { - // Breakup actual desktop name from IP addresses for improved - // readability - String dn = rfb.desktopName.substring(0, idx).trim(); - String ip = rfb.desktopName.substring(idx).trim(); - msg = dn + "\n" + ip; - } - msg += "\n" + rfb.framebufferWidth + "x" + rfb.framebufferHeight; - String enc = getEncoding(); - // Encoding might not be set when we display this message - if (enc != null && !enc.equals("")) { - msg += ", " + getEncoding() + " encoding, " + colorModel.toString(); - } else { - msg += ", " + colorModel.toString(); - } - // Toast.makeText(getContext(), msg, Toast.LENGTH_LONG).show(); - } - - private String getEncoding() { - switch (preferredEncoding) { - case RfbProto.EncodingRaw: - return "RAW"; - case RfbProto.EncodingTight: - return "TIGHT"; - case RfbProto.EncodingCoRRE: - return "CoRRE"; - case RfbProto.EncodingHextile: - return "HEXTILE"; - case RfbProto.EncodingRRE: - return "RRE"; - case RfbProto.EncodingZlib: - return "ZLIB"; - case RfbProto.EncodingZRLE: - return "ZRLE"; - } - return ""; - } - - // Useful shortcuts for modifier masks. - final static int CTRL_MASK = KeyEvent.META_SYM_ON; - final static int SHIFT_MASK = KeyEvent.META_SHIFT_ON; - final static int META_MASK = 0; - final static int ALT_MASK = KeyEvent.META_ALT_ON; - private static final int MOUSE_BUTTON_NONE = 0; - static final int MOUSE_BUTTON_LEFT = 1; - static final int MOUSE_BUTTON_MIDDLE = 2; - static final int MOUSE_BUTTON_RIGHT = 4; - static final int MOUSE_BUTTON_SCROLL_UP = 8; - static final int MOUSE_BUTTON_SCROLL_DOWN = 16; - /** - * Current state of "mouse" buttons Alt meta means use second mouse button 0 - * = none 1 = default button 2 = second button - */ - private int pointerMask = MOUSE_BUTTON_NONE; - private boolean ALT_PRESSED = false; - private boolean CTRL_PRESSED = false; - - /** - * Convert a motion event to a format suitable for sending over the wire - * - * @param evt - * motion event; x and y must already have been converted from - * screen coordinates to remote frame buffer coordinates. - * cameraButton flag is interpreted as second mouse button - * @param downEvent - * True if "mouse button" (touch or trackball button) is down - * when this happens - * @return true if event was actually sent - */ - public boolean processPointerEvent(MotionEvent evt, boolean downEvent) { - return processPointerEvent(evt, downEvent, cameraButtonDown); - } - - /** - * Convert a motion event to a format suitable for sending over the wire - * - * @param evt - * motion event; x and y must already have been converted from - * screen coordinates to remote frame buffer coordinates. - * @param downEvent - * True if "mouse button" (touch or trackball button) is down - * when this happens - * @param useRightButton - * If true, event is interpreted as happening with right mouse - * button - * @return true if event was actually sent - */ - public boolean processPointerEvent(MotionEvent evt, boolean downEvent, boolean useRightButton) { - boolean useMiddleButton = false; - - if(evt.getButtonState() == MotionEvent.BUTTON_SECONDARY){ - useRightButton = true; - } else if(evt.getButtonState() == MotionEvent.BUTTON_TERTIARY){ - useMiddleButton = true; - } - - //XXX: not reliable with laptop trackpads -// if(Config.mouseMode == Config.MouseMode.External -// && MotionEvent.TOOL_TYPE_FINGER == evt.getToolType(0)) -// return true; -// -// if(Config.mouseMode == Config.MouseMode.Trackpad -// && MotionEvent.TOOL_TYPE_MOUSE == evt.getToolType(0)) -// return true; - - return processPointerEvent((int) evt.getX(), (int) evt.getY(), evt.getAction(), evt.getMetaState(), downEvent, - useRightButton, useMiddleButton, false); - } - - boolean processPointerEvent(int x, int y, int action, - int modifiers, boolean mouseIsDown, boolean useRightButton, - boolean useMiddleButton, boolean scrollUp) { - //Log.v("Limbo", "processPointerEvent: " + x + ", " + y + ", " - // + action + ", " + modifiers + ", " + mouseIsDown + ", " - // + useRightButton + ", " + useMiddleButton + ", " + scrollUp - //); - - if (rfb != null && rfb.inNormalProtocol) { - if (action == MotionEvent.ACTION_DOWN || (mouseIsDown && action == MotionEvent.ACTION_MOVE)) { - if (useRightButton) { - // Log.v("Limbo", "Right Button Down"); - pointerMask |= MOUSE_BUTTON_RIGHT; - } else if (useMiddleButton) { - pointerMask |= MOUSE_BUTTON_MIDDLE; - }else { - //Log.v("Limbo", "Left Button Down: x=" + x + ", y=" + y); - pointerMask |= MOUSE_BUTTON_LEFT; - } - } else if (action == MotionEvent.ACTION_SCROLL) { - // Log.v("Limbo", "Button Up"); - if(scrollUp) - pointerMask |= MOUSE_BUTTON_SCROLL_UP; - else - pointerMask |= MOUSE_BUTTON_SCROLL_DOWN; - } else if (action == MotionEvent.ACTION_UP) { - // Log.v("Limbo", "Button Up"); - //pointerMask = 0; - if (useRightButton) { - // Log.v("Limbo", "Right Button Down"); - pointerMask &= ~MOUSE_BUTTON_RIGHT; - } else if (useMiddleButton) { - pointerMask &= ~MOUSE_BUTTON_MIDDLE; - }else { - //Log.v("Limbo", "Left Button Down: x=" + x + ", y=" + y); - //XXX: Mouse middle click cannot always be detected so we - // reset all buttons (left, middle, click) to be safe - pointerMask = 0; - } - } - bitmapData.invalidateMousePosition(); - mouseX = x; - mouseY = y; - if (mouseX < 0) { - mouseX = 0; - } else if (mouseX >= rfb.framebufferWidth) { - mouseX = rfb.framebufferWidth - 1; - } - if (mouseY < 0) { - mouseY = 0; - } else if (mouseY >= rfb.framebufferHeight) { - mouseY = rfb.framebufferHeight - 1; - } - bitmapData.invalidateMousePosition(); - try { - rfb.writePointerEvent(mouseX, mouseY, modifiers, pointerMask); - if (action == MotionEvent.ACTION_SCROLL) { - rfb.writePointerEvent(mouseX, mouseY, 0, 0); - pointerMask = 0; - } - } catch (Exception e) { - e.printStackTrace(); - } - panToMouse(); - return true; - } - - return false; - } - - private int isSpecialKey(int key) { - switch (key) { - case '!': - return '1'; - case '@': - return '2'; - case '#': - return '3'; - case '$': - return '4'; - case '%': - return '5'; - case '^': - return '6'; - case '&': - return '7'; - case '*': - return '8'; - case '(': - return '9'; - case ')': - return '0'; - case '_': - return '-'; - case '+': - return '='; - case '~': - return '`'; - case '{': - return '['; - case '}': - return ']'; - case '|': - return '\\'; - case '\"': - return '\''; - case ':': - return ';'; - case '<': - return ','; - case '>': - return '.'; - case '?': - return '/'; - default: - return -1; - - } } - - /** - * Moves the scroll while the volume key is held down - * - * @author Michael A. MacDonald - */ - class MouseScrollRunnable implements Runnable { - - int delay = 100; - int scrollButton = 0; - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - try { - rfb.writePointerEvent(mouseX, mouseY, 0, scrollButton); - rfb.writePointerEvent(mouseX, mouseY, 0, 0); - - handler.postDelayed(this, delay); - } catch (IOException ioe) { - } - } - } - - public synchronized boolean processLocalKeyEvent(int keyCode, KeyEvent evt) { - if (keyCode == KeyEvent.KEYCODE_MENU) // Ignore menu key - { - return true; - } - if (keyCode == KeyEvent.KEYCODE_CAMERA) { - cameraButtonDown = (evt.getAction() != KeyEvent.ACTION_UP); - } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { - int mouseChange = keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ? MOUSE_BUTTON_SCROLL_DOWN - : MOUSE_BUTTON_SCROLL_UP; - if (evt.getAction() == KeyEvent.ACTION_DOWN) { - // If not auto-repeat - if (scrollRunnable.scrollButton != mouseChange) { - pointerMask |= mouseChange; - scrollRunnable.scrollButton = mouseChange; - handler.postDelayed(scrollRunnable, 200); - } - } else { - handler.removeCallbacks(scrollRunnable); - scrollRunnable.scrollButton = 0; - pointerMask &= ~mouseChange; - } - try { - rfb.writePointerEvent(mouseX, mouseY, evt.getMetaState(), pointerMask); - } catch (IOException ioe) { - // TODO: do something with exception - } - return true; - } - if (rfb != null && rfb.inNormalProtocol) { - boolean down = (evt.getAction() == KeyEvent.ACTION_DOWN); - int key; - int metaState = evt.getMetaState(); - metaState = 0; - // Log.v("Key Pressed", keyCode + ", metaState = " + metaState); - - switch (keyCode) { - case KeyEvent.KEYCODE_BACK: - // key = 0xff1b; - return false; - // break; - case KeyEvent.KEYCODE_DPAD_LEFT: - key = 0xff51; - break; - case KeyEvent.KEYCODE_DPAD_UP: - key = 0xff52; - break; - case KeyEvent.KEYCODE_DPAD_RIGHT: - key = 0xff53; - break; - case KeyEvent.KEYCODE_DPAD_DOWN: - key = 0xff54; - break; - case KeyEvent.KEYCODE_DEL: - key = 0xff08; - break; - case KeyEvent.KEYCODE_FORWARD_DEL: - key = MetaKeyBean.keysByKeyCode.get(KeyEvent.KEYCODE_DEL).keySym; - break; - case KeyEvent.KEYCODE_ALT_LEFT: - case KeyEvent.KEYCODE_ALT_RIGHT: - this.ALT_PRESSED = true; - return true; - case KeyEvent.KEYCODE_MOVE_HOME: - key = 0xFF50; - break; - case KeyEvent.KEYCODE_INSERT: - key = 0xFF63; - break; - case KeyEvent.KEYCODE_MOVE_END: - key = 0xFF57; - break; - case KeyEvent.KEYCODE_PAGE_DOWN: - key = 0xFF56; - break; - case KeyEvent.KEYCODE_PAGE_UP: - key = 0xFF55; - break; - case KeyEvent.KEYCODE_ENTER: - key = 0xff0d; - break; - case KeyEvent.KEYCODE_DPAD_CENTER: - key = 0xff0d; - break; - case KeyEvent.KEYCODE_TAB: - key = 0xFF09; - break; - case 111: // ESCAPE - key = 0xff1b; - break; - default: - key = evt.getUnicodeChar(); - //Log.v("unicode", "Unicode Char for " + evt.getKeyCode() + " is " + key); - - //ΧΧΧ: Workaround for some chars not recognized by QEMU - int specialKey = isSpecialKey(key); - if (specialKey != -1) { - key = specialKey; - metaState = metaState | VncCanvas.SHIFT_MASK; - } else if (keyCode >= 131 && keyCode <= 142) { - // Function Key pressed - key = 0xFFBE + keyCode - 131; - } else if (key == 0){ - //Key is a meta combination or unknown - key = evt.getUnicodeChar(0); - } - - break; - } - - if ((evt.getMetaState() & KeyEvent.META_CTRL_ON) == KeyEvent.META_CTRL_ON) { - // Log.v("meta", "setting ctrl mask"); - metaState = metaState | VncCanvas.CTRL_MASK; - } - - if ((evt.getMetaState() & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON || this.ALT_PRESSED) { - // Log.v("meta", "setting alt mask"); - metaState = metaState | VncCanvas.ALT_MASK; - } - - if ((evt.getMetaState() & KeyEvent.META_SHIFT_ON) == KeyEvent.META_SHIFT_ON) { - // Log.v("meta", "setting shift mask"); - metaState = metaState | VncCanvas.SHIFT_MASK; - } - try { - if (afterMenu) { - afterMenu = false; - if (!down && key != lastKeyDown) { - return true; - } - } - if (down) { - lastKeyDown = key; - } - - rfb.writeKeyEvent(key, metaState, down); - this.ALT_PRESSED = false; - } catch (Exception e) { - e.printStackTrace(); - } - return true; - } - return false; - } - - public void closeConnection() { - maintainConnection = false; - } - - public void sendMetaKey1(int key, int flags) { - try { - rfb.writeKeyEvent(key, flags, true); - rfb.writeKeyEvent(key, flags, false); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - - } - - public void sendText(String s) { - int l = s.length(); - for (int i = 0; i < l; i++) { - char c = s.charAt(i); - int meta = 0; - int keysym = c; - if (Character.isISOControl(c)) { - if (c == '\n') { - keysym = MetaKeyBean.keysByKeyCode.get(KeyEvent.KEYCODE_ENTER).keySym; - } else { - continue; - } - } - try { - rfb.writeKeyEvent(keysym, meta, true); - rfb.writeKeyEvent(keysym, meta, false); - } catch (IOException ioe) { - // TODO: log this - } - } - } - - void sendMetaKey(MetaKeyBean meta) { - if (meta.isMouseClick()) { - try { - rfb.writePointerEvent(mouseX, mouseY, meta.getMetaFlags(), meta.getMouseButtons()); - rfb.writePointerEvent(mouseX, mouseY, meta.getMetaFlags(), 0); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } else { - try { - rfb.writeKeyEvent(meta.getKeySym(), meta.getMetaFlags(), true); - rfb.writeKeyEvent(meta.getKeySym(), meta.getMetaFlags(), false); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - } - - float getScale() { - if (scaling == null) { - return 1; - } - return scaling.getScale(); - } - - public int getVisibleWidth() { - return (int) ((double) getWidth() / getScale() + 0.5); - } - - public int getVisibleHeight() { - return (int) ((double) getHeight() / getScale() + 0.5); - } - - public int getImageWidth() { - return bitmapData.framebufferwidth; - } - - public int getImageHeight() { - return bitmapData.framebufferheight; - } - - public int getCenteredXOffset() { - int xoffset = (bitmapData.framebufferwidth - getWidth()) / 2; - return xoffset; - } - - public int getCenteredYOffset() { - int yoffset = (bitmapData.framebufferheight - getHeight()) / 2; - return yoffset; - } - - /** - * Additional Encodings - * - */ - private void setEncodings(boolean autoSelectOnly) { - if (rfb == null || !rfb.inNormalProtocol) { - return; - } - - if (preferredEncoding == -1) { - // Preferred format is ZRLE - preferredEncoding = RfbProto.EncodingZRLE; - } else { - // Auto encoder selection is not enabled. - if (autoSelectOnly) { - return; - } - } - - int[] encodings = new int[20]; - int nEncodings = 0; - - encodings[nEncodings++] = preferredEncoding; - if (useCopyRect) { - encodings[nEncodings++] = RfbProto.EncodingCopyRect; - } - // if (preferredEncoding != RfbProto.EncodingTight) - // encodings[nEncodings++] = RfbProto.EncodingTight; - if (preferredEncoding != RfbProto.EncodingZRLE) { - encodings[nEncodings++] = RfbProto.EncodingZRLE; - } - if (preferredEncoding != RfbProto.EncodingHextile) { - encodings[nEncodings++] = RfbProto.EncodingHextile; - } - if (preferredEncoding != RfbProto.EncodingZlib) { - encodings[nEncodings++] = RfbProto.EncodingZlib; - } - if (preferredEncoding != RfbProto.EncodingCoRRE) { - encodings[nEncodings++] = RfbProto.EncodingCoRRE; - } - if (preferredEncoding != RfbProto.EncodingRRE) { - encodings[nEncodings++] = RfbProto.EncodingRRE; - } - - if (compressLevel >= 0 && compressLevel <= 9) { - encodings[nEncodings++] = RfbProto.EncodingCompressLevel0 + compressLevel; - } - if (jpegQuality >= 0 && jpegQuality <= 9) { - encodings[nEncodings++] = RfbProto.EncodingQualityLevel0 + jpegQuality; - } - - if (requestCursorUpdates) { - encodings[nEncodings++] = RfbProto.EncodingXCursor; - encodings[nEncodings++] = RfbProto.EncodingRichCursor; - if (!ignoreCursorUpdates) { - encodings[nEncodings++] = RfbProto.EncodingPointerPos; - } - } - - encodings[nEncodings++] = RfbProto.EncodingLastRect; - encodings[nEncodings++] = RfbProto.EncodingNewFBSize; - - boolean encodingsWereChanged = false; - if (nEncodings != nEncodingsSaved) { - encodingsWereChanged = true; - } else { - for (int i = 0; i < nEncodings; i++) { - if (encodings[i] != encodingsSaved[i]) { - encodingsWereChanged = true; - break; - } - } - } - - if (encodingsWereChanged) { - try { - rfb.writeSetEncodings(encodings, nEncodings); - } catch (Exception e) { - e.printStackTrace(); - } - encodingsSaved = encodings; - nEncodingsSaved = nEncodings; - } - } - - // - // Handle a CopyRect rectangle. - // - final Paint handleCopyRectPaint = new Paint(); - - private void handleCopyRect(int x, int y, int w, int h) throws IOException { - - /** - * This does not work properly yet. - */ - rfb.readCopyRect(); - if (!bitmapData.validDraw(x, y, w, h)) { - return; - } - // Source Coordinates - int leftSrc = rfb.copyRectSrcX; - int topSrc = rfb.copyRectSrcY; - int rightSrc = topSrc + w; - int bottomSrc = topSrc + h; - - // Change - int dx = x - rfb.copyRectSrcX; - int dy = y - rfb.copyRectSrcY; - - // Destination Coordinates - int leftDest = leftSrc + dx; - int topDest = topSrc + dy; - int rightDest = rightSrc + dx; - int bottomDest = bottomSrc + dy; - - bitmapData.copyRect(new Rect(leftSrc, topSrc, rightSrc, bottomSrc), - new Rect(leftDest, topDest, rightDest, bottomDest), handleCopyRectPaint); - - reDraw(); - } - - byte[] bg_buf = new byte[4]; - byte[] rre_buf = new byte[128]; - - // - // Handle an RRE-encoded rectangle. - // - - private void handleRRERect(int x, int y, int w, int h) throws IOException { - boolean valid = bitmapData.validDraw(x, y, w, h); - int nSubrects = rfb.is.readInt(); - - rfb.readFully(bg_buf, 0, bytesPerPixel); - int pixel; - if (bytesPerPixel == 1) { - pixel = colorPalette[0xFF & bg_buf[0]]; - } else { - pixel = Color.rgb(bg_buf[2] & 0xFF, bg_buf[1] & 0xFF, bg_buf[0] & 0xFF); - } - handleRREPaint.setColor(pixel); - if (valid) { - bitmapData.drawRect(x, y, w, h, handleRREPaint); - } - - int len = nSubrects * (bytesPerPixel + 8); - if (len > rre_buf.length) { - rre_buf = new byte[len]; - } - - rfb.readFully(rre_buf, 0, len); - if (!valid) { - return; - } - - int sx, sy, sw, sh; - - int i = 0; - for (int j = 0; j < nSubrects; j++) { - if (bytesPerPixel == 1) { - pixel = colorPalette[0xFF & rre_buf[i++]]; - } else { - pixel = Color.rgb(rre_buf[i + 2] & 0xFF, rre_buf[i + 1] & 0xFF, rre_buf[i] & 0xFF); - i += 4; - } - sx = x + ((rre_buf[i] & 0xff) << 8) + (rre_buf[i + 1] & 0xff); - i += 2; - sy = y + ((rre_buf[i] & 0xff) << 8) + (rre_buf[i + 1] & 0xff); - i += 2; - sw = ((rre_buf[i] & 0xff) << 8) + (rre_buf[i + 1] & 0xff); - i += 2; - sh = ((rre_buf[i] & 0xff) << 8) + (rre_buf[i + 1] & 0xff); - i += 2; - - handleRREPaint.setColor(pixel); - bitmapData.drawRect(sx, sy, sw, sh, handleRREPaint); - } - - reDraw(); - } - - // - // Handle a CoRRE-encoded rectangle. - // - private void handleCoRRERect(int x, int y, int w, int h) throws IOException { - boolean valid = bitmapData.validDraw(x, y, w, h); - int nSubrects = rfb.is.readInt(); - - rfb.readFully(bg_buf, 0, bytesPerPixel); - int pixel; - if (bytesPerPixel == 1) { - pixel = colorPalette[0xFF & bg_buf[0]]; - } else { - pixel = Color.rgb(bg_buf[2] & 0xFF, bg_buf[1] & 0xFF, bg_buf[0] & 0xFF); - } - handleRREPaint.setColor(pixel); - if (valid) { - bitmapData.drawRect(x, y, w, h, handleRREPaint); - } - - int len = nSubrects * (bytesPerPixel + 8); - if (len > rre_buf.length) { - rre_buf = new byte[len]; - } - - rfb.readFully(rre_buf, 0, len); - if (!valid) { - return; - } - - int sx, sy, sw, sh; - int i = 0; - - for (int j = 0; j < nSubrects; j++) { - if (bytesPerPixel == 1) { - pixel = colorPalette[0xFF & rre_buf[i++]]; - } else { - pixel = Color.rgb(rre_buf[i + 2] & 0xFF, rre_buf[i + 1] & 0xFF, rre_buf[i] & 0xFF); - i += 4; - } - sx = x + (rre_buf[i++] & 0xFF); - sy = y + (rre_buf[i++] & 0xFF); - sw = rre_buf[i++] & 0xFF; - sh = rre_buf[i++] & 0xFF; - - handleRREPaint.setColor(pixel); - bitmapData.drawRect(sx, sy, sw, sh, handleRREPaint); - } - - reDraw(); - } - - // - // Handle a Hextile-encoded rectangle. - // - // These colors should be kept between handleHextileSubrect() calls. - private int hextile_bg, hextile_fg; - - private void handleHextileRect(int x, int y, int w, int h) throws IOException { - - hextile_bg = Color.BLACK; - hextile_fg = Color.BLACK; - - for (int ty = y; ty < y + h; ty += 16) { - int th = 16; - if (y + h - ty < 16) { - th = y + h - ty; - } - - for (int tx = x; tx < x + w; tx += 16) { - int tw = 16; - if (x + w - tx < 16) { - tw = x + w - tx; - } - - handleHextileSubrect(tx, ty, tw, th); - } - - // Finished with a row of tiles, now let's show it. - reDraw(); - } - } - - // - // Handle one tile in the Hextile-encoded data. - // - Paint handleHextileSubrectPaint = new Paint(); - byte[] backgroundColorBuffer = new byte[4]; - - private void handleHextileSubrect(int tx, int ty, int tw, int th) throws IOException { - - int subencoding = rfb.is.readUnsignedByte(); - - // Is it a raw-encoded sub-rectangle? - if ((subencoding & RfbProto.HextileRaw) != 0) { - handleRawRect(tx, ty, tw, th, false); - return; - } - - boolean valid = bitmapData.validDraw(tx, ty, tw, th); - // Read and draw the background if specified. - if (bytesPerPixel > backgroundColorBuffer.length) { - throw new RuntimeException("impossible colordepth"); - } - if ((subencoding & RfbProto.HextileBackgroundSpecified) != 0) { - rfb.readFully(backgroundColorBuffer, 0, bytesPerPixel); - if (bytesPerPixel == 1) { - hextile_bg = colorPalette[0xFF & backgroundColorBuffer[0]]; - } else { - hextile_bg = Color.rgb(backgroundColorBuffer[2] & 0xFF, backgroundColorBuffer[1] & 0xFF, - backgroundColorBuffer[0] & 0xFF); - } - } - handleHextileSubrectPaint.setColor(hextile_bg); - handleHextileSubrectPaint.setStyle(Paint.Style.FILL); - if (valid) { - bitmapData.drawRect(tx, ty, tw, th, handleHextileSubrectPaint); - } - - // Read the foreground color if specified. - if ((subencoding & RfbProto.HextileForegroundSpecified) != 0) { - rfb.readFully(backgroundColorBuffer, 0, bytesPerPixel); - if (bytesPerPixel == 1) { - hextile_fg = colorPalette[0xFF & backgroundColorBuffer[0]]; - } else { - hextile_fg = Color.rgb(backgroundColorBuffer[2] & 0xFF, backgroundColorBuffer[1] & 0xFF, - backgroundColorBuffer[0] & 0xFF); - } - } - - // Done with this tile if there is no sub-rectangles. - if ((subencoding & RfbProto.HextileAnySubrects) == 0) { - return; - } - - int nSubrects = rfb.is.readUnsignedByte(); - int bufsize = nSubrects * 2; - if ((subencoding & RfbProto.HextileSubrectsColoured) != 0) { - bufsize += nSubrects * bytesPerPixel; - } - if (rre_buf.length < bufsize) { - rre_buf = new byte[bufsize]; - } - rfb.readFully(rre_buf, 0, bufsize); - - int b1, b2, sx, sy, sw, sh; - int i = 0; - if ((subencoding & RfbProto.HextileSubrectsColoured) == 0) { - - // Sub-rectangles are all of the same color. - handleHextileSubrectPaint.setColor(hextile_fg); - for (int j = 0; j < nSubrects; j++) { - b1 = rre_buf[i++] & 0xFF; - b2 = rre_buf[i++] & 0xFF; - sx = tx + (b1 >> 4); - sy = ty + (b1 & 0xf); - sw = (b2 >> 4) + 1; - sh = (b2 & 0xf) + 1; - if (valid) { - bitmapData.drawRect(sx, sy, sw, sh, handleHextileSubrectPaint); - } - } - } else if (bytesPerPixel == 1) { - - // BGR233 (8-bit color) version for colored sub-rectangles. - for (int j = 0; j < nSubrects; j++) { - hextile_fg = colorPalette[0xFF & rre_buf[i++]]; - b1 = rre_buf[i++] & 0xFF; - b2 = rre_buf[i++] & 0xFF; - sx = tx + (b1 >> 4); - sy = ty + (b1 & 0xf); - sw = (b2 >> 4) + 1; - sh = (b2 & 0xf) + 1; - handleHextileSubrectPaint.setColor(hextile_fg); - if (valid) { - bitmapData.drawRect(sx, sy, sw, sh, handleHextileSubrectPaint); - } - } - - } else { - - // Full-color (24-bit) version for colored sub-rectangles. - for (int j = 0; j < nSubrects; j++) { - hextile_fg = Color.rgb(rre_buf[i + 2] & 0xFF, rre_buf[i + 1] & 0xFF, rre_buf[i] & 0xFF); - i += 4; - b1 = rre_buf[i++] & 0xFF; - b2 = rre_buf[i++] & 0xFF; - sx = tx + (b1 >> 4); - sy = ty + (b1 & 0xf); - sw = (b2 >> 4) + 1; - sh = (b2 & 0xf) + 1; - handleHextileSubrectPaint.setColor(hextile_fg); - if (valid) { - bitmapData.drawRect(sx, sy, sw, sh, handleHextileSubrectPaint); - } - } - - } - } - - // - // Handle a ZRLE-encoded rectangle. - // - Paint handleZRLERectPaint = new Paint(); - int[] handleZRLERectPalette = new int[128]; - - private void handleZRLERect(int x, int y, int w, int h) throws Exception { - - if (zrleInStream == null) { - zrleInStream = new ZlibInStream(); - } - - int nBytes = rfb.is.readInt(); - if (nBytes > 64 * 1024 * 1024) { - throw new Exception("ZRLE decoder: illegal compressed data size"); - } - - if (zrleBuf == null || zrleBuf.length < nBytes) { - zrleBuf = new byte[nBytes + 4096]; - } - - rfb.readFully(zrleBuf, 0, nBytes); - - zrleInStream.setUnderlying(new MemInStream(zrleBuf, 0, nBytes), nBytes); - - boolean valid = bitmapData.validDraw(x, y, w, h); - - for (int ty = y; ty < y + h; ty += 64) { - - int th = Math.min(y + h - ty, 64); - - for (int tx = x; tx < x + w; tx += 64) { - - int tw = Math.min(x + w - tx, 64); - - int mode = zrleInStream.readU8(); - boolean rle = (mode & 128) != 0; - int palSize = mode & 127; - - readZrlePalette(handleZRLERectPalette, palSize); - - if (palSize == 1) { - int pix = handleZRLERectPalette[0]; - int c = (bytesPerPixel == 1) ? colorPalette[0xFF & pix] : (0xFF000000 | pix); - handleZRLERectPaint.setColor(c); - handleZRLERectPaint.setStyle(Paint.Style.FILL); - if (valid) { - bitmapData.drawRect(tx, ty, tw, th, handleZRLERectPaint); - } - continue; - } - - if (!rle) { - if (palSize == 0) { - readZrleRawPixels(tw, th); - } else { - readZrlePackedPixels(tw, th, handleZRLERectPalette, palSize); - } - } else { - if (palSize == 0) { - readZrlePlainRLEPixels(tw, th); - } else { - readZrlePackedRLEPixels(tw, th, handleZRLERectPalette); - } - } - if (valid) { - handleUpdatedZrleTile(tx, ty, tw, th); - } - } - } - - zrleInStream.reset(); - - reDraw(); - } - - // - // Handle a Zlib-encoded rectangle. - // - byte[] handleZlibRectBuffer = new byte[128]; - - private void handleZlibRect(int x, int y, int w, int h) throws Exception { - boolean valid = bitmapData.validDraw(x, y, w, h); - int nBytes = rfb.is.readInt(); - - if (zlibBuf == null || zlibBuf.length < nBytes) { - zlibBuf = new byte[nBytes * 2]; - } - - rfb.readFully(zlibBuf, 0, nBytes); - - if (zlibInflater == null) { - zlibInflater = new Inflater(); - } - zlibInflater.setInput(zlibBuf, 0, nBytes); - - int[] pixels = bitmapData.bitmapPixels; - - if (bytesPerPixel == 1) { - // 1 byte per pixel. Use palette lookup table. - if (w > handleZlibRectBuffer.length) { - handleZlibRectBuffer = new byte[w]; - } - int i, offset; - for (int dy = y; dy < y + h; dy++) { - zlibInflater.inflate(handleZlibRectBuffer, 0, w); - if (!valid) { - continue; - } - offset = bitmapData.offset(x, dy); - for (i = 0; i < w; i++) { - pixels[offset + i] = colorPalette[0xFF & handleZlibRectBuffer[i]]; - } - } - } else { - // 24-bit color (ARGB) 4 bytes per pixel. - final int l = w * 4; - if (l > handleZlibRectBuffer.length) { - handleZlibRectBuffer = new byte[l]; - } - int i, offset; - for (int dy = y; dy < y + h; dy++) { - zlibInflater.inflate(handleZlibRectBuffer, 0, l); - if (!valid) { - continue; - } - offset = bitmapData.offset(x, dy); - for (i = 0; i < w; i++) { - final int idx = i * 4; - pixels[offset + i] = (handleZlibRectBuffer[idx + 2] & 0xFF) << 16 - | (handleZlibRectBuffer[idx + 1] & 0xFF) << 8 | (handleZlibRectBuffer[idx] & 0xFF); - } - } - } - if (!valid) { - return; - } - bitmapData.updateBitmap(x, y, w, h); - - reDraw(); - } - - private int readPixel(InStream is) throws Exception { - int pix; - if (bytesPerPixel == 1) { - pix = is.readU8(); - } else { - int p1 = is.readU8(); - int p2 = is.readU8(); - int p3 = is.readU8(); - pix = (p3 & 0xFF) << 16 | (p2 & 0xFF) << 8 | (p1 & 0xFF); - } - return pix; - } - - byte[] readPixelsBuffer = new byte[128]; - - private void readPixels(InStream is, int[] dst, int count) throws Exception { - if (bytesPerPixel == 1) { - if (count > readPixelsBuffer.length) { - readPixelsBuffer = new byte[count]; - } - is.readBytes(readPixelsBuffer, 0, count); - for (int i = 0; i < count; i++) { - dst[i] = (int) readPixelsBuffer[i] & 0xFF; - } - } else { - final int l = count * 3; - if (l > readPixelsBuffer.length) { - readPixelsBuffer = new byte[l]; - } - is.readBytes(readPixelsBuffer, 0, l); - for (int i = 0; i < count; i++) { - final int idx = i * 3; - dst[i] = ((readPixelsBuffer[idx + 2] & 0xFF) << 16 | (readPixelsBuffer[idx + 1] & 0xFF) << 8 - | (readPixelsBuffer[idx] & 0xFF)); - } - } - } - - private void readZrlePalette(int[] palette, int palSize) throws Exception { - readPixels(zrleInStream, palette, palSize); - } - - private void readZrleRawPixels(int tw, int th) throws Exception { - int len = tw * th; - if (zrleTilePixels == null || len > zrleTilePixels.length) { - zrleTilePixels = new int[len]; - } - readPixels(zrleInStream, zrleTilePixels, tw * th); // / - } - - private void readZrlePackedPixels(int tw, int th, int[] palette, int palSize) throws Exception { - - int bppp = ((palSize > 16) ? 8 : ((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1))); - int ptr = 0; - int len = tw * th; - if (zrleTilePixels == null || len > zrleTilePixels.length) { - zrleTilePixels = new int[len]; - } - - for (int i = 0; i < th; i++) { - int eol = ptr + tw; - int b = 0; - int nbits = 0; - - while (ptr < eol) { - if (nbits == 0) { - b = zrleInStream.readU8(); - nbits = 8; - } - nbits -= bppp; - int index = (b >> nbits) & ((1 << bppp) - 1) & 127; - if (bytesPerPixel == 1) { - if (index >= colorPalette.length) { - Log.e(TAG, "zrlePlainRLEPixels palette lookup out of bounds " + index + " (0x" - + Integer.toHexString(index) + ")"); - } - zrleTilePixels[ptr++] = colorPalette[0xFF & palette[index]]; - } else { - zrleTilePixels[ptr++] = palette[index]; - } - } - } - } - - private void readZrlePlainRLEPixels(int tw, int th) throws Exception { - int ptr = 0; - int end = ptr + tw * th; - if (zrleTilePixels == null || end > zrleTilePixels.length) { - zrleTilePixels = new int[end]; - } - while (ptr < end) { - int pix = readPixel(zrleInStream); - int len = 1; - int b; - do { - b = zrleInStream.readU8(); - len += b; - } while (b == 255); - - if (!(len <= end - ptr)) { - throw new Exception("ZRLE decoder: assertion failed" + " (len <= end-ptr)"); - } - - if (bytesPerPixel == 1) { - while (len-- > 0) { - zrleTilePixels[ptr++] = colorPalette[0xFF & pix]; - } - } else { - while (len-- > 0) { - zrleTilePixels[ptr++] = pix; - } - } - } - } - - private void readZrlePackedRLEPixels(int tw, int th, int[] palette) throws Exception { - - int ptr = 0; - int end = ptr + tw * th; - if (zrleTilePixels == null || end > zrleTilePixels.length) { - zrleTilePixels = new int[end]; - } - while (ptr < end) { - int index = zrleInStream.readU8(); - int len = 1; - if ((index & 128) != 0) { - int b; - do { - b = zrleInStream.readU8(); - len += b; - } while (b == 255); - - if (!(len <= end - ptr)) { - throw new Exception("ZRLE decoder: assertion failed" + " (len <= end - ptr)"); - } - } - - index &= 127; - int pix = palette[index]; - - if (bytesPerPixel == 1) { - while (len-- > 0) { - zrleTilePixels[ptr++] = colorPalette[0xFF & pix]; - } - } else { - while (len-- > 0) { - zrleTilePixels[ptr++] = pix; - } - } - } - } - - // - // Copy pixels from zrleTilePixels8 or zrleTilePixels24, then update. - // - private void handleUpdatedZrleTile(int x, int y, int w, int h) { - int offsetSrc = 0; - int[] destPixels = bitmapData.bitmapPixels; - for (int j = 0; j < h; j++) { - System.arraycopy(zrleTilePixels, offsetSrc, destPixels, bitmapData.offset(x, y + j), w); - offsetSrc += w; - } - - bitmapData.updateBitmap(x, y, w, h); - } - - public void connected() { - VncCanvasActivity activity = (VncCanvasActivity) VncCanvas.this.getContext(); - activity.onConnected(); - - } - - - class VNCOnTouchListener implements View.OnTouchListener { - - @Override - public boolean onTouch(View v, MotionEvent event) { - // TODO Auto-generated method stub - //Log.i("VNCOnTouchListener", "onTouch"); - if(Config.mouseMode == Config.MouseMode.Trackpad) { - return false; - } - return processPointerEvent(event, event.getAction() == MotionEvent.ACTION_DOWN); - } - - - } - - class VNCGenericMotionListener_API12 implements View.OnGenericMotionListener { - private VncCanvas mSurface; - - // Generic Motion (mouse hover, joystick...) events go here - @Override - public boolean onGenericMotion(View v, MotionEvent event) { - float x, y; - int action; - - switch (event.getSource()) { - case InputDevice.SOURCE_JOYSTICK: - case InputDevice.SOURCE_GAMEPAD: - case InputDevice.SOURCE_DPAD: - return true; - case InputDevice.SOURCE_MOUSE: - if(Config.mouseMode == Config.MouseMode.Trackpad) - break; - - action = event.getActionMasked(); - //Log.d("SDL", "onGenericMotion, action = " + action + "," + event.getX() + ", " + event.getY()); - switch (action) { - case MotionEvent.ACTION_SCROLL: - x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0); - y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0); - //Log.d("SDL", "Mouse Scroll: " +event.getX() + ":" + event.getY() + " => " + x + "," + y); - - //TODO: - //SDLActivity.onSDLNativeMouse(0, action, x, y); - //processPointerEvent(event,false); - - // Log.v("Limbo", "Button Up"); - boolean scrollUp=false; - if (y > 0) - scrollUp = true; - else if (y < 0) - scrollUp = false; - - return processPointerEvent((int) event.getX(), (int) event.getY(), event.getAction(), event.getMetaState(), false, - false, false, scrollUp); - //return true; - - case MotionEvent.ACTION_HOVER_MOVE: - if(Config.processMouseHistoricalEvents) { - final int historySize = event.getHistorySize(); - for (int h = 0; h < historySize; h++) { - float ex = event.getHistoricalX(h); - float ey = event.getHistoricalY(h); - float ep = event.getHistoricalPressure(h); - processHoverMouse(event, ex, ey, ep, action); - } - } - - float ex = event.getX(); - float ey = event.getY(); - float ep = event.getPressure(); - processHoverMouse(event, ex, ey, ep, action); - return true; - - case MotionEvent.ACTION_UP: - - default: - break; - } - break; - - default: - break; - } - - // Event was not managed - return false; - } - - private void processHoverMouse(MotionEvent event, float x,float y,float p, int action) { - - //Log.d("VncCanvas", "Mouse Hover: " + x + "," + y); - - if(Config.mouseMode == Config.MouseMode.External) { - -// float x_margin = (SDLActivity.width - LimboSDLActivity.vm_width * LimboSDLActivity.height / (float) LimboSDLActivity.vm_height) / 2; -// if (x < x_margin) { -// return; -// } else if (x > SDLActivity.width - x_margin) { -// return; -// } - - //TODO: - //SDLActivity.onSDLNativeMouse(0, action, x, y); - processPointerEvent(event, false, false); - } -// else if (Config.mouseMode == Config.MouseMode.External_Alt){ -// processHoverMouseAlt(x, y, p, action); -// } - } - - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/VncCanvasActivity.java b/limbo-android-lib/src/main/java/android/androidVNC/VncCanvasActivity.java deleted file mode 100644 index c96c1088e..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/VncCanvasActivity.java +++ /dev/null @@ -1,1854 +0,0 @@ -/* - * This 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 software 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 software; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, - * USA. - */ -// -// CanvasView is the Activity for showing VNC Desktop. -// -package android.androidVNC; - -import android.app.Activity; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.DialogInterface.OnDismissListener; -import android.content.Intent; -import android.content.res.Configuration; -import android.graphics.PointF; -import android.net.Uri; -import android.os.Bundle; -import android.os.SystemClock; -import android.util.Log; -import android.view.Display; -import android.view.KeyEvent; -import android.view.Menu; -import android.view.MenuItem; -import android.view.MotionEvent; -import android.view.View; -import android.view.Window; -import android.view.WindowManager; -import android.view.inputmethod.InputMethodManager; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.Toast; -import android.widget.ZoomControls; - -import com.antlersoft.android.bc.BCFactory; -import com.limbo.emu.lib.R; -import com.max2idea.android.limbo.main.Config; -import com.max2idea.android.limbo.main.LimboActivity; -import com.max2idea.android.limbo.utils.UIUtils; - -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import androidx.appcompat.app.AppCompatActivity; - -public class VncCanvasActivity extends AppCompatActivity { - - static Display display = null; - public static Activity activity; - - /** - * @author Michael A. MacDonald - */ - class ZoomInputHandler extends AbstractGestureInputHandler { - - /** - * In drag mode (entered with long press) you process mouse events - * without sending them through the gesture detector - */ - private boolean dragMode; - /** - * Key handler delegate that handles DPad-based mouse motion - */ - private DPadMouseKeyHandler keyHandler; - - /** - * @param c - */ - ZoomInputHandler() { - super(VncCanvasActivity.this); - keyHandler = new DPadMouseKeyHandler(VncCanvasActivity.this, vncCanvas.handler); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getHandlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getString(R.string.input_mode_touch_pan_zoom_mouse); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return TOUCH_ZOOM_MODE; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.VncCanvasActivity.ZoomInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - return keyHandler.onKeyDown(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.VncCanvasActivity.ZoomInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - return keyHandler.onKeyUp(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return trackballMouse(evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onDown(android - * .view.MotionEvent) - */ - @Override - public boolean onDown(MotionEvent e) { - panner.stop(); - return true; - } - - /** - * Divide stated fling velocity by this amount to get initial velocity - * per pan interval - */ - static final float FLING_FACTOR = 8; - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onFling(android - * .view.MotionEvent, android.view.MotionEvent, float, float) - */ - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - showZoomer(false); - panner.start(-(velocityX / FLING_FACTOR), -(velocityY / FLING_FACTOR), new Panner.VelocityUpdater() { - - /* - * (non-Javadoc) - * - * @see android.androidVNC.Panner.VelocityUpdater#updateVelocity - * (android.graphics.Point, long) - */ - @Override - public boolean updateVelocity(PointF p, long interval) { - double scale = Math.pow(0.8, interval / 50.0); - p.x *= scale; - p.y *= scale; - return (Math.abs(p.x) > 0.5 || Math.abs(p.y) > 0.5); - } - }); - return true; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractGestureInputHandler#onTouchEvent(android - * .view.MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent e) { - // MK - if (e.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - if (dragMode) { - vncCanvas.changeTouchCoordinatesToFullFrame(e); - if (e.getAction() == MotionEvent.ACTION_UP) { - dragMode = false; - } - return vncCanvas.processPointerEvent(e, true); - } else { - return super.onTouchEvent(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onLongPress( - * android.view.MotionEvent) - */ - @Override - public void onLongPress(MotionEvent e) { -// showZoomer(true); -// BCFactory.getInstance().getBCHaptic().performLongPressHaptic(vncCanvas); -// dragMode = true; -// vncCanvas.processPointerEvent(vncCanvas.changeTouchCoordinatesToFullFrame(e), true); - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onScroll(android - * .view.MotionEvent, android.view.MotionEvent, float, float) - */ - @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - if (inScaling) { - return false; - } - showZoomer(false); - return vncCanvas.pan((int) distanceX, (int) distanceY); - } - - /* - * (non-Javadoc) - * - * @see android.view.GestureDetector.SimpleOnGestureListener# - * onSingleTapConfirmed (android.view.MotionEvent) - */ - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - vncCanvas.changeTouchCoordinatesToFullFrame(e); - vncCanvas.processPointerEvent(e, true); - e.setAction(MotionEvent.ACTION_UP); - return vncCanvas.processPointerEvent(e, false); - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onDoubleTap( - * android.view.MotionEvent) - */ - @Override - public boolean onDoubleTap(MotionEvent e) { - vncCanvas.changeTouchCoordinatesToFullFrame(e); - vncCanvas.processPointerEvent(e, true, true); - e.setAction(MotionEvent.ACTION_UP); - return vncCanvas.processPointerEvent(e, false, true); - } - } - - public class TouchpadInputHandler extends AbstractGestureInputHandler { - - /** - * In drag mode (entered with long press) you process mouse events - * without sending them through the gesture detector - */ - private boolean dragMode; - float dragX, dragY; - /** - * Key handler delegate that handles DPad-based mouse motion - */ - private DPadMouseKeyHandler keyHandler; - - TouchpadInputHandler() { - super(VncCanvasActivity.this); - keyHandler = new DPadMouseKeyHandler(VncCanvasActivity.this, vncCanvas.handler); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getHandlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getString(R.string.input_mode_touchpad); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return TOUCHPAD_MODE; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.VncCanvasActivity.ZoomInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - return keyHandler.onKeyDown(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.VncCanvasActivity.ZoomInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - return keyHandler.onKeyUp(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return trackballMouse(evt); - } - - /** - * scale down delta when it is small. This will allow finer control when - * user is making a small movement on touch screen. Scale up delta when - * delta is big. This allows fast mouse movement when user is flinging. - * - * @param deltaX - * @return - */ - private float fineCtrlScale(float delta) { - float sign = (delta > 0) ? 1 : -1; - delta = Math.abs(delta); - if (delta >= 1 && delta <= 3) { - delta = 1; - } else if (delta <= 10) { - delta *= 0.34; - } else if (delta <= 30) { - delta *= delta / 30; - } else if (delta <= 90) { - delta *= (delta / 30); - } else { - delta *= 3.0; - } - return sign * delta; - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onLongPress( - * android.view.MotionEvent) - */ - @Override - public void onLongPress(MotionEvent e) { - if(Config.enableDragOnLongPress) - dragPointer(e); - } - - private void dragPointer(MotionEvent e) { - - showZoomer(true); - BCFactory.getInstance().getBCHaptic().performLongPressHaptic(vncCanvas); - dragMode = true; - dragX = e.getX(); - dragY = e.getY(); - // send a mouse down event to the remote without moving the mouse. - remoteMouseStayPut(e); - vncCanvas.processPointerEvent(e, true); - - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onScroll(android - * .view.MotionEvent, android.view.MotionEvent, float, float) - */ - @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - //LIMBO: Disable this for now -// if (BCFactory.getInstance().getBCMotionEvent().getPointerCount(e2) > 1) { -// if (inScaling) { -// return false; -// } -// showZoomer(true); -// return vncCanvas.pan((int) distanceX, (int) distanceY); -// } else { - // compute the relative movement offset on the remote screen. - float deltaX = -distanceX * vncCanvas.getScale(); - float deltaY = -distanceY * vncCanvas.getScale(); - deltaX = fineCtrlScale(deltaX); - deltaY = fineCtrlScale(deltaY); - - // compute the absolution new mouse pos on the remote site. - float newRemoteX = vncCanvas.mouseX + deltaX; - float newRemoteY = vncCanvas.mouseY + deltaY; - - if (dragMode) { - if (e2.getAction() == MotionEvent.ACTION_UP) { - dragMode = false; - } - dragX = e2.getX(); - dragY = e2.getY(); - e2.setLocation(newRemoteX, newRemoteY); - return vncCanvas.processPointerEvent(e2, true); - } else { - e2.setLocation(newRemoteX, newRemoteY); - vncCanvas.processPointerEvent(e2, false); - } -// } - return true; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractGestureInputHandler#onTouchEvent(android - * .view.MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent e) { - - // MK - if (e.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - if (Config.mouseMode == Config.MouseMode.External) { - return true; - } - // if (e.getPointerCount() > 1) { - // // Log.v("Limbo", "Detected 2 finger tap in onTouchEvent"); - // rightClick(e); - // return true; - // } - - // compute the relative movement offset on the remote screen. - float deltaX = (e.getX() - dragX) * vncCanvas.getScale(); - float deltaY = (e.getY() - dragY) * vncCanvas.getScale(); - dragX = e.getX(); - dragY = e.getY(); - deltaX = fineCtrlScale(deltaX); - deltaY = fineCtrlScale(deltaY); - - // compute the absolution new mouse pos on the remote site. - float newRemoteX = vncCanvas.mouseX + deltaX; - float newRemoteY = vncCanvas.mouseY + deltaY; - - if (dragMode) { - boolean down = false; - if (e.getAction() == MotionEvent.ACTION_UP) { - dragMode = false; - } else if (e.getAction() == MotionEvent.ACTION_DOWN) { - down = true; - } - - e.setLocation(newRemoteX, newRemoteY); - vncCanvas.processPointerEvent(e, down); - return super.onTouchEvent(e); - - } else if (!Config.enableDragOnLongPress && e.getAction() == MotionEvent.ACTION_MOVE) { - e.setLocation(newRemoteX, newRemoteY); - return vncCanvas.processPointerEvent(e, false); - } else { - return super.onTouchEvent(e); - } - } - - public boolean rightClick(final MotionEvent e) { - Thread t = new Thread(new Runnable() { - public void run() { - remoteMouseStayPut(e); - // One - // Log.v("Double Click", "One"); - vncCanvas.processPointerEvent(e, true, true); - try { - Thread.sleep(100); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - e.setAction(MotionEvent.ACTION_UP); - vncCanvas.processPointerEvent(e, false, true); - } - }); - // t.setPriority(Thread.MAX_PRIORITY); - t.start(); - return true; - - } - - /** - * Modify the event so that it does not move the mouse on the remote - * server. - * - * @param e - */ - private void remoteMouseStayPut(MotionEvent e) { - e.setLocation(vncCanvas.mouseX, vncCanvas.mouseY); - - } - - /* - * (non-Javadoc) confirmed single tap: do a single mouse click on remote - * without moving the mouse. - * - * @see android.view.GestureDetector.SimpleOnGestureListener# - * onSingleTapConfirmed (android.view.MotionEvent) - */ - - @Override - public boolean onSingleTapConfirmed(MotionEvent e) { - singleClick(e); - return true; - // boolean multiTouch = - // (BCFactory.getInstance().getBCMotionEvent().getPointerCount(e) > - // 1); - // remoteMouseStayPut(e); - // vncCanvas.processPointerEvent(e, true, multiTouch || - // vncCanvas.cameraButtonDown); - // e.setAction(MotionEvent.ACTION_UP); - // return vncCanvas.processPointerEvent(e, false, multiTouch || - // vncCanvas.cameraButtonDown); - } - - private boolean singleClick(final MotionEvent e) { - Thread t = new Thread(new Runnable() { - public void run() { - remoteMouseStayPut(e); - // One - // Log.v("Double Click", "One"); - vncCanvas.processPointerEvent(e, true, false); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - e.setAction(MotionEvent.ACTION_UP); - vncCanvas.processPointerEvent(e, false, false); - } - }); - // t.setPriority(Thread.MAX_PRIORITY); - t.start(); - return true; - - } - - private boolean middleClick(final MotionEvent e) { - Thread t = new Thread(new Runnable() { - public void run() { - remoteMouseStayPut(e); - // One - // Log.v("Double Click", "One"); - //vncCanvas.processPointerEvent(e, true, false); - vncCanvas.processPointerEvent((int) e.getX(), (int) e.getY(), e.getAction(), 0, true, false, true, false); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - e.setAction(MotionEvent.ACTION_UP); - //vncCanvas.processPointerEvent(e, false, false); - vncCanvas.processPointerEvent((int) e.getX(), (int) e.getY(), e.getAction(), 0, false, false, true, false); - } - }); - // t.setPriority(Thread.MAX_PRIORITY); - t.start(); - return true; - - } - - /* - * (non-Javadoc) double tap: do two left mouse right mouse clicks on - * remote without moving the mouse. - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onDoubleTap( - * android.view.MotionEvent) - */ - @Override - public boolean onDoubleTap(MotionEvent e) { - if(!Config.enableDragOnLongPress) - processDoubleTap(e); - else - doubleClick(e); - return false; - - } - - private void processDoubleTap(final MotionEvent e) { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Thread.sleep(400); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - - if (vncCanvas.mouseDown) { -// panner.stop(); - dragPointer(e); - } else - doubleClick(e); - - } - }); - t.start(); - } - - /* - * (non-Javadoc) - * - * @see - * android.view.GestureDetector.SimpleOnGestureListener#onDown(android - * .view.MotionEvent) - */ - @Override - public boolean onDown(MotionEvent e) { - panner.stop(); - return true; - } - - private Object doubleClickLock = new Object(); - - private boolean doubleClick(final MotionEvent e1) { - Thread t = new Thread(new Runnable() { - public void run() { - synchronized (doubleClickLock) { - - //XXX: We make a copy of the event because we have some - // race condition here updating mouseX, mouseY - MotionEvent event = MotionEvent.obtain(e1.getDownTime(), - e1.getEventTime(), e1.getAction(), - e1.getX(), e1.getY(), e1.getMetaState()); - - remoteMouseStayPut(event); - // One - // Log.v("Double Click", "One"); - vncCanvas.processPointerEvent(event, true, false); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - event.setAction(MotionEvent.ACTION_UP); - vncCanvas.processPointerEvent(event, false, false); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - // Two - // Log.v("Double Click", "Two"); - event.setAction(MotionEvent.ACTION_DOWN); - vncCanvas.processPointerEvent(event, true, false); - try { - Thread.sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(VncCanvasActivity.class.getName()).log(Level.SEVERE, null, ex); - } - event.setAction(MotionEvent.ACTION_UP); - vncCanvas.processPointerEvent(event, false, false); - } - } - }); - // t.setPriority(Thread.MAX_PRIORITY); - t.start(); - return true; - - } - } - - private final static String TAG = "VncCanvasActivity"; - public AbstractInputHandler inputHandler; - public VncCanvas vncCanvas; - - public MenuItem[] inputModeMenuItems; - public AbstractInputHandler inputModeHandlers[]; - public ConnectionBean connection; - public boolean trackballButtonDown; - public static final int inputModeIds[] = { R.id.itemInputFitToScreen, R.id.itemInputTouchpad, R.id.itemInputMouse, - R.id.itemInputPan, R.id.itemInputTouchPanTrackballMouse, R.id.itemInputDPadPanTouchMouse, - R.id.itemInputTouchPanZoomMouse }; - ZoomControls zoomer; - Panner panner; - - @Override - public void onCreate(Bundle icicle) { - - super.onCreate(icicle); - activity = this; - - Intent i = getIntent(); - connection = new ConnectionBean(); - Uri data = i.getData(); - if ((data != null) && (data.getScheme().equals("vnc"))) { - String host = data.getHost(); - // This should not happen according to Uri contract, but bug - // introduced in Froyo (2.2) - // has made this parsing of host necessary - int index = host.indexOf(':'); - int port; - if (index != -1) { - try { - port = Integer.parseInt(host.substring(index + 1)); - } catch (NumberFormatException nfe) { - port = 0; - } - host = host.substring(0, index); - } else { - port = data.getPort(); - } - if (host.equals(VncConstants.CONNECTION)) { - ConnectionBean bean = new ConnectionBean(); - if (bean != null) { - bean.setConnectionId(connection.get_Id()); - } - } else { - connection.setAddress(host); - connection.setNickname(connection.getAddress()); - connection.setPort(port); - List path = data.getPathSegments(); - if (path.size() >= 1) { - connection.setColorModel(path.get(1)); - } - if (path.size() >= 2) { - connection.setPassword(path.get(1)); - } - } - } else { - - Bundle extras = i.getExtras(); - - if (connection.getPort() == 0) { - connection.setPort(5901); - } - - // Parse a HOST:PORT entry - String host = connection.getAddress(); - // if (host.indexOf(':') > -1) { - // String p = host.substring(host.indexOf(':') + 1); - // try { - // connection.setPort(Integer.parseInt(p)); - // } catch (Exception e) { - // } - // connection.setAddress(host.substring(0, host.indexOf(':'))); - // } - } - connection.setPassword(LimboActivity.getVnc_passwd()); - setContentView(); - - vncCanvas = (VncCanvas) findViewById(R.id.vnc_canvas); - zoomer = (ZoomControls) findViewById(R.id.zoomer); - - vncCanvas.initializeVncCanvas(connection, new Runnable() { - public void run() { - setModes(); - } - }); - zoomer.hide(); - zoomer.setOnZoomInClickListener(new View.OnClickListener() { - - /* - * (non-Javadoc) - * - * @see android.view.View.OnClickListener#onClick(android.view.View) - */ - @Override - public void onClick(View v) { - showZoomer(true); - vncCanvas.scaling.zoomIn(VncCanvasActivity.this); - - } - }); - zoomer.setOnZoomOutClickListener(new View.OnClickListener() { - - /* - * (non-Javadoc) - * - * @see android.view.View.OnClickListener#onClick(android.view.View) - */ - @Override - public void onClick(View v) { - showZoomer(true); - vncCanvas.scaling.zoomOut(VncCanvasActivity.this); - - } - }); - zoomer.setOnZoomInClickListener(new View.OnClickListener() { - - /* - * (non-Javadoc) - * - * @see android.view.View.OnClickListener#onClick(android.view.View) - */ - @Override - public void onClick(View v) { - InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - inputMgr.toggleSoftInput(0, 0); - } - }); - zoomer.setOnZoomOutClickListener(new View.OnClickListener() { - - /* - * (non-Javadoc) - * - * @see android.view.View.OnClickListener#onClick(android.view.View) - */ - @Override - public void onClick(View v) { - InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); - inputMgr.toggleSoftInput(0, 0); - } - }); - panner = new Panner(this, vncCanvas.handler); - - inputHandler = getInputHandlerById(R.id.itemInputFitToScreen); - - display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - } - - public void setContentView() { - setContentView(R.layout.limbo_vnc); - } - - /** - * Set modes on start to match what is specified in the ConnectionBean; - * color mode (already done) scaling, input mode - */ - void setModes() { - AbstractInputHandler handler = getInputHandlerByName(connection.getInputMode()); - AbstractScaling.getByScaleType(connection.getScaleMode()).setScaleTypeForActivity(this); - this.inputHandler = handler; - showPanningState(); - } - - ConnectionBean getConnection() { - return connection; - } - - /* - * (non-Javadoc) - * - * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) - */ - @Override - protected void onPrepareDialog(int id, Dialog dialog) { - super.onPrepareDialog(id, dialog); - if (dialog instanceof ConnectionSettable) { - ((ConnectionSettable) dialog).setConnection(connection); - } - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - // ignore orientation/keyboard change - super.onConfigurationChanged(newConfig); - } - - @Override - protected void onStop() { - vncCanvas.disableRepaints(); - super.onStop(); - } - - @Override - protected void onRestart() { - vncCanvas.enableRepaints(); - super.onRestart(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.vnccanvasactivitymenu, menu); - - if (vncCanvas.scaling != null) { - menu.findItem(vncCanvas.scaling.getId()).setChecked(true); - } - - Menu inputMenu = menu.findItem(R.id.itemInputMode).getSubMenu(); - - inputModeMenuItems = new MenuItem[inputModeIds.length]; - for (int i = 0; i < inputModeIds.length; i++) { - inputModeMenuItems[i] = inputMenu.findItem(inputModeIds[i]); - } - updateInputMenu(); - return true; - } - - /** - * Change the input mode sub-menu to reflect change in scaling - */ - public void updateInputMenu() { - if (inputModeMenuItems == null || vncCanvas.scaling == null) { - return; - } - for (MenuItem item : inputModeMenuItems) { - item.setEnabled(vncCanvas.scaling.isValidInputMode(item.getItemId())); - if (getInputHandlerById(item.getItemId()) == inputHandler) { - item.setChecked(true); - } - } - } - - - - /** - * If id represents an input handler, return that; otherwise return null - * - * @param id - * @return - */ - public AbstractInputHandler getInputHandlerById(int id) { - if (inputModeHandlers == null) { - inputModeHandlers = new AbstractInputHandler[inputModeIds.length]; - } - for (int i = 0; i < inputModeIds.length; ++i) { - if (inputModeIds[i] == id) { - if (inputModeHandlers[i] == null) { - if (id == R.id.itemInputFitToScreen) - inputModeHandlers[i] = new FitToScreenMode(); - else if (id == R.id.itemInputPan) - inputModeHandlers[i] = new PanMode(); - else if (id == R.id.itemInputMouse) - inputModeHandlers[i] = new MouseMode(); - - else if (id == R.id.itemInputTouchPanTrackballMouse) - inputModeHandlers[i] = new TouchPanTrackballMouse(); - else if (id == R.id.itemInputDPadPanTouchMouse) - inputModeHandlers[i] = new DPadPanTouchMouseMode(); - - else if (id == R.id.itemInputTouchPanZoomMouse) - inputModeHandlers[i] = new ZoomInputHandler(); - - else if (id == R.id.itemInputTouchpad) - inputModeHandlers[i] = new TouchpadInputHandler(); - } - - return inputModeHandlers[i]; - } - } - return null; - } - - AbstractInputHandler getInputHandlerByName(String name) { - AbstractInputHandler result = null; - for (int id : inputModeIds) { - AbstractInputHandler handler = getInputHandlerById(id); - if (handler.getName().equals(name)) { - result = handler; - break; - } - } - if (result == null) { - result = getInputHandlerById(R.id.itemInputTouchPanZoomMouse); - } - return result; - } - - int getModeIdFromHandler(AbstractInputHandler handler) { - for (int id : inputModeIds) { - if (handler == getInputHandlerById(id)) { - return id; - } - } - return R.id.itemInputTouchPanZoomMouse; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - vncCanvas.afterMenu = true; - if (item.getItemId() == R.id.itemSpecialKeys) { - showDialog(R.layout.metakey); - return true; - }else if (item.getItemId() == R.id.itemColorMode) { - selectColorModel(); - return true; - } - // Following sets one of the scaling options - else if (item.getItemId() == R.id.itemZoomable || - item.getItemId() == R.id.itemOneToOne || - item.getItemId() == R.id.itemFitToScreen) { - AbstractScaling.getById(item.getItemId()).setScaleTypeForActivity(this); - item.setChecked(true); - showPanningState(); - return true; - } - // case R.id.itemCenterMouse: - // vncCanvas.warpMouse(vncCanvas.absoluteXPosition - // + vncCanvas.getVisibleWidth() / 2, - // vncCanvas.absoluteYPosition + vncCanvas.getVisibleHeight() - // / 2); - // return true; - else if (item.getItemId() == R.id.itemReconnect){ - vncCanvas.closeConnection(); - vncCanvas.reload(); - return true; - } else if (item.getItemId() == R.id.itemDisconnect){ - vncCanvas.closeConnection(); - finish(); - return true; - } else if (item.getItemId() == R.id.itemEnterText){ - showDialog(R.layout.entertext); - return true; - }else if (item.getItemId() == R.id.itemCtrlC) { - vncCanvas.sendMetaKey(MetaKeyBean.keyCtrlC); - return true; - }else if (item.getItemId() == R.id.itemCtrlAltDel){ - vncCanvas.sendMetaKey(MetaKeyBean.keyCtrlAltDel); - return true; - } - // case R.id.itemFollowMouse: - // vncCanvas.panToMouse(); - // return true; - // case R.id.itemFollowPan: - // return true; - // case R.id.itemArrowLeft: - // vncCanvas.sendMetaKey(MetaKeyBean.keyArrowLeft); - // return true; - // case R.id.itemArrowUp: - // vncCanvas.sendMetaKey(MetaKeyBean.keyArrowUp); - // return true; - // case R.id.itemArrowRight: - // vncCanvas.sendMetaKey(MetaKeyBean.keyArrowRight); - // return true; - // case R.id.itemArrowDown: - // vncCanvas.sendMetaKey(MetaKeyBean.keyArrowDown); - // return true; - else if (item.getItemId() == R.id.itemSendKeyAgain) { - return true; - }else if (item.getItemId() == R.id.itemOpenDoc){ - Utils.showDocumentation(this); - return true; - }else { - AbstractInputHandler input = getInputHandlerById(item.getItemId()); - if (input != null) { - inputHandler = input; - connection.setInputMode(input.getName()); - item.setChecked(true); - showPanningState(); - return true; - } - } - return super.onOptionsItemSelected(item); - } - - private MetaKeyBean lastSentKey; - - @Override - protected void onDestroy() { - super.onDestroy(); - if (isFinishing()) { - vncCanvas.closeConnection(); - vncCanvas.onDestroy(); - - - } - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { - MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, vncCanvas.mouseX, vncCanvas.mouseY, - 0); - ((TouchpadInputHandler) this.inputHandler).rightClick(e); - return true; - } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { - MotionEvent e = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, vncCanvas.mouseX, vncCanvas.mouseY, - 0); - ((TouchpadInputHandler) this.inputHandler).middleClick(e); - return true; - } else if (keyCode == KeyEvent.KEYCODE_MENU) { - return super.onKeyDown(keyCode, evt); - } - - return inputHandler.onKeyDown(keyCode, evt); - } - - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - if (keyCode == KeyEvent.KEYCODE_MENU) { - return super.onKeyUp(keyCode, evt); - } - - return inputHandler.onKeyUp(keyCode, evt); - } - - public void showPanningState() { - // Toast.makeText(this, inputHandler.getHandlerDescription(), - // Toast.LENGTH_SHORT).show(); - } - - /* - * (non-Javadoc) - * - * @see android.app.Activity#onTrackballEvent(android.view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - trackballButtonDown = true; - break; - case MotionEvent.ACTION_UP: - trackballButtonDown = false; - break; - } - return inputHandler.onTrackballEvent(event); - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - // MK - if (event.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - if(event.getAction() == MotionEvent.ACTION_DOWN) - vncCanvas.mouseDown = true; - else if(event.getAction() == MotionEvent.ACTION_UP) - vncCanvas.mouseDown = false; - - return inputHandler.onTouchEvent(event); - } - - protected void selectColorModel() { - // Stop repainting the desktop - // because the display is composited! - vncCanvas.disableRepaints(); - - String[] choices = new String[COLORMODEL.values().length]; - int currentSelection = -1; - for (int i = 0; i < choices.length; i++) { - COLORMODEL cm = COLORMODEL.values()[i]; - choices[i] = cm.toString(); - if (vncCanvas.isColorModel(cm)) { - currentSelection = i; - } - } - - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - ListView list = new ListView(this); - list.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_checked, choices)); - list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); - list.setItemChecked(currentSelection, true); - list.setOnItemClickListener(new OnItemClickListener() { - public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { - if (dialog.isShowing()) { - dialog.dismiss(); - } - COLORMODEL cm = COLORMODEL.values()[arg2]; - vncCanvas.setColorModel(cm); - connection.setColorModel(cm.nameString()); - UIUtils.toastShort(VncCanvasActivity.this, "Updating Color Model to " + cm.toString()); - } - }); - dialog.setOnDismissListener(new OnDismissListener() { - @Override - public void onDismiss(DialogInterface arg0) { - Log.i(TAG, "Color Model Selector dismissed"); - // Restore desktop repaints - vncCanvas.enableRepaints(); - } - }); - dialog.setContentView(list); - dialog.show(); - } - - float panTouchX, panTouchY; - - /** - * Pan based on touch motions - * - * @param event - */ - private boolean pan(MotionEvent event) { - float curX = event.getX(); - float curY = event.getY(); - int dX = (int) (panTouchX - curX); - int dY = (int) (panTouchY - curY); - - return vncCanvas.pan(dX, dY); - } - - boolean defaultKeyDownHandler(int keyCode, KeyEvent evt) { - if (vncCanvas.processLocalKeyEvent(keyCode, evt)) { - return true; - } - return super.onKeyDown(keyCode, evt); - } - - boolean defaultKeyUpHandler(int keyCode, KeyEvent evt) { - if (vncCanvas.processLocalKeyEvent(keyCode, evt)) { - return true; - } - return super.onKeyUp(keyCode, evt); - } - - boolean touchPan(MotionEvent event) { - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - panTouchX = event.getX(); - panTouchY = event.getY(); - break; - case MotionEvent.ACTION_MOVE: - pan(event); - panTouchX = event.getX(); - panTouchY = event.getY(); - break; - case MotionEvent.ACTION_UP: - pan(event); - break; - } - return true; - } - - private static int convertTrackballDelta(double delta) { - return (int) Math.pow(Math.abs(delta) * 6.01, 2.5) * (delta < 0.0 ? -1 : 1); - } - - boolean trackballMouse(MotionEvent evt) { - // MK - if (evt.getAction() == MotionEvent.ACTION_CANCEL) - return false; - - int dx = convertTrackballDelta(evt.getX()); - int dy = convertTrackballDelta(evt.getY()); - - evt.offsetLocation(vncCanvas.mouseX + dx - evt.getX(), vncCanvas.mouseY + dy - evt.getY()); - - if (vncCanvas.processPointerEvent(evt, trackballButtonDown)) { - return true; - } - return VncCanvasActivity.super.onTouchEvent(evt); - } - - long hideZoomAfterMs; - static final long ZOOM_HIDE_DELAY_MS = 2500; - HideZoomRunnable hideZoomInstance = new HideZoomRunnable(); - - private void showZoomer(boolean force) { - - if (force || zoomer.getVisibility() != View.VISIBLE) { - // zoomer.show(); - hideZoomAfterMs = SystemClock.uptimeMillis() + ZOOM_HIDE_DELAY_MS; - vncCanvas.handler.postAtTime(hideZoomInstance, hideZoomAfterMs + 10); - } - } - - private class HideZoomRunnable implements Runnable { - - public void run() { - if (SystemClock.uptimeMillis() >= hideZoomAfterMs) { - zoomer.hide(); - } - } - } - - /** - * Touches and dpad (trackball) pan the screen - * - * @author Michael A. MacDonald - * - */ - class PanMode implements AbstractInputHandler { - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - // DPAD KeyDown events are move MotionEvents in Panning Mode - final int dPos = 100; - boolean result = false; - // MK - if (evt.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - switch (keyCode) { - case KeyEvent.KEYCODE_DPAD_CENTER: - result = true; - break; - case KeyEvent.KEYCODE_DPAD_LEFT: - onTouchEvent(MotionEvent.obtain(1, System.currentTimeMillis(), MotionEvent.ACTION_MOVE, - panTouchX + dPos, panTouchY, 0)); - result = true; - break; - case KeyEvent.KEYCODE_DPAD_RIGHT: - onTouchEvent(MotionEvent.obtain(1, System.currentTimeMillis(), MotionEvent.ACTION_MOVE, - panTouchX - dPos, panTouchY, 0)); - result = true; - break; - case KeyEvent.KEYCODE_DPAD_UP: - onTouchEvent(MotionEvent.obtain(1, System.currentTimeMillis(), MotionEvent.ACTION_MOVE, panTouchX, - panTouchY + dPos, 0)); - result = true; - break; - case KeyEvent.KEYCODE_DPAD_DOWN: - onTouchEvent(MotionEvent.obtain(1, System.currentTimeMillis(), MotionEvent.ACTION_MOVE, panTouchX, - panTouchY - dPos, 0)); - result = true; - break; - default: - result = defaultKeyDownHandler(keyCode, evt); - break; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - // Ignore KeyUp events for DPAD keys in Panning Mode; trackball - // button switches to mouse mode - switch (keyCode) { - case KeyEvent.KEYCODE_DPAD_CENTER: - inputHandler = getInputHandlerById(R.id.itemInputMouse); - connection.setInputMode(inputHandler.getName()); - updateInputMenu(); - showPanningState(); - return true; - case KeyEvent.KEYCODE_DPAD_LEFT: - return true; - case KeyEvent.KEYCODE_DPAD_RIGHT: - return true; - case KeyEvent.KEYCODE_DPAD_UP: - return true; - case KeyEvent.KEYCODE_DPAD_DOWN: - return true; - } - return defaultKeyUpHandler(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTouchEvent(android.view - * .MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent event) { - // MK - if (event.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - return touchPan(event); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return false; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#handlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getText(R.string.input_mode_panning); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return "PAN_MODE"; - } - } - - /** - * The touchscreen pans the screen; the trackball moves and clicks the - * mouse. - * - * @author Michael A. MacDonald - * - */ - public class TouchPanTrackballMouse implements AbstractInputHandler { - - private DPadMouseKeyHandler keyHandler = new DPadMouseKeyHandler(VncCanvasActivity.this, vncCanvas.handler); - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - return keyHandler.onKeyDown(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - return keyHandler.onKeyUp(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTouchEvent(android.view - * .MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent evt) { - // MK - if (evt.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - return touchPan(evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return trackballMouse(evt); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#handlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getText(R.string.input_mode_touchpad_pan_trackball_mouse); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return "TOUCH_PAN_TRACKBALL_MOUSE"; - } - } - - public static final String FIT_SCREEN_NAME = "FIT_SCREEN"; - /** - * Internal name for default input mode with Zoom scaling - */ - public static final String TOUCH_ZOOM_MODE = "TOUCH_ZOOM_MODE"; - public static final String TOUCHPAD_MODE = "TOUCHPAD_MODE"; - - /** - * In fit-to-screen mode, no panning. Trackball and touchscreen work as - * mouse. - * - * @author Michael A. MacDonald - * - */ - public class FitToScreenMode implements AbstractInputHandler { - - private DPadMouseKeyHandler keyHandler = new DPadMouseKeyHandler(VncCanvasActivity.this, vncCanvas.handler); - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - return keyHandler.onKeyDown(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - return keyHandler.onKeyUp(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTouchEvent(android.view - * .MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent evt) { - // MK - if (evt.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - return false; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return trackballMouse(evt); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#handlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getText(R.string.input_mode_fit_to_screen); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return FIT_SCREEN_NAME; - } - } - - /** - * Touch screen controls, clicks the mouse. - * - * @author Michael A. MacDonald - * - */ - class MouseMode implements AbstractInputHandler { - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { - return true; - } - return defaultKeyDownHandler(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { - inputHandler = getInputHandlerById(R.id.itemInputPan); - showPanningState(); - connection.setInputMode(inputHandler.getName()); - updateInputMenu(); - return true; - } - return defaultKeyUpHandler(keyCode, evt); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTouchEvent(android.view - * .MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent event) { - // Mouse Pointer Control Mode - // Pointer event is absolute coordinates. - - // MK - if (event.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - vncCanvas.changeTouchCoordinatesToFullFrame(event); - if (vncCanvas.processPointerEvent(event, true)) { - return true; - } - return VncCanvasActivity.super.onTouchEvent(event); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return false; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#handlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getText(R.string.input_mode_mouse); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return "MOUSE"; - } - } - - /** - * Touch screen controls, clicks the mouse. DPad pans the screen - * - * @author Michael A. MacDonald - * - */ - class DPadPanTouchMouseMode implements AbstractInputHandler { - - private boolean isPanning; - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyDown(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyDown(int keyCode, KeyEvent evt) { - int xv = 0; - int yv = 0; - boolean result = true; - switch (keyCode) { - case KeyEvent.KEYCODE_DPAD_LEFT: - // xv = -1; - vncCanvas.sendMetaKey(MetaKeyBean.keyArrowLeft); - return result; - // break; - case KeyEvent.KEYCODE_DPAD_RIGHT: - // xv = 1; - vncCanvas.sendMetaKey(MetaKeyBean.keyArrowRight); - return result; - // break; - case KeyEvent.KEYCODE_DPAD_UP: - // yv = -1; - vncCanvas.sendMetaKey(MetaKeyBean.keyArrowUp); - return result; - // break; - case KeyEvent.KEYCODE_DPAD_DOWN: - // yv = 1; - vncCanvas.sendMetaKey(MetaKeyBean.keyArrowDown); - return result; - // break; - default: - result = defaultKeyDownHandler(keyCode, evt); - break; - } - if ((xv != 0 || yv != 0) && !isPanning) { - final int x = xv; - final int y = yv; - isPanning = true; - panner.start(x, y, new Panner.VelocityUpdater() { - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.Panner.VelocityUpdater#updateVelocity - * (android.graphics.Point, long) - */ - @Override - public boolean updateVelocity(PointF p, long interval) { - double scale = (2.0 * (double) interval / 50.0); - if (Math.abs(p.x) < 500) { - p.x += (int) (scale * x); - } - if (Math.abs(p.y) < 500) { - p.y += (int) (scale * y); - } - return true; - } - }); - vncCanvas.pan(x, y); - } - return result; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#onKeyUp(int, - * android.view.KeyEvent) - */ - @Override - public boolean onKeyUp(int keyCode, KeyEvent evt) { - boolean result = false; - - switch (keyCode) { - case KeyEvent.KEYCODE_DPAD_LEFT: - case KeyEvent.KEYCODE_DPAD_RIGHT: - case KeyEvent.KEYCODE_DPAD_UP: - case KeyEvent.KEYCODE_DPAD_DOWN: - panner.stop(); - isPanning = false; - result = true; - break; - default: - result = defaultKeyUpHandler(keyCode, evt); - break; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTouchEvent(android.view - * .MotionEvent) - */ - @Override - public boolean onTouchEvent(MotionEvent event) { - // Mouse Pointer Control Mode - // Pointer event is absolute coordinates. - - // MK - if (event.getAction() == MotionEvent.ACTION_CANCEL) - return true; - - vncCanvas.changeTouchCoordinatesToFullFrame(event); - if (vncCanvas.processPointerEvent(event, true)) { - return true; - } - return VncCanvasActivity.super.onTouchEvent(event); - } - - /* - * (non-Javadoc) - * - * @see - * android.androidVNC.AbstractInputHandler#onTrackballEvent(android. - * view.MotionEvent) - */ - @Override - public boolean onTrackballEvent(MotionEvent evt) { - return false; - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#handlerDescription() - */ - @Override - public CharSequence getHandlerDescription() { - return getResources().getText(R.string.input_mode_dpad_pan_touchpad_mouse); - } - - /* - * (non-Javadoc) - * - * @see android.androidVNC.AbstractInputHandler#getName() - */ - @Override - public String getName() { - return "DPAD_PAN_TOUCH_MOUSE"; - } - } - - public void onConnected() { - - } -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/VncConstants.java b/limbo-android-lib/src/main/java/android/androidVNC/VncConstants.java deleted file mode 100644 index 7aaa22bfd..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/VncConstants.java +++ /dev/null @@ -1,8 +0,0 @@ -package android.androidVNC; - -/** - * Keys for intent values - */ -public class VncConstants { - public static final String CONNECTION = "android.androidVNC.CONNECTION"; -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ZlibInStream.java b/limbo-android-lib/src/main/java/android/androidVNC/ZlibInStream.java deleted file mode 100644 index 91103a184..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ZlibInStream.java +++ /dev/null @@ -1,112 +0,0 @@ -package android.androidVNC; -/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. - * - * This 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 software 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 software; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, - * USA. - */ - -// -// A ZlibInStream reads from a zlib.io.InputStream -// - -public class ZlibInStream extends InStream { - - static final int defaultBufSize = 16384; - - public ZlibInStream(int bufSize_) { - bufSize = bufSize_; - b = new byte[bufSize]; - ptr = end = ptrOffset = 0; - inflater = new java.util.zip.Inflater(); - } - - public ZlibInStream() { this(defaultBufSize); } - - public void setUnderlying(InStream is, int bytesIn_) { - underlying = is; - bytesIn = bytesIn_; - ptr = end = 0; - } - - public void reset() throws Exception { - ptr = end = 0; - if (underlying == null) return; - - while (bytesIn > 0) { - decompress(); - end = 0; // throw away any data - } - underlying = null; - } - - public int pos() { return ptrOffset + ptr; } - - protected int overrun(int itemSize, int nItems) throws Exception { - if (itemSize > bufSize) - throw new Exception("ZlibInStream overrun: max itemSize exceeded"); - if (underlying == null) - throw new Exception("ZlibInStream overrun: no underlying stream"); - - if (end - ptr != 0) - System.arraycopy(b, ptr, b, 0, end - ptr); - - ptrOffset += ptr; - end -= ptr; - ptr = 0; - - while (end < itemSize) { - decompress(); - } - - if (itemSize * nItems > end) - nItems = end / itemSize; - - return nItems; - } - - // decompress() calls the decompressor once. Note that this won't - // necessarily generate any output data - it may just consume some input - // data. Returns false if wait is false and we would block on the underlying - // stream. - - private void decompress() throws Exception { - try { - underlying.check(1); - int avail_in = underlying.getend() - underlying.getptr(); - if (avail_in > bytesIn) - avail_in = bytesIn; - - if (inflater.needsInput()) { - inflater.setInput(underlying.getbuf(), underlying.getptr(), avail_in); - } - - int n = inflater.inflate(b, end, bufSize - end); - - end += n; - if (inflater.needsInput()) { - bytesIn -= avail_in; - underlying.setptr(underlying.getptr() + avail_in); - } - } catch (java.util.zip.DataFormatException e) { - throw new Exception("ZlibInStream: inflate failed"); - } - } - - private InStream underlying; - private int bufSize; - private int ptrOffset; - private java.util.zip.Inflater inflater; - private int bytesIn; -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/ZoomScaling.java b/limbo-android-lib/src/main/java/android/androidVNC/ZoomScaling.java deleted file mode 100644 index 533ffe1b6..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/ZoomScaling.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package android.androidVNC; - -import com.limbo.emu.lib.R; - -import android.graphics.Matrix; -import android.widget.ImageView.ScaleType; - -/** - * @author Michael A. MacDonald - */ -class ZoomScaling extends AbstractScaling { - - static final String TAG = "ZoomScaling"; - - private Matrix matrix; - int canvasXOffset; - int canvasYOffset; - float scaling; - float minimumScale; - - /** - * @param id - * @param scaleType - */ - public ZoomScaling() { - super(R.id.itemZoomable, ScaleType.MATRIX); - matrix = new Matrix(); - scaling = 1; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#getDefaultHandlerId() - */ - @Override - int getDefaultHandlerId() { - return R.id.itemInputTouchPanZoomMouse; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isAbleToPan() - */ - @Override - boolean isAbleToPan() { - return true; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#isValidInputMode(int) - */ - @Override - boolean isValidInputMode(int mode) { - return mode != R.id.itemInputFitToScreen; - } - - /** - * Call after scaling and matrix have been changed to resolve scrolling - * @param activity - */ - private void resolveZoom(VncCanvasActivity activity) - { - activity.vncCanvas.scrollToAbsolute(); - activity.vncCanvas.pan(0,0); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#zoomIn(android.androidVNC.VncCanvasActivity) - */ - @Override - void zoomIn(VncCanvasActivity activity) { - resetMatrix(); - standardizeScaling(); - scaling += 0.25; - if (scaling > 4.0) - { - scaling = (float)4.0; - activity.zoomer.setIsZoomInEnabled(false); - } - activity.zoomer.setIsZoomOutEnabled(false); //disable Zoomer - matrix.postScale(scaling, scaling); - //Log.v(TAG,String.format("before set matrix scrollx = %d scrolly = %d", activity.vncCanvas.getScrollX(), activity.vncCanvas.getScrollY())); - activity.vncCanvas.setImageMatrix(matrix); - resolveZoom(activity); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#getScale() - */ - @Override - float getScale() { - return scaling; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#zoomOut(android.androidVNC.VncCanvasActivity) - */ - @Override - void zoomOut(VncCanvasActivity activity) { - resetMatrix(); - standardizeScaling(); - scaling -= 0.25; - if (scaling < minimumScale) - { - scaling = minimumScale; - activity.zoomer.setIsZoomOutEnabled(false); - } - activity.zoomer.setIsZoomInEnabled(true); - matrix.postScale(scaling, scaling); - //Log.v(TAG,String.format("before set matrix scrollx = %d scrolly = %d", activity.vncCanvas.getScrollX(), activity.vncCanvas.getScrollY())); - activity.vncCanvas.setImageMatrix(matrix); - //Log.v(TAG,String.format("after set matrix scrollx = %d scrolly = %d", activity.vncCanvas.getScrollX(), activity.vncCanvas.getScrollY())); - resolveZoom(activity); - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#adjust(android.androidVNC.VncCanvasActivity, float, float, float) - */ - @Override - void adjust(VncCanvasActivity activity, float scaleFactor, float fx, - float fy) { - float newScale = scaleFactor * scaling; - if (scaleFactor < 1) - { - if (newScale < minimumScale) - { - newScale = minimumScale; - activity.zoomer.setIsZoomOutEnabled(false); - } - activity.zoomer.setIsZoomInEnabled(true); - } - else - { - if (newScale > 4) - { - newScale = 4; - activity.zoomer.setIsZoomInEnabled(false); - } - activity.zoomer.setIsZoomOutEnabled(true); - } - // ax is the absolute x of the focus - int xPan = activity.vncCanvas.absoluteXPosition; - float ax = (fx / scaling) + xPan; - float newXPan = (scaling * xPan - scaling * ax + newScale * ax)/newScale; - int yPan = activity.vncCanvas.absoluteYPosition; - float ay = (fy / scaling) + yPan; - float newYPan = (scaling * yPan - scaling * ay + newScale * ay)/newScale; - resetMatrix(); - scaling = newScale; - matrix.postScale(scaling, scaling); - activity.vncCanvas.setImageMatrix(matrix); - resolveZoom(activity); - activity.vncCanvas.pan((int)(newXPan - xPan), (int)(newYPan - yPan)); - } - - private void resetMatrix() - { - matrix.reset(); - matrix.preTranslate(canvasXOffset, canvasYOffset); - } - - /** - * Set scaling to one of the clicks on the zoom scale - */ - private void standardizeScaling() - { - scaling = ((float)((int)(scaling * 4))) / 4; - } - - /* (non-Javadoc) - * @see android.androidVNC.AbstractScaling#setScaleTypeForActivity(android.androidVNC.VncCanvasActivity) - */ - @Override - public void setScaleTypeForActivity(VncCanvasActivity activity) { - super.setScaleTypeForActivity(activity); - scaling = (float)1.0; - minimumScale = activity.vncCanvas.bitmapData.getMinimumScale(); - canvasXOffset = -activity.vncCanvas.getCenteredXOffset(); - canvasYOffset = -activity.vncCanvas.getCenteredYOffset(); - resetMatrix(); - activity.vncCanvas.setImageMatrix(matrix); - // Reset the pan position to (0,0) - resolveZoom(activity); - } - -} diff --git a/limbo-android-lib/src/main/java/android/androidVNC/androidVNC.java b/limbo-android-lib/src/main/java/android/androidVNC/androidVNC.java deleted file mode 100644 index bd51d47f1..000000000 --- a/limbo-android-lib/src/main/java/android/androidVNC/androidVNC.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * This 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 software 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 software; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, - * USA. - */ - -// -// androidVNC is the Activity for setting VNC server IP and port. -// - -package android.androidVNC; - -import java.util.ArrayList; - -import com.limbo.emu.lib.R; - -import android.app.Activity; -import android.app.ActivityManager.MemoryInfo; -import android.app.Dialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.EditText; -import android.widget.RadioGroup; -import android.widget.Spinner; -import android.widget.TextView; - -public class androidVNC extends Activity { - private EditText ipText; - private EditText portText; - private EditText passwordText; - private Button goButton; - private TextView repeaterText; - private RadioGroup groupForceFullScreen; - private Spinner colorSpinner; - private Spinner spinnerConnection; - private ConnectionBean selected; - private EditText textNickname; - private EditText textUsername; - private CheckBox checkboxKeepPassword; - private CheckBox checkboxLocalCursor; - private boolean repeaterTextSet; - - @Override - public void onCreate(Bundle icicle) { - - super.onCreate(icicle); - setContentView(R.layout.limbo_main); - - ipText = (EditText) findViewById(R.id.textIP); - portText = (EditText) findViewById(R.id.textPORT); - passwordText = (EditText) findViewById(R.id.textPASSWORD); - textNickname = (EditText) findViewById(R.id.textNickname); - textUsername = (EditText) findViewById(R.id.textUsername); - goButton = (Button) findViewById(R.id.buttonGO); - ((Button) findViewById(R.id.buttonRepeater)) - .setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - showDialog(R.layout.repeater_dialog); - } - }); - ((Button) findViewById(R.id.buttonImportExport)) - .setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - showDialog(R.layout.importexport); - } - }); - colorSpinner = (Spinner) findViewById(R.id.colorformat); - COLORMODEL[] models = COLORMODEL.values(); - ArrayAdapter colorSpinnerAdapter = new ArrayAdapter( - this, android.R.layout.simple_spinner_item, models); - groupForceFullScreen = (RadioGroup) findViewById(R.id.groupForceFullScreen); - checkboxKeepPassword = (CheckBox) findViewById(R.id.checkboxKeepPassword); - checkboxLocalCursor = (CheckBox) findViewById(R.id.checkboxUseLocalCursor); - colorSpinner.setAdapter(colorSpinnerAdapter); - colorSpinner.setSelection(0); - spinnerConnection = (Spinner) findViewById(R.id.spinnerConnection); - spinnerConnection - .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView ad, View view, - int itemIndex, long id) { - selected = (ConnectionBean) ad.getSelectedItem(); - updateViewFromSelected(); - } - - @Override - public void onNothingSelected(AdapterView ad) { - selected = null; - } - }); - spinnerConnection - .setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - - /* - * (non-Javadoc) - * - * @see android.widget.AdapterView.OnItemLongClickListener# - * onItemLongClick(android.widget.AdapterView, - * android.view.View, int, long) - */ - @Override - public boolean onItemLongClick(AdapterView arg0, - View arg1, int arg2, long arg3) { - spinnerConnection.setSelection(arg2); - selected = (ConnectionBean) spinnerConnection - .getItemAtPosition(arg2); - canvasStart(); - return true; - } - - }); - repeaterText = (TextView) findViewById(R.id.textRepeaterId); - goButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - canvasStart(); - } - }); - - } - - protected void onDestroy() { - - super.onDestroy(); - } - - /* - * (non-Javadoc) - * - * @see android.app.Activity#onCreateDialog(int) - */ - @Override - protected Dialog onCreateDialog(int id) { - return new RepeaterDialog(this); - } - - /* - * (non-Javadoc) - * - * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) - */ - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.androidvncmenu, menu); - return true; - } - - - /* - * (non-Javadoc) - * - * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) - */ - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == R.id.itemSaveAsCopy){ - updateSelectedFromView(); - arriveOnPage(); - } else if (item.getItemId() == R.id.itemDeleteConnection || - item.getItemId() == R.id.itemOpenDoc) { - Utils.showDocumentation(this); - } - return true; - } - - private void updateViewFromSelected() { - if (selected == null) - return; - ipText.setText(selected.getAddress()); - portText.setText(Integer.toString(selected.getPort())); - if (selected.getPassword().length() > 0) { - passwordText.setText(selected.getPassword()); - } - groupForceFullScreen - .check(selected.getForceFull() == BitmapImplHint.AUTO ? R.id.radioForceFullScreenAuto - : (selected.getForceFull() == BitmapImplHint.FULL ? R.id.radioForceFullScreenOn - : R.id.radioForceFullScreenOff)); - checkboxLocalCursor.setChecked(selected.getUseLocalCursor()); - textNickname.setText(selected.getNickname()); - COLORMODEL cm = COLORMODEL.valueOf(selected.getColorModel()); - COLORMODEL[] colors = COLORMODEL.values(); - for (int i = 0; i < colors.length; ++i) { - if (colors[i] == cm) { - colorSpinner.setSelection(i); - break; - } - } - } - - /** - * Called when changing view to match selected connection or from Repeater - * dialog to update the repeater information shown. - * - * @param repeaterId - * If null or empty, show text for not using repeater - */ - void updateRepeaterInfo(boolean useRepeater, String repeaterId) { - if (useRepeater) { - repeaterText.setText(repeaterId); - repeaterTextSet = true; - } else { - repeaterText.setText(getText(R.string.repeater_empty_text)); - repeaterTextSet = false; - } - } - - private void updateSelectedFromView() { - if (selected == null) { - return; - } - selected.setAddress(ipText.getText().toString()); - try { - selected.setPort(Integer.parseInt(portText.getText().toString())); - } catch (NumberFormatException nfe) { - - } - selected.setNickname(textNickname.getText().toString()); - - selected.setForceFull(groupForceFullScreen.getCheckedRadioButtonId() == R.id.radioForceFullScreenAuto ? BitmapImplHint.AUTO - : (groupForceFullScreen.getCheckedRadioButtonId() == R.id.radioForceFullScreenOn ? BitmapImplHint.FULL - : BitmapImplHint.TILE)); - selected.setPassword(passwordText.getText().toString()); - - selected.setUseLocalCursor(checkboxLocalCursor.isChecked()); - selected.setColorModel(((COLORMODEL) colorSpinner.getSelectedItem()) - .nameString()); - } - - protected void onStart() { - super.onStart(); - arriveOnPage(); - } - - void arriveOnPage() { - ArrayList connections = new ArrayList(); - connections.add(0, new ConnectionBean()); - int connectionIndex = 0; - - spinnerConnection.setAdapter(new ArrayAdapter(this, - android.R.layout.simple_spinner_item, connections - .toArray(new ConnectionBean[connections.size()]))); - spinnerConnection.setSelection(connectionIndex, false); - selected = connections.get(connectionIndex); - updateViewFromSelected(); - } - - protected void onStop() { - super.onStop(); - if (selected == null) { - return; - } - updateSelectedFromView(); - - } - - - - private void canvasStart() { - if (selected == null) - return; - MemoryInfo info = Utils.getMemoryInfo(this); - if (info.lowMemory) { - // Low Memory situation. Prompt. - Utils.showYesNoPrompt( - this, - "Continue?", - "Android reports low system memory.\nContinue with VNC connection?", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - vnc(); - } - }, null); - } else - vnc(); - } - - private void vnc() { - updateSelectedFromView(); - Intent intent = new Intent(this, VncCanvasActivity.class); - startActivity(intent); - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerDefault.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerDefault.java deleted file mode 100644 index a5d9b603e..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerDefault.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.app.ActivityManager; - -/** - * @author Michael A. MacDonald - */ -class BCActivityManagerDefault implements IBCActivityManager { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCActivityManager#getMemoryClass(android.app.ActivityManager) - */ - @Override - public int getMemoryClass(ActivityManager am) { - return 16; - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerV5.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerV5.java deleted file mode 100644 index a764c76a9..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCActivityManagerV5.java +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.app.ActivityManager; - -/** - * @author Michael A. MacDonald - */ -public class BCActivityManagerV5 implements IBCActivityManager { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCActivityManager#getMemoryClass(android.app.ActivityManager) - */ - @Override - public int getMemoryClass(ActivityManager am) { - return am.getMemoryClass(); - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCFactory.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCFactory.java deleted file mode 100644 index d9cf102eb..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCFactory.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -/** - * Create interface implementations appropriate to the current version of the SDK; - * implementations can allow use of higher-level SDK calls in .apk's that will still run - * on lower-level SDK's - * @author Michael A. MacDonald - */ -public class BCFactory { - - private static BCFactory _theInstance = new BCFactory(); - - private IBCActivityManager bcActivityManager; - private IBCHaptic bcHaptic; - private IBCMotionEvent bcMotionEvent; - private IBCStorageContext bcStorageContext; - - /** - * This is here so checking the static doesn't get optimized away; - * note we can't use SDK_INT because that is too new - * @return sdk version - */ - int getSdkVersion() - { - try - { - return android.os.Build.VERSION.SDK_INT; - } - catch (NumberFormatException nfe) - { - return 1; - } - } - - /** - * Return the implementation of IBCActivityManager appropriate for this SDK level - * @return - */ - public IBCActivityManager getBCActivityManager() - { - if (bcActivityManager == null) - { - synchronized (this) - { - if (bcActivityManager == null) - { - if (getSdkVersion() >= 5) - { - try - { - bcActivityManager = (IBCActivityManager)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCActivityManagerV5").newInstance(); - } - catch (Exception ie) - { - bcActivityManager = new BCActivityManagerDefault(); - throw new RuntimeException("Error instantiating", ie); - } - } - else - { - bcActivityManager = new BCActivityManagerDefault(); - } - } - } - } - return bcActivityManager; - } - - - - /** - * Return the implementation of IBCHaptic appropriate for this SDK level - * - * Since we dropped support of SDK levels prior to 3, there is only one version at the moment. - * @return - */ - public IBCHaptic getBCHaptic() - { - if (bcHaptic == null) - { - synchronized (this) - { - if (bcHaptic == null) - { - try - { - bcHaptic = (IBCHaptic)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCHapticDefault").newInstance(); - } - catch (Exception ie) - { - throw new RuntimeException("Error instantiating", ie); - } - } - } - } - return bcHaptic; - } - - /** - * Return the implementation of IBCMotionEvent appropriate for this SDK level - * @return - */ - public IBCMotionEvent getBCMotionEvent() - { - if (bcMotionEvent == null) - { - synchronized (this) - { - if (bcMotionEvent == null) - { - if (getSdkVersion() >= 5) - { - try - { - bcMotionEvent = (IBCMotionEvent)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCMotionEvent5").newInstance(); - } - catch (Exception ie) - { - throw new RuntimeException("Error instantiating", ie); - } - } - else - { - try - { - bcMotionEvent = (IBCMotionEvent)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCMotionEvent4").newInstance(); - } - catch (Exception ie) - { - throw new RuntimeException("Error instantiating", ie); - } - } - } - } - } - return bcMotionEvent; - } - - /** - * - * @return An implementation of IBCStorageContext appropriate for the running Android release - */ - public IBCStorageContext getStorageContext() - { - if (bcStorageContext == null) - { - synchronized (this) - { - if (bcStorageContext == null) - { - if (getSdkVersion() >= 8) - { - try - { - bcStorageContext = (IBCStorageContext)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCStorageContext8").newInstance(); - } - catch (Exception ie) - { - throw new RuntimeException("Error instantiating", ie); - } - } - else - { - try - { - bcStorageContext = (IBCStorageContext)getClass().getClassLoader().loadClass("com.antlersoft.android.bc.BCStorageContext7").newInstance(); - } - catch (Exception ie) - { - throw new RuntimeException("Error instantiating", ie); - } - } - } - } - } - return bcStorageContext; - } - - /** - * Returns the only instance of this class, which manages the SDK specific interface - * implementations - * @return Factory instance - */ - public static BCFactory getInstance() - { - return _theInstance; - } -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCHapticDefault.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCHapticDefault.java deleted file mode 100644 index c632c05ed..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCHapticDefault.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.view.View; -import android.view.HapticFeedbackConstants; - -/** - * Implementation for SDK version >= 3 - * @author Michael A. MacDonald - */ -class BCHapticDefault implements IBCHaptic { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCHaptic#performLongPressHaptic(android.view.View) - */ - @Override - public boolean performLongPressHaptic(View v) { - return v.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING|HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING - ); - } - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCHaptic#setIsHapticEnabled(android.view.View, boolean) - */ -/* - * @Override - public boolean setIsHapticEnabled(View v, boolean enabled) { - return v.setHapticFeedbackEnabled(hapticFeedbackEnabled) - } -*/ -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent4.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent4.java deleted file mode 100644 index 9e7eab2c8..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent4.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.view.MotionEvent; - -/** - * Pre-sdk 5 version; add fake multi-touch sensing later? - * - * @author Michael A. MacDonald - * - */ -class BCMotionEvent4 implements IBCMotionEvent { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCMotionEvent#getPointerCount(android.view.MotionEvent) - */ - @Override - public int getPointerCount(MotionEvent evt) { - return 1; - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent5.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent5.java deleted file mode 100644 index af15236d0..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCMotionEvent5.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.view.MotionEvent; - -/** - * @author Michael A. MacDonald - * - */ -class BCMotionEvent5 implements IBCMotionEvent { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCMotionEvent#getPointerCount(android.view.MotionEvent) - */ - @Override - public int getPointerCount(MotionEvent evt) { - return evt.getPointerCount(); - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext7.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext7.java deleted file mode 100644 index 27587830b..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext7.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2011 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import java.io.File; - -import android.content.Context; - -import android.os.Environment; - -/** - * @author Michael A. MacDonald - * - */ -public class BCStorageContext7 implements IBCStorageContext { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCStorageContext#getExternalStorageDir(android.content.Context, java.lang.String) - */ - @Override - public File getExternalStorageDir(Context context, String type) { - File f = Environment.getExternalStorageDirectory(); - f = new File(f, "Android/data/android.androidVNC/files"); - if (type != null) - f=new File(f, type); - f.mkdirs(); - return f; - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext8.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext8.java deleted file mode 100644 index 3a7988fef..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/BCStorageContext8.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import java.io.File; - -import android.content.Context; - -/** - * @author Michael A. MacDonald - * - */ -class BCStorageContext8 implements IBCStorageContext { - - /* (non-Javadoc) - * @see com.antlersoft.android.bc.IBCStorageContext#getExternalStorageDir(android.content.Context, java.lang.String) - */ - @Override - public File getExternalStorageDir(Context context, String type) { - return context.getExternalFilesDir(type); - } - -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCActivityManager.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCActivityManager.java deleted file mode 100644 index 103c19ef1..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCActivityManager.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.app.ActivityManager; - -/** - * @author Michael A. MacDonald - */ -public interface IBCActivityManager { - public int getMemoryClass(ActivityManager am); -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCHaptic.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCHaptic.java deleted file mode 100644 index 4a53f7c6a..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCHaptic.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.view.View; - -/** - * Access the Haptic interfaces added in version 3 without breaking compatibility - * @author Michael A. MacDonald - */ -public interface IBCHaptic { - public boolean performLongPressHaptic(View v); - /** - * Set whether haptic feedback is enabled on the view - * @param enabled - * @return Old value of setting - */ - //public boolean setIsHapticEnabled(View v, boolean enabled); -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCMotionEvent.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCMotionEvent.java deleted file mode 100644 index 166f23a60..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCMotionEvent.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.view.MotionEvent; - -/** - * Access to SDK-dependent features of MotionEvent - * - * @see android.view.MotionEvent - * - * @author Michael A. MacDonald - * - */ -public interface IBCMotionEvent { - /** - * Obtain the number of pointers active in the event - * @see android.view.MotionEvent#getPointerCount() - * @param evt - * @return number of pointers - */ - int getPointerCount(MotionEvent evt); -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCStorageContext.java b/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCStorageContext.java deleted file mode 100644 index 69d6ab615..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/bc/IBCStorageContext.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2010 Michael A. MacDonald - */ -package com.antlersoft.android.bc; - -import android.content.Context; - -import java.io.File; - -/** - * Provides a way to access the directory on external storage as returned by - * Context.getExternal... added in API 8 that will work with earlier API releases. - * @author Michael A. MacDonald - * - */ -public interface IBCStorageContext { - /** - * - * @param context Context within the application with which the storage will be associated - * @param type May be null; if specified, references a sub-directory within the base directory - * for the app in the external storage - * @return File representing abstract path of storage directory; refer to android.os.Environment to - * see if the path is actually accessible - */ - public File getExternalStorageDir(Context context, String type); -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/OverlappingCopy.java b/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/OverlappingCopy.java deleted file mode 100644 index 96e15fa2b..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/OverlappingCopy.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.antlersoft.android.drawing; - -import com.antlersoft.util.ObjectPool; -import com.antlersoft.util.SafeObjectPool; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; - -public class OverlappingCopy -{ - private static SafeObjectPool ocRectPool = new SafeObjectPool() { - @Override - protected Rect itemForPool() - { - return new Rect(); - } - }; - private static void transformRect(Rect source, Rect transformedSource, int deltaX, int deltaY) - { - transformedSource.set(deltaX < 0 ? source.right * -1 : source.left, - deltaY < 0 ? source.bottom * -1 : source.top, - deltaX < 0 ? source.left * -1 : source.right, - deltaY < 0 ? source.top * -1 : source.bottom); - } - private static void copyTransformedRect(Rect stepSourceRect, Rect stepDestRect, int deltaX, int deltaY, Bitmap data, Canvas bitmapBackedCanvas, Paint paint) - { - transformRect(stepSourceRect,stepSourceRect,deltaX,deltaY); - stepDestRect.set(stepSourceRect); - stepDestRect.offset(deltaX,deltaY); - bitmapBackedCanvas.drawBitmap(data, stepSourceRect, stepDestRect, paint); - } - public static void Copy(Bitmap data, Canvas bitmapBackedCanvas, Paint paint, Rect source, int destX, int destY) - { - Copy(data,bitmapBackedCanvas,paint,source,destX,destY,ocRectPool); - } - public static void Copy(Bitmap data, Canvas bitmapBackedCanvas, Paint paint, Rect source, int destX, int destY, ObjectPool rectPool) - { - //android.util.Log.i("LBM","Copy "+source.toString()+" to "+destX+","+destY); - int deltaX = destX - source.left; - int deltaY = destY - source.top; - int absDeltaX = deltaX < 0 ? -deltaX : deltaX; - int absDeltaY = deltaY < 0 ? -deltaY : deltaY; - - // Look for degenerate case - if (absDeltaX == 0 && absDeltaY == 0) - return; - // Look for non-overlap case - if (absDeltaX >= source.right - source.left || absDeltaY >= source.bottom - source.top) - { - // Non-overlapping copy - ObjectPool.Entry entry = rectPool.reserve(); - Rect dest = entry.get(); - dest.set(source.left + deltaX, source.top + deltaY, source.right + deltaX, source.bottom + deltaY); - bitmapBackedCanvas.drawBitmap(data, source, dest, paint); - rectPool.release(entry); - return; - } - // Determine coordinate transform so that dest rectangle is always down and to the right. - ObjectPool.Entry transformedSourceEntry = rectPool.reserve(); - Rect transformedSource = transformedSourceEntry.get(); - transformRect(source,transformedSource,deltaX,deltaY); - ObjectPool.Entry transformedDestEntry = rectPool.reserve(); - Rect transformedDest = transformedDestEntry.get(); - transformedDest.set(transformedSource); - transformedDest.offset(absDeltaX, absDeltaY); - ObjectPool.Entry intersectEntry = rectPool.reserve(); - Rect intersect = intersectEntry.get(); - intersect.setIntersect(transformedSource, transformedDest); - - boolean xStepDone = false; - int xStepWidth; - int yStepHeight; - if (absDeltaX > absDeltaY) - { - xStepWidth = absDeltaX; - yStepHeight = source.bottom - source.top - absDeltaY; - } - else - { - xStepWidth = source.right - source.left - absDeltaX; - yStepHeight = absDeltaY; - } - - ObjectPool.Entry stepSourceEntry = rectPool.reserve(); - Rect stepSourceRect = stepSourceEntry.get(); - ObjectPool.Entry stepDestEntry = rectPool.reserve(); - Rect stepDestRect = stepDestEntry.get(); - - for (int xStep = 0; ! xStepDone; xStep++) - { - int stepRight = intersect.right - xStep * xStepWidth; - int stepLeft = stepRight - xStepWidth; - if (stepLeft <= intersect.left) - { - stepLeft = intersect.left; - xStepDone = true; - } - boolean yStepDone = false; - for (int yStep = 0; ! yStepDone; yStep++) - { - int stepBottom = intersect.bottom - yStep * yStepHeight; - int stepTop = stepBottom - yStepHeight; - if (stepTop <= intersect.top) - { - stepTop = intersect.top; - yStepDone = true; - } - stepSourceRect.set(stepLeft,stepTop,stepRight,stepBottom); - //android.util.Log.i("LBM","Copy transformed "+stepSourceRect.toString()+" "+deltaX+" "+deltaY); - copyTransformedRect(stepSourceRect, stepDestRect, deltaX, deltaY, data, bitmapBackedCanvas, paint); - } - } - if (absDeltaX>0) - { - // Copy left edge - stepSourceRect.set(transformedSource.left,transformedSource.top,intersect.left,transformedSource.bottom); - copyTransformedRect(stepSourceRect, stepDestRect, deltaX, deltaY, data, bitmapBackedCanvas, paint); - } - if (absDeltaY>0) - { - // Copy top excluding left edge - stepSourceRect.set(intersect.left,transformedSource.top,transformedSource.right,intersect.top); - copyTransformedRect(stepSourceRect, stepDestRect, deltaX, deltaY, data, bitmapBackedCanvas, paint); - } - - rectPool.release(stepDestEntry); - rectPool.release(stepSourceEntry); - rectPool.release(intersectEntry); - rectPool.release(transformedDestEntry); - rectPool.release(transformedSourceEntry); - } -} - - diff --git a/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/RectList.java b/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/RectList.java deleted file mode 100644 index c1de32087..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/android/drawing/RectList.java +++ /dev/null @@ -1,550 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.android.drawing; - -import android.graphics.Rect; - -import java.util.ArrayList; - -import com.antlersoft.util.ObjectPool; - -/** - * A list of rectangular regions that together represent an area of interest. Provides - * a set of operations that apply to the whole area, adding, changing and mutating the - * rectangles in the list as required. - *

- * Invariants: None of the rectangles in the list overlap; no pair of rectangles in the list - * together make a single rectangle (none share a complete side) - *

- *

- * Instances of this class are not thread safe - *

- * @author Michael A. MacDonald - * - */ -public class RectList { - - enum OverlapType { - NONE, - SAME, - CONTAINS, - CONTAINED_BY, - COALESCIBLE, - PARTIAL - } - - static final int LEFT = 1; - static final int TOP_LEFT = 2; - static final int TOP = 4; - static final int TOP_RIGHT = 8; - static final int RIGHT = 16; - static final int BOTTOM_RIGHT = 32; - static final int BOTTOM = 64; - static final int BOTTOM_LEFT = 128; - - /** - * The part left over when one rectangle is subtracted from another - * @author Michael A. MacDonald - * - */ - static class NonOverlappingPortion - { - Rect leftPortion; - Rect topLeftPortion; - Rect topPortion; - Rect topRightPortion; - Rect rightPortion; - Rect bottomRightPortion; - Rect bottomPortion; - Rect bottomLeftPortion; - - int r1Owns; - int r2Owns; - int common; - int adjacent; - boolean horizontalOverlap; - boolean verticalOverlap; - - Rect coalesced; - - NonOverlappingPortion() - { - leftPortion = new Rect(); - topLeftPortion = new Rect(); - topPortion = new Rect(); - topRightPortion = new Rect(); - rightPortion = new Rect(); - bottomRightPortion = new Rect(); - bottomPortion = new Rect(); - bottomLeftPortion = new Rect(); - coalesced = new Rect(); - } - - void setCornerOwnership(int side1, int side2, int corner) - { - int combined = (side1 | side2); - if ((r1Owns & combined) == combined) - r1Owns |= corner; - else if ((r2Owns & combined) == combined) - r2Owns |= corner; - } - - void setCornerOwnership() - { - setCornerOwnership(LEFT,TOP,TOP_LEFT); - setCornerOwnership(TOP,RIGHT,TOP_RIGHT); - setCornerOwnership(BOTTOM,RIGHT,BOTTOM_RIGHT); - setCornerOwnership(BOTTOM,LEFT,BOTTOM_LEFT); - } - - /** - * Populates with the borders remaining when r2 is subtracted from r1 - * @param r1 - * @param r2 - * @return - */ - OverlapType overlap(Rect r1, Rect r2) - { - r1Owns = 0; - r2Owns = 0; - common = 0; - adjacent = 0; - OverlapType result = OverlapType.NONE; - horizontalOverlap = false; - verticalOverlap = false; - - if (r1.left < r2.left) - { - leftPortion.left = topLeftPortion.left = bottomLeftPortion.left = r1.left; - if (r2.left < r1.right) { - leftPortion.right = topLeftPortion.right = bottomLeftPortion.right = topPortion.left = bottomPortion.left = r2.left; - horizontalOverlap = true; - } else { - leftPortion.right = topLeftPortion.right = bottomLeftPortion.right = topPortion.left = bottomPortion.left = r1.right; - if (r2.left == r1.right) - adjacent |= LEFT; - } - r1Owns |= LEFT; - } - else - { - leftPortion.left = topLeftPortion.left = bottomLeftPortion.left = r2.left; - if (r1.left < r2.right) { - leftPortion.right = topLeftPortion.right = bottomLeftPortion.right = topPortion.left = bottomPortion.left = r1.left; - horizontalOverlap = true; - } else { - leftPortion.right = topLeftPortion.right = bottomLeftPortion.right = topPortion.left = bottomPortion.left = r2.right; - if ( r1.left == r2.right) - adjacent |= RIGHT; - } - if (r2.left < r1.left) - r2Owns |= LEFT; - else - common |= LEFT; - } - if (r1.top < r2.top) - { - topPortion.top = topLeftPortion.top = topRightPortion.top = r1.top; - if (r2.top < r1.bottom) { - topPortion.bottom = topLeftPortion.bottom = topRightPortion.bottom = leftPortion.top = rightPortion.top = r2.top; - verticalOverlap = true; - } else { - topPortion.bottom = topLeftPortion.bottom = topRightPortion.bottom = leftPortion.top = rightPortion.top = r1.bottom; - if (r2.top == r1.bottom) - adjacent |= TOP; - } - r1Owns |= TOP; - } - else - { - topPortion.top = topLeftPortion.top = topRightPortion.top = r2.top; - if (r1.top < r2.bottom) { - topPortion.bottom = topLeftPortion.bottom = topRightPortion.bottom = leftPortion.top = rightPortion.top = r1.top; - verticalOverlap = true; - } else { - topPortion.bottom = topLeftPortion.bottom = topRightPortion.bottom = leftPortion.top = rightPortion.top = r2.bottom; - if (r1.top == r2.bottom) - adjacent |= BOTTOM; - } - if (r2.top < r1.top) - r2Owns |= TOP; - else - common |= TOP; - } - if (r1.right > r2.right) - { - rightPortion.right = topRightPortion.right = bottomRightPortion.right = r1.right; - if (r2.right > r1.left) { - rightPortion.left = topRightPortion.left = bottomRightPortion.left = topPortion.right = bottomPortion.right = r2.right; - horizontalOverlap = true; - } else { - rightPortion.left = topRightPortion.left = bottomRightPortion.left = topPortion.right = bottomPortion.right = r1.left; - if (r2.right == r1.left) - adjacent |= RIGHT; - } - r1Owns |= RIGHT; - } - else - { - rightPortion.right = topRightPortion.right = bottomRightPortion.right = r2.right; - if (r1.right > r2.left) { - rightPortion.left = topRightPortion.left = bottomRightPortion.left = topPortion.right = bottomPortion.right = r1.right; - horizontalOverlap = true; - } else { - rightPortion.left = topRightPortion.left = bottomRightPortion.left = topPortion.right = bottomPortion.right = r2.left; - if (r1.right==r2.left) - adjacent |= LEFT; - } - if (r2.right > r1.right) - r2Owns |= RIGHT; - else - common |= RIGHT; - } - if (r1.bottom > r2.bottom) - { - bottomPortion.bottom = bottomLeftPortion.bottom = bottomRightPortion.bottom = r1.bottom; - if (r2.bottom > r1.top) { - bottomPortion.top = bottomLeftPortion.top = bottomRightPortion.top = leftPortion.bottom = rightPortion.bottom = r2.bottom; - verticalOverlap = true; - } else { - bottomPortion.top = bottomLeftPortion.top = bottomRightPortion.top = leftPortion.bottom = rightPortion.bottom = r1.top; - if (r2.bottom==r1.top) - adjacent |= BOTTOM; - } - r1Owns |= BOTTOM; - } - else - { - bottomPortion.bottom = bottomLeftPortion.bottom = bottomRightPortion.bottom = r2.bottom; - if (r1.bottom > r2.top) { - bottomPortion.top = bottomLeftPortion.top = bottomRightPortion.top = leftPortion.bottom = rightPortion.bottom = r1.bottom; - verticalOverlap = true; - } else { - bottomPortion.top = bottomLeftPortion.top = bottomRightPortion.top = leftPortion.bottom = rightPortion.bottom = r2.top; - if (r1.bottom==r2.top) - adjacent |= TOP; - } - if (r2.bottom > r1.bottom) - r2Owns |= BOTTOM; - else - common |= BOTTOM; - } - if ( common == (LEFT|RIGHT|TOP|BOTTOM)) - { - result = OverlapType.SAME; - } - else if ((common & (LEFT|RIGHT)) == (LEFT | RIGHT) && (verticalOverlap || (adjacent & (TOP | BOTTOM)) != 0)) - { - result = OverlapType.COALESCIBLE; - coalesced.left = r1.left; - coalesced.right = r1.right; - coalesced.top = topPortion.top; - coalesced.bottom = bottomPortion.bottom; - } - else if ((common & (TOP | BOTTOM)) == (TOP | BOTTOM) && (horizontalOverlap || (adjacent & (LEFT | RIGHT)) != 0)) - { - result = OverlapType.COALESCIBLE; - coalesced.left = leftPortion.left; - coalesced.right = rightPortion.right; - coalesced.top = r1.top; - coalesced.bottom = r1.bottom; - } - else if (verticalOverlap && horizontalOverlap) { - if (r2Owns == 0) - { - result = OverlapType.CONTAINED_BY; - } - else if (r1Owns == 0) - { - result = OverlapType.CONTAINS; - } - else - { - // Partial overlap, non coalescible case - result = OverlapType.PARTIAL; - setCornerOwnership(); - } - } - return result; - } - } - - /** - * Up to 8 Rect objects - * @author Michael A. MacDonald - * - */ - static class NonOverlappingRects - { - ObjectPool.Entry[] rectEntries; - int count; - static final int MAX_RECTS = 8; - - @SuppressWarnings("unchecked") - NonOverlappingRects() - { - rectEntries = new ObjectPool.Entry[MAX_RECTS]; - } - - private void addOwnedRect(int owner, int direction, ObjectPool pool, Rect r) - { - if ((owner & direction)==direction) - { - ObjectPool.Entry entry = pool.reserve(); - rectEntries[count++] = entry; - entry.get().set(r); - } - } - - void Populate(NonOverlappingPortion p, ObjectPool pool, int owner) - { - count = 0; - for (int i=0; i> list; - private ObjectPool pool; - private ObjectPool nonOverlappingRectsPool = new ObjectPool() { - - /* (non-Javadoc) - * @see com.antlersoft.util.ObjectPool#itemForPool() - */ - @Override - protected NonOverlappingRects itemForPool() { - return new NonOverlappingRects(); - } - - }; - private ObjectPool>> listRectsPool = new ObjectPool>>() { - - /* (non-Javadoc) - * @see com.antlersoft.util.ObjectPool#itemForPool() - */ - @Override - protected ArrayList> itemForPool() { - return new ArrayList>(NonOverlappingRects.MAX_RECTS); - } - }; - private NonOverlappingPortion nonOverlappingPortion; - - public RectList(ObjectPool pool) - { - this.pool = pool; - list = new ArrayList>(); - nonOverlappingPortion = new NonOverlappingPortion(); - } - - public int getSize() - { - return list.size(); - } - - public Rect get(int i) - { - return list.get(i).get(); - } - - /** - * Remove all rectangles from the list and release them from the pool - */ - public void clear() - { - for (int i=list.size()-1; i>=0; i--) - { - ObjectPool.Entry r = list.get(i); - pool.release(r); - } - list.clear(); - } - - private void recursiveAdd(ObjectPool.Entry toAdd, int level) - { - if (level>=list.size()) - { - list.add(toAdd); - return; - } - Rect addRect = toAdd.get(); - ObjectPool.Entry thisEntry = list.get(level); - Rect thisRect = thisEntry.get(); - switch (nonOverlappingPortion.overlap(thisRect, addRect)) - { - case NONE : - recursiveAdd(toAdd,level + 1); - break; - case SAME : - case CONTAINS : - pool.release(toAdd); - break; - case CONTAINED_BY : - pool.release(thisEntry); - list.remove(level); - recursiveAdd(toAdd,level); - break; - case COALESCIBLE : - pool.release(thisEntry); - list.remove(level); - addRect.set(nonOverlappingPortion.coalesced); - recursiveAdd(toAdd,0); - break; - case PARTIAL : - pool.release(toAdd); - ObjectPool.Entry rectsEntry = nonOverlappingRectsPool.reserve(); - NonOverlappingRects rects = rectsEntry.get(); - rects.Populate(nonOverlappingPortion,pool,nonOverlappingPortion.r2Owns); - for (int i=0; i entry = pool.reserve(); - Rect r = entry.get(); - r.set(toAdd); - recursiveAdd(entry,0); - } - - /** - * Change the rectangle of interest to include only those portions - * that fall inside bounds. - * @param bounds - */ - public void intersect(Rect bounds) - { - int size = list.size(); - ObjectPool.Entry>> listEntry = listRectsPool.reserve(); - ArrayList> newList = listEntry.get(); - newList.clear(); - for (int i=0; i entry = list.get(i); - Rect rect = entry.get(); - if (rect.intersect(bounds)) - { - newList.add(entry); - } - else - pool.release(entry); - } - list.clear(); - size = newList.size(); - for (int i=0; i>> listEntry = listRectsPool.reserve(); - ArrayList> newList = listEntry.get(); - newList.clear(); - for (int i=0; i entry = list.get(i); - Rect rect = entry.get(); - switch (nonOverlappingPortion.overlap(rect, toSubtract)) - { - case SAME: - pool.release(entry); - newList.clear(); - list.remove(i); - return; - case CONTAINED_BY: - pool.release(entry); - list.remove(i); - i--; - size--; - break; - case NONE: - break; - case COALESCIBLE: - if (!nonOverlappingPortion.verticalOverlap || ! nonOverlappingPortion.horizontalOverlap) - break; - case CONTAINS : - nonOverlappingPortion.setCornerOwnership(); - case PARTIAL : - { - ObjectPool.Entry rectsEntry = nonOverlappingRectsPool.reserve(); - NonOverlappingRects rects = rectsEntry.get(); - rects.Populate(nonOverlappingPortion, pool, nonOverlappingPortion.r1Owns); - pool.release(entry); - list.remove(i); - i--; - size--; - for (int j=0; j m_max_size) - { - m_max_size = Math.max(2 * m_max_size, new_size); - byte[] new_buffer = new byte[m_max_size]; - System.arraycopy(m_buffer, 0, new_buffer, 0, result); - m_buffer = new_buffer; - } - - return result; - } - - public void release() - { - if (m_depth<1) - { - throw new IllegalStateException("release() without reserve()"); - } - m_depth--; - } -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/util/ObjectPool.java b/limbo-android-lib/src/main/java/com/antlersoft/util/ObjectPool.java deleted file mode 100644 index e5043096f..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/util/ObjectPool.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.util; - -/** - * A pool of reusable object of a given type. You get the object from a Entry, which you get - * by calling reserve(). When you are done with the object, you call release() passing the Entry. - *

- * Failing to call release() does not leak memory--but you will not get the benefits - * of reusing the object. You will run into contention issues if you - * call release() while still holding a reference to the pool object. - * @author Michael A. MacDonald - * - */ -public abstract class ObjectPool { - public static class Entry { - S item; - Entry nextEntry; - - Entry(S i, Entry n) - { - item = i; - nextEntry = n; - } - - public S get() { - return item; - } - } - - private Entry next; - public ObjectPool() - { - next = null; - } - - public Entry reserve() - { - if (next == null) - { - next = new Entry(itemForPool(), null); - } - Entry result = next; - next = result.nextEntry; - result.nextEntry = null; - - return result; - } - - public void release(Entry entry) - { - entry.nextEntry = next; - next = entry; - } - - protected abstract R itemForPool(); -} diff --git a/limbo-android-lib/src/main/java/com/antlersoft/util/SafeObjectPool.java b/limbo-android-lib/src/main/java/com/antlersoft/util/SafeObjectPool.java deleted file mode 100644 index 3d197ab0c..000000000 --- a/limbo-android-lib/src/main/java/com/antlersoft/util/SafeObjectPool.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (C) 2009 Michael A. MacDonald - */ -package com.antlersoft.util; - -/** - * Synchronized object pool - * @author Michael A. MacDonald - * - */ -public abstract class SafeObjectPool extends ObjectPool { - - /* (non-Javadoc) - * @see com.antlersoft.util.ObjectPool#release(com.antlersoft.util.ObjectPool.Entry) - */ - @Override - public synchronized void release(com.antlersoft.util.ObjectPool.Entry entry) { - super.release(entry); - } - - /* (non-Javadoc) - * @see com.antlersoft.util.ObjectPool#reserve() - */ - @Override - public synchronized com.antlersoft.util.ObjectPool.Entry reserve() { - return super.reserve(); - } - -} From 0882d47715d0d2426940011ad2a35bd9b39e6ea1 Mon Sep 17 00:00:00 2001 From: limboemu Date: Sat, 4 Sep 2021 15:07:38 +0300 Subject: [PATCH 003/154] removed obsolete layouts --- .../src/main/res/layout/connection_list.xml | 46 ---- .../src/main/res/layout/entertext.xml | 31 --- .../src/main/res/layout/importexport.xml | 54 ---- .../src/main/res/layout/intro_dialog.xml | 55 ---- .../src/main/res/layout/limbo_vnc.xml | 63 ----- .../src/main/res/layout/main_vnc.xml | 245 ------------------ .../src/main/res/layout/metakey.xml | 112 -------- .../src/main/res/layout/repeater_dialog.xml | 37 --- .../src/main/res/layout/sliding_drawer.xml | 18 -- 9 files changed, 661 deletions(-) delete mode 100644 limbo-android-lib/src/main/res/layout/connection_list.xml delete mode 100644 limbo-android-lib/src/main/res/layout/entertext.xml delete mode 100644 limbo-android-lib/src/main/res/layout/importexport.xml delete mode 100644 limbo-android-lib/src/main/res/layout/intro_dialog.xml delete mode 100644 limbo-android-lib/src/main/res/layout/limbo_vnc.xml delete mode 100644 limbo-android-lib/src/main/res/layout/main_vnc.xml delete mode 100644 limbo-android-lib/src/main/res/layout/metakey.xml delete mode 100644 limbo-android-lib/src/main/res/layout/repeater_dialog.xml delete mode 100644 limbo-android-lib/src/main/res/layout/sliding_drawer.xml diff --git a/limbo-android-lib/src/main/res/layout/connection_list.xml b/limbo-android-lib/src/main/res/layout/connection_list.xml deleted file mode 100644 index 3f140ebbd..000000000 --- a/limbo-android-lib/src/main/res/layout/connection_list.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - diff --git a/limbo-android-lib/src/main/res/layout/entertext.xml b/limbo-android-lib/src/main/res/layout/entertext.xml deleted file mode 100644 index 6bd5e8f96..000000000 --- a/limbo-android-lib/src/main/res/layout/entertext.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - -