code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
package net.srcz.android.screencast.api.injector;
import com.android.ddmlib.SyncService.ISyncProgressMonitor;
public class NullSyncProgressMonitor implements ISyncProgressMonitor {
public void advance(int arg0) {
}
public boolean isCanceled() {
return false;
}
public void start(int arg0) {
}
public void startSubTask(String arg0) {
}
public void stop() {
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/NullSyncProgressMonitor.java
|
Java
|
asf20
| 407
|
package net.srcz.android.screencast.api.injector;
import java.io.IOException;
import java.io.OutputStream;
import com.android.ddmlib.IShellOutputReceiver;
public class OutputStreamShellOutputReceiver implements IShellOutputReceiver {
OutputStream os;
public OutputStreamShellOutputReceiver(OutputStream os) {
this.os = os;
}
public boolean isCancelled() {
return false;
}
public void flush() {
}
public void addOutput(byte[] buf, int off, int len) {
try {
os.write(buf,off,len);
} catch(IOException ex) {
throw new RuntimeException(ex);
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/OutputStreamShellOutputReceiver.java
|
Java
|
asf20
| 612
|
package net.srcz.android.screencast.api.injector;
public class ConstEvtKey {
// Field descriptor #13 I
public static final int KEYCODE_UNKNOWN = 0;
// Field descriptor #13 I
public static final int KEYCODE_SOFT_LEFT = 1;
// Field descriptor #13 I
public static final int KEYCODE_SOFT_RIGHT = 2;
// Field descriptor #13 I
public static final int KEYCODE_HOME = 3;
// Field descriptor #13 I
public static final int KEYCODE_BACK = 4;
// Field descriptor #13 I
public static final int KEYCODE_CALL = 5;
// Field descriptor #13 I
public static final int KEYCODE_ENDCALL = 6;
// Field descriptor #13 I
public static final int KEYCODE_0 = 7;
// Field descriptor #13 I
public static final int KEYCODE_1 = 8;
// Field descriptor #13 I
public static final int KEYCODE_2 = 9;
// Field descriptor #13 I
public static final int KEYCODE_3 = 10;
// Field descriptor #13 I
public static final int KEYCODE_4 = 11;
// Field descriptor #13 I
public static final int KEYCODE_5 = 12;
// Field descriptor #13 I
public static final int KEYCODE_6 = 13;
// Field descriptor #13 I
public static final int KEYCODE_7 = 14;
// Field descriptor #13 I
public static final int KEYCODE_8 = 15;
// Field descriptor #13 I
public static final int KEYCODE_9 = 16;
// Field descriptor #13 I
public static final int KEYCODE_STAR = 17;
// Field descriptor #13 I
public static final int KEYCODE_POUND = 18;
// Field descriptor #13 I
public static final int KEYCODE_DPAD_UP = 19;
// Field descriptor #13 I
public static final int KEYCODE_DPAD_DOWN = 20;
// Field descriptor #13 I
public static final int KEYCODE_DPAD_LEFT = 21;
// Field descriptor #13 I
public static final int KEYCODE_DPAD_RIGHT = 22;
// Field descriptor #13 I
public static final int KEYCODE_DPAD_CENTER = 23;
// Field descriptor #13 I
public static final int KEYCODE_VOLUME_UP = 24;
// Field descriptor #13 I
public static final int KEYCODE_VOLUME_DOWN = 25;
// Field descriptor #13 I
public static final int KEYCODE_POWER = 26;
// Field descriptor #13 I
public static final int KEYCODE_CAMERA = 27;
// Field descriptor #13 I
public static final int KEYCODE_CLEAR = 28;
// Field descriptor #13 I
public static final int KEYCODE_A = 29;
// Field descriptor #13 I
public static final int KEYCODE_B = 30;
// Field descriptor #13 I
public static final int KEYCODE_C = 31;
// Field descriptor #13 I
public static final int KEYCODE_D = 32;
// Field descriptor #13 I
public static final int KEYCODE_E = 33;
// Field descriptor #13 I
public static final int KEYCODE_F = 34;
// Field descriptor #13 I
public static final int KEYCODE_G = 35;
// Field descriptor #13 I
public static final int KEYCODE_H = 36;
// Field descriptor #13 I
public static final int KEYCODE_I = 37;
// Field descriptor #13 I
public static final int KEYCODE_J = 38;
// Field descriptor #13 I
public static final int KEYCODE_K = 39;
// Field descriptor #13 I
public static final int KEYCODE_L = 40;
// Field descriptor #13 I
public static final int KEYCODE_M = 41;
// Field descriptor #13 I
public static final int KEYCODE_N = 42;
// Field descriptor #13 I
public static final int KEYCODE_O = 43;
// Field descriptor #13 I
public static final int KEYCODE_P = 44;
// Field descriptor #13 I
public static final int KEYCODE_Q = 45;
// Field descriptor #13 I
public static final int KEYCODE_R = 46;
// Field descriptor #13 I
public static final int KEYCODE_S = 47;
// Field descriptor #13 I
public static final int KEYCODE_T = 48;
// Field descriptor #13 I
public static final int KEYCODE_U = 49;
// Field descriptor #13 I
public static final int KEYCODE_V = 50;
// Field descriptor #13 I
public static final int KEYCODE_W = 51;
// Field descriptor #13 I
public static final int KEYCODE_X = 52;
// Field descriptor #13 I
public static final int KEYCODE_Y = 53;
// Field descriptor #13 I
public static final int KEYCODE_Z = 54;
// Field descriptor #13 I
public static final int KEYCODE_COMMA = 55;
// Field descriptor #13 I
public static final int KEYCODE_PERIOD = 56;
// Field descriptor #13 I
public static final int KEYCODE_ALT_LEFT = 57;
// Field descriptor #13 I
public static final int KEYCODE_ALT_RIGHT = 58;
// Field descriptor #13 I
public static final int KEYCODE_SHIFT_LEFT = 59;
// Field descriptor #13 I
public static final int KEYCODE_SHIFT_RIGHT = 60;
// Field descriptor #13 I
public static final int KEYCODE_TAB = 61;
// Field descriptor #13 I
public static final int KEYCODE_SPACE = 62;
// Field descriptor #13 I
public static final int KEYCODE_SYM = 63;
// Field descriptor #13 I
public static final int KEYCODE_EXPLORER = 64;
// Field descriptor #13 I
public static final int KEYCODE_ENVELOPE = 65;
// Field descriptor #13 I
public static final int KEYCODE_ENTER = 66;
// Field descriptor #13 I
public static final int KEYCODE_DEL = 67;
// Field descriptor #13 I
public static final int KEYCODE_GRAVE = 68;
// Field descriptor #13 I
public static final int KEYCODE_MINUS = 69;
// Field descriptor #13 I
public static final int KEYCODE_EQUALS = 70;
// Field descriptor #13 I
public static final int KEYCODE_LEFT_BRACKET = 71;
// Field descriptor #13 I
public static final int KEYCODE_RIGHT_BRACKET = 72;
// Field descriptor #13 I
public static final int KEYCODE_BACKSLASH = 73;
// Field descriptor #13 I
public static final int KEYCODE_SEMICOLON = 74;
// Field descriptor #13 I
public static final int KEYCODE_APOSTROPHE = 75;
// Field descriptor #13 I
public static final int KEYCODE_SLASH = 76;
// Field descriptor #13 I
public static final int KEYCODE_AT = 77;
// Field descriptor #13 I
public static final int KEYCODE_NUM = 78;
// Field descriptor #13 I
public static final int KEYCODE_HEADSETHOOK = 79;
// Field descriptor #13 I
public static final int KEYCODE_FOCUS = 80;
// Field descriptor #13 I
public static final int KEYCODE_PLUS = 81;
// Field descriptor #13 I
public static final int KEYCODE_MENU = 82;
// Field descriptor #13 I
public static final int KEYCODE_NOTIFICATION = 83;
// Field descriptor #13 I
public static final int KEYCODE_SEARCH = 84;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_PLAY_PAUSE = 85;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_STOP = 86;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_NEXT = 87;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_PREVIOUS = 88;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_REWIND = 89;
// Field descriptor #13 I
public static final int KEYCODE_MEDIA_FAST_FORWARD = 90;
// Field descriptor #13 I
public static final int KEYCODE_MUTE = 91;
// Field descriptor #13 I
public static final int MAX_KEYCODE = 84;
// Field descriptor #13 I
public static final int ACTION_DOWN = 0;
// Field descriptor #13 I
public static final int ACTION_UP = 1;
// Field descriptor #13 I
public static final int ACTION_MULTIPLE = 2;
// Field descriptor #13 I
public static final int META_ALT_ON = 2;
// Field descriptor #13 I
public static final int META_ALT_LEFT_ON = 16;
// Field descriptor #13 I
public static final int META_ALT_RIGHT_ON = 32;
// Field descriptor #13 I
public static final int META_SHIFT_ON = 1;
// Field descriptor #13 I
public static final int META_SHIFT_LEFT_ON = 64;
// Field descriptor #13 I
public static final int META_SHIFT_RIGHT_ON = 128;
// Field descriptor #13 I
public static final int META_SYM_ON = 4;
// Field descriptor #13 I
public static final int FLAG_WOKE_HERE = 1;
// Field descriptor #13 I
public static final int FLAG_SOFT_KEYBOARD = 2;
// Field descriptor #13 I
public static final int FLAG_KEEP_TOUCH_MODE = 4;
// Field descriptor #13 I
public static final int FLAG_FROM_SYSTEM = 8;
// Field descriptor #13 I
public static final int FLAG_EDITOR_ACTION = 16;
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/ConstEvtKey.java
|
Java
|
asf20
| 9,059
|
package net.srcz.android.screencast.api.injector;
import java.awt.event.KeyEvent;
public class KeyCodeConverter {
public static int getKeyCode(KeyEvent e) {
char c = e.getKeyChar();
int code = 0;
if(Character.isLetter(c))
code = ConstEvtKey.KEYCODE_A + (Character.toLowerCase(c)-'a');
if(Character.isDigit(c))
code = ConstEvtKey.KEYCODE_0 + (c-'0');
if(c == '\n')
code = ConstEvtKey.KEYCODE_ENTER;
if(c == ' ')
code = ConstEvtKey.KEYCODE_SPACE;
if(c == '\b')
code = ConstEvtKey.KEYCODE_DEL;
if(c == '\t')
code = ConstEvtKey.KEYCODE_TAB;
if(c == '/')
code = ConstEvtKey.KEYCODE_SLASH;
if(c == '\\')
code = ConstEvtKey.KEYCODE_BACKSLASH;
if(c == ',')
code = ConstEvtKey.KEYCODE_COMMA;
if(c == ';')
code = ConstEvtKey.KEYCODE_SEMICOLON;
if(c == '.')
code = ConstEvtKey.KEYCODE_PERIOD;
if(c == '*')
code = ConstEvtKey.KEYCODE_STAR;
if(c == '+')
code = ConstEvtKey.KEYCODE_PLUS;
if(c == '-')
code = ConstEvtKey.KEYCODE_MINUS;
if(c == '=')
code = ConstEvtKey.KEYCODE_EQUALS;
if(e.getKeyCode() == KeyEvent.VK_HOME)
code = ConstEvtKey.KEYCODE_HOME;
if(e.getKeyCode() == KeyEvent.VK_PAGE_UP)
code = ConstEvtKey.KEYCODE_MENU;
if(e.getKeyCode() == KeyEvent.VK_PAGE_DOWN)
code = ConstEvtKey.KEYCODE_STAR;
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
code = ConstEvtKey.KEYCODE_BACK;
if(e.getKeyCode() == KeyEvent.VK_F3)
code = ConstEvtKey.KEYCODE_CALL;
if(e.getKeyCode() == KeyEvent.VK_F4)
code = ConstEvtKey.KEYCODE_ENDCALL;
if(e.getKeyCode() == KeyEvent.VK_F5)
code = ConstEvtKey.KEYCODE_SEARCH;
if(e.getKeyCode() == KeyEvent.VK_F7)
code = ConstEvtKey.KEYCODE_POWER;
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
code = ConstEvtKey.KEYCODE_DPAD_RIGHT;
if(e.getKeyCode() == KeyEvent.VK_UP)
code = ConstEvtKey.KEYCODE_DPAD_UP;
if(e.getKeyCode() == KeyEvent.VK_DOWN)
code = ConstEvtKey.KEYCODE_DPAD_DOWN;
if(e.getKeyCode() == KeyEvent.VK_SHIFT)
code = ConstEvtKey.KEYCODE_SHIFT_LEFT;
return code;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/KeyCodeConverter.java
|
Java
|
asf20
| 2,171
|
package net.srcz.android.screencast.api.injector;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import net.srcz.android.screencast.api.AndroidDevice;
import net.srcz.android.screencast.api.StreamUtils;
import com.android.ddmlib.IDevice;
public class Injector {
private static final int PORT = 1324;
private static final String LOCAL_AGENT_JAR_LOCATION = "/MyInjectEventApp.jar";
private static final String REMOTE_AGENT_JAR_LOCATION = "/data/local/tmp/InjectAgent.jar";
private static final String AGENT_MAIN_CLASS = "net.srcz.android.screencast.client.Main";
IDevice device;
public static Socket s;
OutputStream os;
Thread t = new Thread("Agent Init") {
public void run() {
try {
init();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
public ScreenCaptureThread screencapture;
public Injector(IDevice d) throws IOException {
this.device = d;
this.screencapture = new ScreenCaptureThread(d);
}
public void start() {
t.start();
}
private void uploadAgent() throws IOException {
try {
File tempFile = File.createTempFile("agent", ".jar");
StreamUtils.transfertResource(getClass(), LOCAL_AGENT_JAR_LOCATION,
tempFile);
new AndroidDevice(device).pushFile(tempFile,
REMOTE_AGENT_JAR_LOCATION);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* @return true if there was a client running
*/
private static boolean killRunningAgent() {
try {
Socket s = new Socket("127.0.0.1", PORT);
OutputStream os = s.getOutputStream();
os.write("quit\n".getBytes());
os.flush();
os.close();
s.close();
return true;
} catch (Exception ex) {
// ignor�
}
return false;
}
public void close() {
try {
if (os != null) {
os.write("quit\n".getBytes());
os.flush();
os.close();
}
s.close();
} catch (Exception ex) {
// ignored
}
screencapture.interrupt();
try {
s.close();
} catch (Exception ex) {
// ignored
}
try {
synchronized (device) {
/*
* if(device != null) device.removeForward(PORT, PORT);
*/
}
} catch (Exception ex) {
// ignored
}
}
public void injectMouse(int action, float x, float y) throws IOException {
long downTime = 10;
long eventTime = 10;
int metaState = -1;
String cmdList1 = "pointer/" + downTime + "/" + eventTime + "/"
+ action + "/" + x + "/" + y + "/" + metaState;
injectData(cmdList1);
}
public void injectTrackball(float amount) throws IOException {
long downTime = 0;
long eventTime = 0;
float x = 0;
float y = amount;
int metaState = -1;
String cmdList1 = "trackball/" + downTime + "/" + eventTime + "/"
+ ConstEvtMotion.ACTION_MOVE + "/" + x + "/" + y + "/"
+ metaState;
injectData(cmdList1);
String cmdList2 = "trackball/" + downTime + "/" + eventTime + "/"
+ ConstEvtMotion.ACTION_CANCEL + "/" + x + "/" + y + "/"
+ metaState;
injectData(cmdList2);
}
public void injectKeycode(int type, int keyCode) {
String cmdList = "key/" + type + "/" + keyCode;
injectData(cmdList);
}
private void injectData(String data) {
try {
if (os == null) {
System.out.println("Injector is not running yet...");
return;
}
os.write((data + "\n").getBytes());
os.flush();
} catch (Exception sex) {
try {
s = new Socket("127.0.0.1", PORT);
os = s.getOutputStream();
os.write((data + "\n").getBytes());
os.flush();
} catch(Exception ex) {
// ignored
}
}
}
private void init() throws UnknownHostException, IOException,
InterruptedException {
device.createForward(PORT, PORT);
if (killRunningAgent())
System.out.println("Old client closed");
uploadAgent();
Thread threadRunningAgent = new Thread("Running Agent") {
public void run() {
try {
launchProg("" + PORT);
} catch (IOException e) {
e.printStackTrace();
}
}
};
threadRunningAgent.start();
Thread.sleep(4000);
connectToAgent();
System.out.println("succes !");
}
private void connectToAgent() {
for (int i = 0; i < 10; i++) {
try {
s = new Socket("127.0.0.1", PORT);
break;
} catch (Exception s) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
System.out.println("Desktop => device socket connected");
screencapture.start();
try {
os = s.getOutputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void launchProg(String cmdList) throws IOException {
String fullCmd = "export CLASSPATH=" + REMOTE_AGENT_JAR_LOCATION;
fullCmd += "; exec app_process /system/bin " + AGENT_MAIN_CLASS + " "
+ cmdList;
System.out.println(fullCmd);
device.executeShellCommand(fullCmd,
new OutputStreamShellOutputReceiver(System.out));
System.out.println("Prog ended");
device.executeShellCommand("rm " + REMOTE_AGENT_JAR_LOCATION,
new OutputStreamShellOutputReceiver(System.out));
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/Injector.java
|
Java
|
asf20
| 5,257
|
package net.srcz.android.screencast.api.injector;
public class ConstEvtMotion {
// Field descriptor #10 I
public static final int ACTION_DOWN = 0;
// Field descriptor #10 I
public static final int ACTION_UP = 1;
// Field descriptor #10 I
public static final int ACTION_MOVE = 2;
// Field descriptor #10 I
public static final int ACTION_CANCEL = 3;
// Field descriptor #10 I
public static final int ACTION_OUTSIDE = 4;
// Field descriptor #10 I
public static final int EDGE_TOP = 1;
// Field descriptor #10 I
public static final int EDGE_BOTTOM = 2;
// Field descriptor #10 I
public static final int EDGE_LEFT = 4;
// Field descriptor #10 I
public static final int EDGE_RIGHT = 8;
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/injector/ConstEvtMotion.java
|
Java
|
asf20
| 804
|
package net.srcz.android.screencast.api.file;
import java.io.File;
import net.srcz.android.screencast.api.AndroidDevice;
public class FileInfo {
public AndroidDevice device;
public String path;
public String attribs;
public boolean directory;
public String name;
public File downloadTemporary() {
try {
File tempFile = File.createTempFile("android", name);
device.pullFile(path + name, tempFile);
tempFile.deleteOnExit();
return tempFile;
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}
public String toString() {
return name;
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/file/FileInfo.java
|
Java
|
asf20
| 585
|
package net.srcz.android.screencast.api;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Vector;
import net.srcz.android.screencast.api.file.FileInfo;
import net.srcz.android.screencast.api.injector.NullSyncProgressMonitor;
import net.srcz.android.screencast.api.injector.OutputStreamShellOutputReceiver;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.SyncService.ISyncProgressMonitor;
import com.android.ddmlib.SyncService.SyncResult;
public class AndroidDevice {
IDevice device;
public AndroidDevice(IDevice device) {
this.device = device;
}
public void openUrl(String url) {
executeCommand("am start "+url);
}
public String executeCommand(String cmd) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
device.executeShellCommand(cmd,
new OutputStreamShellOutputReceiver(bos));
return new String(bos.toByteArray(), "UTF-8");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void pushFile(File localFrom, String remoteTo) {
try {
if (device.getSyncService() == null)
throw new RuntimeException("SyncService is null, ADB crashed ?");
SyncResult result = device.getSyncService().pushFile(localFrom.getAbsolutePath(),
remoteTo, new NullSyncProgressMonitor());
if (result.getCode() != 0)
throw new RuntimeException("code = " + result.getCode()
+ " message= " + result.getMessage());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void pullFile(String removeFrom, File localTo) {
// ugly hack to call the method without FileEntry
try {
if (device.getSyncService() == null)
throw new RuntimeException("SyncService is null, ADB crashed ?");
Method m = device.getSyncService().getClass().getDeclaredMethod(
"doPullFile", String.class, String.class,
ISyncProgressMonitor.class);
m.setAccessible(true);
m.invoke(device.getSyncService(), removeFrom, localTo.getAbsolutePath(), device
.getSyncService().getNullProgressMonitor());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public List<FileInfo> list(String path) {
try {
String s = executeCommand("ls -l "+path);
String[] entries = s.split("\r\n");
Vector<FileInfo> liste = new Vector<FileInfo>();
for (int i = 0; i < entries.length; i++) {
String[] data = entries[i].split(" ");
if (data.length < 4)
continue;
/*
* for(int j=0; j<data.length; j++) {
* System.out.println(j+" = "+data[j]); }
*/
String attribs = data[0];
boolean directory = attribs.startsWith("d");
String name = data[data.length - 1];
FileInfo fi = new FileInfo();
fi.attribs = attribs;
fi.directory = directory;
fi.name = name;
fi.path = path;
fi.device = this;
liste.add(fi);
}
return liste;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
|
zyq726-0001
|
AndroidScreencast/src/net/srcz/android/screencast/api/AndroidDevice.java
|
Java
|
asf20
| 2,969
|
package net.srcz.android.screencast.client;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
static boolean debug = false;
int port;
public Main(int port, boolean debug) {
this.port = port;
this.debug = debug;
}
public void execute() throws IOException {
ServerSocket ss = new ServerSocket(port);
while(true) {
final Socket s = ss.accept();
if(s == null || ss.isClosed())
break;
if(debug)
System.out.println("New client ! ");
Thread t = new Thread() {
public void run() {
try {
new ClientHandler(s);
} catch(Exception ex) {
ex.printStackTrace();
}
try {
s.close();
} catch(Exception ex) {
// ignor�
}
}
};
t.start();
/*
Thread t2 = new Thread() {
public void run() {
try {
File f = new File("/dev/graphics/fb0");
FileInputStream fis = new FileInputStream(f);
byte[] data = new byte[16];
OutputStream os = s.getOutputStream();
while(true) {
int val = fis.read(data);
if(val <= 0) {
sleep(0);
continue;
}
os.write(data,0,val);
os.flush();
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
};
t2.start();
*/
}
}
public static void main(String[] args) {
System.out.println("[agent] Starting ...");
try {
if(args.length == 0)
throw new RuntimeException("Need >= 1 param");
int port = Integer.parseInt(args[0]);
boolean debug = args.length >= 2 && args[1].equals("debug");
new Main(port, debug).execute();
} catch(Exception ex) {
ex.printStackTrace();
}
}
/*
public static void keystroke2(int keycode) throws RemoteException {
import android.app.Instrumentation;
Instrumentation ins = new Instrumentation();
ins.sendKeyDownUpSync(keycode);
}
*/
}
|
zyq726-0001
|
AndroidScreencastClient/src/net/srcz/android/screencast/client/Main.java
|
Java
|
asf20
| 2,458
|
package net.srcz.android.screencast.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.view.IWindowManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class ClientHandler {
IBinder wmbinder = ServiceManager.getService( "window" );
final IWindowManager wm = IWindowManager.Stub.asInterface( wmbinder );
Socket s;
public ClientHandler(Socket s) throws IOException, RemoteException {
this.s = s;
Thread tSend = new Thread() {
public void run() {
sendFrameBuffer();
}
};
Thread tHandleCmd = new Thread() {
public void run() {
handleCmd();
}
};
tSend.start();
tHandleCmd.start();
try {
tSend.join();
tHandleCmd.join();
} catch (InterruptedException e) {
}
}
private void sendFrameBuffer() {
try {
Process p = Runtime.getRuntime().exec("/system/bin/cat /dev/graphics/fb0");
InputStream is = p.getInputStream();
System.out.println("Starting sending framebuffer");
OutputStream os = s.getOutputStream();
byte[] buff = new byte[336*512*2];
while(true) {
//FileInputStream fos = new FileInputStream("/dev/graphics/fb0");
int nb = is.read(buff);
if(nb < -1)
break;
//fos.close();
System.out.println("val "+nb);
os.write(buff,0,nb);
Thread.sleep(10);
}
is.close();
System.out.println("End of sending thread");
} catch(Exception ex) {
ex.printStackTrace();
}
}
private void handleCmd() {
try {
InputStream is = s.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
while(true) {
String line = r.readLine();
if(line == null) {
r.close();
s.close();
break;
}
if(Main.debug)
System.out.println("Received : "+line);
try {
handleCommand(line);
} catch(Exception ex) {
ex.printStackTrace();
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
private void handleCommand(String line) throws RemoteException {
String[] paramList = line.split("/");
String type = paramList[0];
if(type.equals("quit")) {
System.exit(0);
return;
}
if(type.equals("pointer")) {
wm.injectPointerEvent(getMotionEvent(paramList), false);
return;
}
if(type.equals("key")) {
wm.injectKeyEvent(getKeyEvent(paramList), false);
return;
}
if(type.equals("trackball")) {
wm.injectTrackballEvent(getMotionEvent(paramList), false);
return;
}
throw new RuntimeException("Invalid type : "+type);
}
private static MotionEvent getMotionEvent(String[] args) {
int i = 1;
long downTime = Long.parseLong(args[i++]);
long eventTime = Long.parseLong(args[i++]);
int action = Integer.parseInt(args[i++]);
float x = Float.parseFloat(args[i++]);
float y = Float.parseFloat(args[i++]);
int metaState = Integer.parseInt(args[i++]);
return MotionEvent.obtain(downTime, eventTime, action, x, y, metaState);
}
private static KeyEvent getKeyEvent(String[] args) {
int action = Integer.parseInt(args[1]);
int code = Integer.parseInt(args[2]);
return new KeyEvent(action, code);
}
}
|
zyq726-0001
|
AndroidScreencastClient/src/net/srcz/android/screencast/client/ClientHandler.java
|
Java
|
asf20
| 3,540
|
del classes.dex
set PATH=%PATH%;C:\Users\a015843\Documents\perso\android-sdk-windows-1.5_r3_\platforms\android-1.5\tools
cmd /c dx --dex --output=C:\Users\a015843\eclipse-workspace\AndroidScreencastClient\classes.dex C:\Users\a015843\eclipse-workspace\AndroidScreencastClient\MyInjectEventApp.jar
aapt add MyInjectEventApp.jar classes.dex
adb push MyInjectEventApp.jar /data/
del classes.dex
rem del MyInjectEventApp.jar
move MyInjectEventApp.jar ../AndroidScreencast/
|
zyq726-0001
|
AndroidScreencastClient/MyInjectEventApp.bat
|
Batchfile
|
asf20
| 475
|
package net.appositedesigns.fileexplorer.activity;
import net.appositedesigns.fileexplorer.util.BookmarksHelper;
import net.appositedesigns.fileexplorer.util.PreferenceHelper;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
public abstract class BaseFileListActivity extends ListActivity {
protected PreferenceHelper prefs;
protected BookmarksHelper bookmarker;
private OnSharedPreferenceChangeListener listener;
protected boolean shouldRestartApp = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
prefs = new PreferenceHelper(this);
bookmarker = new BookmarksHelper(this);
setTheme(prefs.getTheme());
super.onCreate(savedInstanceState);
listenToThemeChange();
}
private void listenToThemeChange() {
listener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (PreferenceHelper.PREF_THEME.equals(key)) {
shouldRestartApp = true;
}
if (PreferenceHelper.PREF_USE_QUICKACTIONS.equals(key)) {
shouldRestartApp = true;
}
}
};
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(listener);
}
public synchronized PreferenceHelper getPreferenceHelper()
{
return prefs;
}
public BookmarksHelper getBookmarker()
{
return bookmarker;
}
@Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(listener);
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/activity/BaseFileListActivity.java
|
Java
|
gpl3
| 1,804
|
package net.appositedesigns.fileexplorer.activity;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import net.appositedesigns.fileexplorer.FileExplorerApp;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.adapters.FileListAdapter;
import net.appositedesigns.fileexplorer.callbacks.CancellationCallback;
import net.appositedesigns.fileexplorer.callbacks.FileActionsCallback;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.model.FileListing;
import net.appositedesigns.fileexplorer.util.FileActionsHelper;
import net.appositedesigns.fileexplorer.util.Util;
import net.appositedesigns.fileexplorer.workers.FileMover;
import net.appositedesigns.fileexplorer.workers.Finder;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileListActivity extends BaseFileListActivity {
private static final String TAG = FileListActivity.class.getName();
private static final String CURRENT_DIR_DIR = "current-dir";
private ListView explorerListView;
private File currentDir;
private List<FileListEntry> files;
private FileListAdapter adapter;
protected Object mCurrentActionMode;
private ArrayAdapter<CharSequence> mSpinnerAdapter;
private CharSequence[] gotoLocations;
private boolean isPicker = false;
private FileExplorerApp app;
private File previousOpenDirChild;
private boolean focusOnParent;
private boolean excludeFromMedia = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
app = (FileExplorerApp)getApplication();
isPicker = getIntent().getBooleanExtra(FileExplorerApp.EXTRA_IS_PICKER, false);
if(Intent.ACTION_GET_CONTENT.equals(getIntent().getAction()))
{
isPicker = true;
app.setFileAttachIntent(getIntent());
}
initUi();
initGotoLocations();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prepareActionBar();
initRootDir(savedInstanceState);
files = new ArrayList<FileListEntry>();
initFileListView();
focusOnParent = getPreferenceHelper().focusOnParent();
if (getPreferenceHelper().isEulaAccepted()) {
listContents(currentDir);
} else {
EulaPopupBuilder.create(this).show();
}
}
private void initUi() {
if(isPicker)
{
getWindow().setUiOptions(0);
}
}
private void initGotoLocations() {
gotoLocations = getResources().getStringArray(R.array.goto_locations);
}
private void initFileListView() {
explorerListView = (ListView) getListView();
adapter = new FileListAdapter(this, files);
explorerListView.setAdapter(adapter);
explorerListView.setTextFilterEnabled(true);
explorerListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (explorerListView.isClickable()) {
FileListEntry file = (FileListEntry) explorerListView
.getAdapter().getItem(position);
select(file.getPath());
}
}
});
explorerListView.setOnItemLongClickListener(getLongPressListener());
registerForContextMenu(explorerListView);
}
private OnItemLongClickListener getLongPressListener() {
return new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
final View view, int arg2, long arg3) {
if(!explorerListView.isLongClickable())
return true;
if(isPicker)
{
return false;
}
view.setSelected(true);
final FileListEntry fileListEntry = (FileListEntry) adapter
.getItem(arg2);
if (mCurrentActionMode != null) {
return false;
}
if (Util.isProtected(fileListEntry
.getPath())) {
return false;
}
explorerListView.setEnabled(false);
mCurrentActionMode = FileListActivity.this
.startActionMode(new FileActionsCallback(
FileListActivity.this, fileListEntry) {
@Override
public void onDestroyActionMode(
ActionMode mode) {
view.setSelected(false);
mCurrentActionMode = null;
explorerListView.setEnabled(true);
}
});
view.setSelected(true);
return true;
}
};
}
private void initRootDir(Bundle savedInstanceState) {
// If app was restarted programmatically, find where the user last left
// it
String restartDirPath = getIntent().getStringExtra(FileExplorerApp.EXTRA_FOLDER);
if (restartDirPath != null)
{
File restartDir = new File(restartDirPath);
if (restartDir.exists() && restartDir.isDirectory()) {
currentDir = restartDir;
getIntent().removeExtra(FileExplorerApp.EXTRA_FOLDER);
}
}
else if (savedInstanceState!=null && savedInstanceState.getSerializable(CURRENT_DIR_DIR) != null) {
currentDir = new File(savedInstanceState
.getSerializable(CURRENT_DIR_DIR).toString());
}
else
{
currentDir = getPreferenceHelper().getStartDir();
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(CURRENT_DIR_DIR, currentDir.getAbsolutePath());
}
private void prepareActionBar() {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
mSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, gotoLocations);
actionBar.setListNavigationCallbacks(mSpinnerAdapter, getActionbarListener(actionBar));
}
private OnNavigationListener getActionbarListener(final ActionBar actionBar) {
return new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
int selectedIndex = actionBar.getSelectedNavigationIndex();
if(selectedIndex == 0)
{
return false;
}
switch (selectedIndex) {
case 1:
listContents(getPreferenceHelper().getStartDir());
break;
case 2:
listContents(new File("/sdcard"));
break;
case 3:
listContents(Util.getDownloadsFolder());
break;
case 4:
listContents(Util.getDcimFolder());
break;
case 5:
openBookmarks(actionBar);
break;
case 6:
Util.gotoPath(currentDir.getAbsolutePath(), FileListActivity.this, new CancellationCallback() {
@Override
public void onCancel() {
actionBar.setSelectedNavigationItem(0);
}
});
break;
default:
break;
}
return true;
}
};
}
private void openBookmarks(final ActionBar actionBar) {
Intent intent = new Intent();
intent.setAction(FileExplorerApp.ACTION_OPEN_BOOKMARK);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(FileExplorerApp.EXTRA_IS_PICKER, isPicker);
actionBar.setSelectedNavigationItem(0);
startActivityForResult(intent, FileExplorerApp.REQ_PICK_BOOKMARK);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FileExplorerApp.REQ_PICK_BOOKMARK:
if(resultCode == RESULT_OK)
{
String selectedBookmark = data.getStringExtra(FileExplorerApp.EXTRA_SELECTED_BOOKMARK);
listContents(new File(selectedBookmark));
}
break;
default:
break;
}
}
@Override
protected void onResume() {
super.onResume();
if (shouldRestartApp) {
shouldRestartApp = false;
restartApp();
}
}
@Override
public void onBackPressed() {
if(isPicker)
{
super.onBackPressed();
return;
}
if (getPreferenceHelper().useBackNavigation()) {
if (Util.isRoot(currentDir)) {
finish();
} else {
gotoParent();
}
} else {
super.onBackPressed();
}
}
void select(File file) {
if (Util.isProtected(file)){
new Builder(this)
.setTitle(getString(R.string.access_denied))
.setMessage(
getString(R.string.cant_open_dir, file.getName()))
.show();
} else if (file.isDirectory()) {
listContents(file);
} else {
doFileAction(file);
}
}
private void doFileAction(File file) {
if (Util.isProtected(file) || file.isDirectory()) {
return;
}
if(isPicker)
{
pickFile(file);
return;
}
else
{
openFile(file);
return;
}
}
private void openFile(File file) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri, type == null ? "*/*" : type);
startActivity((Intent.createChooser(intent,
getString(R.string.open_using))));
}
private void pickFile(File file) {
Intent fileAttachIntent = app.getFileAttachIntent();
fileAttachIntent.setData(Uri.fromFile(file));
setResult(Activity.RESULT_OK, fileAttachIntent);
finish();
return;
}
public void listContents(File dir)
{
listContents(dir, null);
}
public void listContents(File dir, File previousOpenDirChild) {
if (!dir.isDirectory() || Util.isProtected(dir)) {
return;
}
if(previousOpenDirChild!=null)
{
this.previousOpenDirChild = new File(previousOpenDirChild.getAbsolutePath());
}
else
{
this.previousOpenDirChild = null;
}
new Finder(this).execute(dir);
}
private void gotoParent() {
if (Util.isRoot(currentDir)) {
// Do nothing finish();
} else {
listContents(currentDir.getParentFile(), currentDir);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if(isPicker)
{
inflater.inflate(R.menu.picker_options_menu, menu);
}
else
{
inflater.inflate(R.menu.options_menu, menu);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(!isPicker)
{
if(getPreferenceHelper().isMediaExclusionEnabled())
{
menu.findItem(R.id.menu_media_exclusion).setVisible(true);
menu.findItem(R.id.menu_media_exclusion).setChecked(excludeFromMedia);
}
else
{
menu.findItem(R.id.menu_media_exclusion).setVisible(false);
}
menu.findItem(R.id.menu_bookmark_toggle).setChecked(bookmarker.isBookmarked(currentDir.getAbsolutePath()));
if (Util.canPaste(currentDir)) {
menu.findItem(R.id.menu_paste).setVisible(true);
} else {
menu.findItem(R.id.menu_paste).setVisible(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
gotoParent();
return true;
case R.id.menu_cancel:
setResult(RESULT_CANCELED);
finish();
return true;
case R.id.menu_bookmark_toggle:
boolean setBookmark = item.isChecked();
item.setChecked(!setBookmark);
if(!setBookmark)
{
bookmarker.addBookmark(currentDir.getAbsolutePath());
}
else
{
bookmarker.removeBookmark(currentDir.getAbsolutePath());
}
return true;
case R.id.menu_media_exclusion:
item.setChecked(!excludeFromMedia);
setMediaExclusionForFolder();
return true;
case R.id.menu_goto:
Util.gotoPath(currentDir.getAbsolutePath(), this);
return true;
case R.id.menu_paste:
confirmPaste();
return true;
case R.id.menu_refresh:
refresh();
return true;
case R.id.menu_newfolder:
confirmCreateFolder();
return true;
case R.id.menu_settings:
Intent prefsIntent = new Intent(FileListActivity.this,
SettingsActivity.class);
startActivity(prefsIntent);
return true;
default:
super.onOptionsItemSelected(item);
break;
}
return true;
}
private void setMediaExclusionForFolder() {
if(excludeFromMedia)
{
//Now include folder in media
FileUtils.deleteQuietly(new File(currentDir, ".nomedia"));
excludeFromMedia = false;
}
else
{
try
{
FileUtils.touch(new File(currentDir, ".nomedia"));
excludeFromMedia = true;
}
catch(Exception e)
{
Log.e(TAG, "Error occurred while creating .nomedia file", e);
}
}
FileActionsHelper.rescanMedia(this);
refresh();
}
private void confirmPaste() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.confirm));
alert.setMessage(getString(R.string.confirm_paste_text,
Util.getFileToPaste().getName()));
alert.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
new FileMover(FileListActivity.this, Util
.getPasteMode()).execute(currentDir);
}
});
alert.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
private void confirmCreateFolder() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.create_folder));
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setHint(getString(R.string.enter_folder_name));
input.setSingleLine();
alert.setView(input);
alert.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence newDir = input.getText();
if (Util.mkDir(
currentDir.getAbsolutePath(), newDir)) {
listContents(currentDir);
}
}
});
alert.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
public synchronized void setCurrentDirAndChilren(File dir, FileListing folderListing) {
currentDir = dir;
List<FileListEntry> children = folderListing.getChildren();
excludeFromMedia = folderListing.isExcludeFromMedia();
TextView emptyText = (TextView) findViewById(android.R.id.empty);
if (emptyText != null) {
emptyText.setText(R.string.empty_folder);
}
files.clear();
files.addAll(children);
adapter.notifyDataSetChanged();
getActionBar().setSelectedNavigationItem(0);
if(Util.isRoot(currentDir))
{
gotoLocations[0] = getString(R.string.filesystem);
}
else
{
gotoLocations[0] = currentDir.getName();
}
if(previousOpenDirChild!=null && focusOnParent)
{
int position = files.indexOf(new FileListEntry(previousOpenDirChild.getAbsolutePath()));
if(position>=0)
explorerListView.setSelection(position);
}
else
{
explorerListView.setSelection(0);
}
mSpinnerAdapter.notifyDataSetChanged();
ActionBar ab = getActionBar();
ab.setSelectedNavigationItem(0);
ab.setSubtitle(getString(R.string.item_count_subtitle, children.size()));
if(Util.isRoot(currentDir) || currentDir.getParentFile()==null)
{
ab.setDisplayHomeAsUpEnabled(false);
ab.setTitle(getString(R.string.filesystem));
}
else
{
ab.setTitle(currentDir.getName());
ab.setDisplayHomeAsUpEnabled(true);
}
}
public void refresh() {
listContents(currentDir);
}
private void restartApp() {
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra(FileExplorerApp.EXTRA_FOLDER, currentDir.getAbsolutePath());
startActivity(i);
}
public boolean isInPickMode()
{
return isPicker;
}
public File getCurrentDir() {
return currentDir;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/activity/FileListActivity.java
|
Java
|
gpl3
| 16,569
|
package net.appositedesigns.fileexplorer.activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.MenuItem;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.util.FileActionsHelper;
import net.appositedesigns.fileexplorer.util.PreferenceHelper;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(new PreferenceHelper(this).getTheme());
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home)
{
onBackPressed();
return true;
}
else
{
return false;
}
}
/**
* Populate the activity with the top-level headers.
*/
@Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.prefs, target);
}
public static class NavigationPreferences extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.nav_prefs);
}
}
public static class GeekyPreferences extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.geeky_prefs);
Preference rescan = findPreference("pref_opt_rescan");
rescan.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
FileActionsHelper.rescanMedia(GeekyPreferences.this.getActivity());
return true;
}
});
}
}
public static class ViewPreferences extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.view_prefs);
}
}
public static class AboutPreferences extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.about_prefs);
Preference share = (Preference)findPreference("pref_opt_share");
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String text = getString(R.string.share_text);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_SUBJECT, "FileExplorer");
startActivity(Intent.createChooser(intent,
getString(R.string.share_via)));
return true;
}
});
}
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/activity/SettingsActivity.java
|
Java
|
gpl3
| 3,276
|
package net.appositedesigns.fileexplorer.activity;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.R.string;
import net.appositedesigns.fileexplorer.util.PreferenceHelper;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.widget.TextView;
public class EulaPopupBuilder {
public static AlertDialog create(final FileListActivity context) {
final TextView message = new TextView(context);
final SpannableString s = new SpannableString(
context.getText(R.string.eula_popup_text));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setText(s);
message.setMovementMethod(LinkMovementMethod.getInstance());
return new AlertDialog.Builder(context)
.setTitle(R.string.eula_popup_title).setCancelable(false)
.setPositiveButton(R.string.eula_accept, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new PreferenceHelper(context).markEulaAccepted();
dialog.dismiss();
context.refresh();
}
})
.setNegativeButton(R.string.eula_decline, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
context.finish();
}
})
.setView(message).create();
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/activity/EulaPopupBuilder.java
|
Java
|
gpl3
| 1,520
|
package net.appositedesigns.fileexplorer.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import net.appositedesigns.fileexplorer.FileExplorerApp;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.adapters.BookmarkListAdapter;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.PreferenceHelper;
import net.appositedesigns.fileexplorer.workers.BookmarkLoader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class BookmarkListActivity extends BaseFileListActivity {
protected static final String TAG = BookmarkListActivity.class.getName();
private BookmarkListAdapter adapter;
private ArrayList<FileListEntry> bookmarks;
private ListView bookmarkListView;
private boolean isPicker = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(new PreferenceHelper(this).getTheme());
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.main);
isPicker = getIntent().getBooleanExtra(FileExplorerApp.EXTRA_IS_PICKER, false);
bookmarks = new ArrayList<FileListEntry>();
initBookmarksList();
refresh();
bookmarkListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
return false;
}
});
bookmarkListView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
if(!isPicker)
{
FileListEntry bookmark = (FileListEntry)bookmarkListView.getAdapter().getItem(position);
removeBookmark(bookmark);
return true;
}
return false;
}
});
registerForContextMenu(bookmarkListView);
}
protected void removeBookmark(final FileListEntry bookmark) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage(getString(R.string.confirm_remove_bookmark, bookmark.getName()))
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
bookmarker.removeBookmark(bookmark.getPath().getAbsolutePath());
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setTitle(R.string.confirm);
AlertDialog confirm = builder.create();
confirm.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(!isPicker)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.bookmarks_options_menu, menu);
return true;
}
return false;
}
private void initBookmarksList() {
bookmarkListView = (ListView) getListView();
adapter = new BookmarkListAdapter(this, bookmarks);
bookmarkListView.setAdapter(adapter);
bookmarkListView.setTextFilterEnabled(true);
bookmarkListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (bookmarkListView.isClickable()) {
FileListEntry file = (FileListEntry) bookmarkListView
.getAdapter().getItem(position);
select(file.getPath());
}
}
});
}
protected void select(File path) {
Intent intent = new Intent();
intent.putExtra(FileExplorerApp.EXTRA_SELECTED_BOOKMARK, path.getAbsolutePath());
intent.putExtra(FileExplorerApp.EXTRA_IS_PICKER, isPicker);
setResult(Activity.RESULT_OK, intent);
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home)
{
onBackPressed();
return true;
}
else if(R.id.menu_settings == item.getItemId())
{
Intent prefsIntent = new Intent(this,
SettingsActivity.class);
startActivity(prefsIntent);
return true;
}
else if(R.id.menu_add_bookmark == item.getItemId())
{
promptBookmarkPath();
return true;
}
return false;
}
private void promptBookmarkPath() {
final EditText input = new EditText(this);
input.setSingleLine();
input.setHint(getString(R.string.add_bookmark_prompt_hint));
input.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
new Builder(this)
.setTitle(getString(R.string.add_bookmark_prompt))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence bookmarkPath = input.getText();
try
{
File toDir = new File(bookmarkPath.toString());
if(toDir.isDirectory() && toDir.exists())
{
bookmarker.addBookmark(bookmarkPath.toString());
}
else
{
throw new FileNotFoundException();
}
}
catch (Exception e) {
Log.e(TAG, "Error bookmarking path"+bookmarkPath, e);
new Builder(BookmarkListActivity.this)
.setTitle(getString(R.string.error))
.setMessage(getString(R.string.path_not_exist))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
public void setBookmarks(List<FileListEntry> childFiles) {
TextView emptyText = (TextView) findViewById(android.R.id.empty);
if (emptyText != null) {
emptyText.setText(R.string.no_bookmarks);
}
bookmarks.clear();
bookmarks.addAll(childFiles);
adapter.notifyDataSetChanged();
}
public void refresh() {
new BookmarkLoader(this).execute();
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/activity/BookmarkListActivity.java
|
Java
|
gpl3
| 6,757
|
package net.appositedesigns.fileexplorer.model;
import java.util.List;
public class FileListing {
private List<FileListEntry> children;
private boolean isExcludeFromMedia = false;
public List<FileListEntry> getChildren() {
return children;
}
public void setChildren(List<FileListEntry> children) {
this.children = children;
}
public boolean isExcludeFromMedia() {
return isExcludeFromMedia;
}
public void setExcludeFromMedia(boolean isExcludeFromMedia) {
this.isExcludeFromMedia = isExcludeFromMedia;
}
public FileListing(List<FileListEntry> children) {
super();
this.children = children;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/model/FileListing.java
|
Java
|
gpl3
| 654
|
package net.appositedesigns.fileexplorer.adapters;
import java.util.List;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.BookmarkListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.Util;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class BookmarkListAdapter extends BaseAdapter {
public static class ViewHolder
{
public TextView resName;
public ImageView resIcon;
public TextView resMeta;
}
private static final String TAG = BookmarkListAdapter.class.getName();
private BookmarkListActivity mContext;
private List<FileListEntry> files;
private LayoutInflater mInflater;
public BookmarkListAdapter(BookmarkListActivity context, List<FileListEntry> files) {
super();
mContext = context;
this.files = files;
mInflater = mContext.getLayoutInflater();
}
@Override
public int getCount() {
if(files == null)
{
return 0;
}
else
{
return files.size();
}
}
@Override
public Object getItem(int arg0) {
if(files == null)
return null;
else
return files.get(arg0);
}
public List<FileListEntry> getItems()
{
return files;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.bookmark_list_item, parent, false);
holder = new ViewHolder();
holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName);
holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta);
holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
final FileListEntry currentFile = files.get(position);
holder.resName.setText(currentFile.getName());
if(Util.isRoot(currentFile.getPath()))
{
holder.resName.setText(mContext.getString(R.string.filesystem_root));
}
holder.resIcon.setImageDrawable(Util.getIcon(mContext, currentFile.getPath()));
holder.resMeta.setText(currentFile.getPath().getAbsolutePath());
return convertView;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/adapters/BookmarkListAdapter.java
|
Java
|
gpl3
| 2,702
|
package net.appositedesigns.fileexplorer.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.Util;
import java.util.List;
public class FileListAdapter extends BaseAdapter {
public static class ViewHolder
{
public TextView resName;
public ImageView resIcon;
public TextView resMeta;
}
private static final String TAG = FileListAdapter.class.getName();
private FileListActivity mContext;
private List<FileListEntry> files;
private LayoutInflater mInflater;
public FileListAdapter(FileListActivity context, List<FileListEntry> files) {
super();
mContext = context;
this.files = files;
mInflater = mContext.getLayoutInflater();
}
@Override
public int getCount() {
if(files == null)
{
return 0;
}
else
{
return files.size();
}
}
@Override
public Object getItem(int arg0) {
if(files == null)
return null;
else
return files.get(arg0);
}
public List<FileListEntry> getItems()
{
return files;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.explorer_item, parent, false);
holder = new ViewHolder();
holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName);
holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta);
holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
final FileListEntry currentFile = files.get(position);
holder.resName.setText(currentFile.getName());
holder.resIcon.setImageDrawable(Util.getIcon(mContext, currentFile.getPath()));
String meta = Util.prepareMeta(currentFile, mContext);
holder.resMeta.setText(meta);
return convertView;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/adapters/FileListAdapter.java
|
Java
|
gpl3
| 2,561
|
package net.appositedesigns.fileexplorer.callbacks;
public interface CancellationCallback {
void onCancel();
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/callbacks/CancellationCallback.java
|
Java
|
gpl3
| 120
|
package net.appositedesigns.fileexplorer.callbacks;
public interface OperationCallback<T> {
T onSuccess();
void onFailure(Throwable e);
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/callbacks/OperationCallback.java
|
Java
|
gpl3
| 149
|
package net.appositedesigns.fileexplorer.callbacks;
import android.content.Intent;
import android.net.Uri;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.MimeTypeMap;
import android.widget.ShareActionProvider;
import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.FileActionsHelper;
public abstract class FileActionsCallback implements Callback {
private FileListActivity activity;
private FileListEntry file;
static int[] allOptions = {R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_props, R.id.menu_share, R.id.menu_rename, R.id.menu_zip, R.id.menu_unzip};
public FileActionsCallback(FileListActivity activity,
FileListEntry fileListEntry) {
this.activity = activity;
this.file = fileListEntry;
}
@Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
FileActionsHelper.doOperation(file, item.getItemId(), activity, new OperationCallback<Void>() {
@Override
public Void onSuccess() {
return null;
}
@Override
public void onFailure(Throwable e) {
}
});
mode.finish();
return true;
}
@Override
public boolean onCreateActionMode(final ActionMode actionMode, Menu menu) {
int[] validOptions = FileActionsHelper.getContextMenuOptions(file.getPath(), activity);
if(validOptions==null || validOptions.length ==0)
{
onDestroyActionMode(actionMode);
return false;
}
actionMode.setTitle(activity.getString(R.string.selected_,
file.getName()));
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
for(int o :allOptions)
{
boolean valid = false;
for(int v : validOptions)
{
if(o == v)
{
valid = true;
break;
}
}
if(!valid)
{
menu.removeItem(o);
}
else
{
if(o == R.id.menu_share)
{
MenuItem menuItem = menu.findItem(R.id.menu_share);
ShareActionProvider mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
mShareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
@Override
public boolean onShareTargetSelected(ShareActionProvider source,
Intent intent) {
actionMode.finish();
return false;
}
});
final Intent intent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(file.getPath());
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setType(type);
intent.setAction(Intent.ACTION_SEND);
intent.setType(type==null?"*/*":type);
intent.putExtra(Intent.EXTRA_STREAM, uri);
mShareActionProvider.setShareIntent(intent);
}
}
}
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/callbacks/FileActionsCallback.java
|
Java
|
gpl3
| 3,369
|
package net.appositedesigns.fileexplorer.util;
public class AbortionFlag {
private boolean aborted = false;
public synchronized void abort()
{
aborted = true;
}
public synchronized boolean isAborted()
{
return aborted;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/AbortionFlag.java
|
Java
|
gpl3
| 253
|
package net.appositedesigns.fileexplorer.util;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.callbacks.CancellationCallback;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public final class Util {
private static final String TAG = Util.class.getName();
private static File COPIED_FILE = null;
private static int pasteMode = 1;
public static final int PASTE_MODE_COPY = 0;
public static final int PASTE_MODE_MOVE = 1;
private Util(){}
public static synchronized void setPasteSrcFile(File f, int mode)
{
COPIED_FILE = f;
pasteMode = mode%2;
}
public static synchronized File getFileToPaste()
{
return COPIED_FILE;
}
public static synchronized int getPasteMode()
{
return pasteMode;
}
static boolean isMusic(File file) {
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
if(type == null)
return false;
else
return (type.toLowerCase().startsWith("audio/"));
}
static boolean isVideo(File file) {
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
if(type == null)
return false;
else
return (type.toLowerCase().startsWith("video/"));
}
public static boolean isPicture(File file) {
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
if(type == null)
return false;
else
return (type.toLowerCase().startsWith("image/"));
}
public static boolean isProtected(File path)
{
return (!path.canRead() && !path.canWrite());
}
public static boolean isUnzippable(File path)
{
return (path.isFile() && path.canRead() && path.getName().endsWith(".zip"));
}
public static boolean isRoot(File dir) {
return dir.getAbsolutePath().equals("/");
}
public static boolean isSdCard(File file) {
try {
return (file.getCanonicalPath().equals(Environment.getExternalStorageDirectory().getCanonicalPath()));
} catch (IOException e) {
return false;
}
}
public static Drawable getIcon(Context mContext, File file) {
if(!file.isFile()) //dir
{
if(Util.isProtected(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_sys_dir);
}
else if(Util.isSdCard(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_sdcard);
}
else
{
return mContext.getResources().getDrawable(R.drawable.filetype_dir);
}
}
else //file
{
String fileName = file.getName();
if(Util.isProtected(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_sys_file);
}
if(fileName.endsWith(".apk"))
{
return mContext.getResources().getDrawable(R.drawable.filetype_apk);
}
if(fileName.endsWith(".zip"))
{
return mContext.getResources().getDrawable(R.drawable.filetype_zip);
}
else if(Util.isMusic(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_music);
}
else if(Util.isVideo(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_video);
}
else if(Util.isPicture(file))
{
return mContext.getResources().getDrawable(R.drawable.filetype_image);
}
else
{
return mContext.getResources().getDrawable(R.drawable.filetype_generic);
}
}
}
public static boolean delete(File fileToBeDeleted) {
try
{
FileUtils.forceDelete(fileToBeDeleted);
return true;
} catch (IOException e) {
return false;
}
}
public static boolean mkDir(String canonicalPath, CharSequence newDirName) {
File newdir = new File(canonicalPath+File.separator+newDirName);
return newdir.mkdirs();
}
public static String prepareMeta(FileListEntry file,FileListActivity context) {
File f = file.getPath();
try
{
if(isProtected(f))
{
return context.getString(R.string.system_path);
}
if(file.getPath().isFile())
{
return context.getString(R.string.size_is, FileUtils.byteCountToDisplaySize(file.getSize()));
}
}
catch (Exception e) {
Log.e(Util.class.getName(), e.getMessage());
}
return "";
}
public static boolean paste(int mode, File destinationDir, AbortionFlag flag) {
Log.v(TAG, "Will now paste file on clipboard");
File fileBeingPasted = new File(getFileToPaste().getParent(),getFileToPaste().getName());
if(doPaste(mode, getFileToPaste(), destinationDir, flag))
{
if(getPasteMode() == PASTE_MODE_MOVE)
{
if(fileBeingPasted.isFile())
{
if(FileUtils.deleteQuietly(fileBeingPasted))
{
Log.i(TAG, "File deleted after paste "+fileBeingPasted.getAbsolutePath());
}
else
{
Log.w(TAG, "File NOT deleted after paste "+fileBeingPasted.getAbsolutePath());
}
}
else
{
try {
FileUtils.deleteDirectory(fileBeingPasted);
} catch (IOException e) {
Log.e(TAG, "Error while deleting directory after paste - "+fileBeingPasted.getAbsolutePath(), e);
return false;
}
}
}
return true;
}
else
{
return false;
}
}
private static boolean doPaste(int mode, File srcFile, File destinationDir, AbortionFlag flag) {
if(!flag.isAborted())
try
{
if(srcFile.isDirectory())
{
File newDir = new File(destinationDir.getAbsolutePath()+File.separator+srcFile.getName());
newDir.mkdirs();
for(File child : srcFile.listFiles())
{
doPaste(mode, child, newDir, flag);
}
return true;
}
else
{
FileUtils.copyFileToDirectory(srcFile, destinationDir);
return true;
}
}
catch (Exception e) {
return false;
}
else
{
return false;
}
}
public static boolean canPaste(File destDir) {
if(getFileToPaste() == null)
{
return false;
}
if(getFileToPaste().isFile())
{
return true;
}
try
{
if(destDir.getCanonicalPath().startsWith(COPIED_FILE.getCanonicalPath()))
{
return false;
}
else
{
return true;
}
}
catch (Exception e) {
return false;
}
}
public static boolean canShowQuickActions(FileListEntry currentFile, FileListActivity mContext) {
if(!mContext.getPreferenceHelper().useQuickActions() || mContext.isInPickMode())
{
return false;
}
File path = currentFile.getPath();
if(isProtected(path))
{
return false;
}
if(isSdCard(path))
{
return false;
}
else
{
return true;
}
}
public static CharSequence[] getFileProperties(FileListEntry file, FileListActivity context) {
if(Util.isSdCard(file.getPath()))
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long sdAvailSize = (long)stat.getAvailableBlocks() *(long)stat.getBlockSize();
long totalSize = (long)stat.getBlockCount() *(long)stat.getBlockSize();
return new CharSequence[]{context.getString(R.string.total_capacity, Util.getSizeStr(totalSize)),
context.getString(R.string.free_space, Util.getSizeStr(sdAvailSize))};
}
else if(file.getPath().isFile())
return new CharSequence[]{context.getString(R.string.filepath_is, file.getPath().getAbsolutePath()),
context.getString(R.string.mtime_is, DateFormat.getDateFormat(context).format(file.getLastModified())),
context.getString(R.string.size_is, FileUtils.byteCountToDisplaySize(file.getSize()))};
else
{
return new CharSequence[]{context.getString(R.string.filepath_is, file.getPath().getAbsolutePath()),
context.getString(R.string.mtime_is, DateFormat.getDateFormat(context).format(file.getLastModified()))};
}
}
private static String getSizeStr(long bytes) {
if(bytes >= FileUtils.ONE_GB)
{
return (double)Math.round((((double)bytes / FileUtils.ONE_GB)*100))/100 + " GB";
}
else if(bytes >= FileUtils.ONE_MB)
{
return (double)Math.round((((double)bytes / FileUtils.ONE_MB)*100))/100 + " MB";
}
else if(bytes >= FileUtils.ONE_KB)
{
return (double)Math.round((((double)bytes / FileUtils.ONE_KB)*100))/100 + " KB";
}
return bytes+" bytes";
}
public static Map<String, Long> getDirSizes(File dir)
{
Map<String, Long> sizes = new HashMap<String, Long>();
try {
Process du = Runtime.getRuntime().exec("/system/bin/du -b -d1 "+dir.getCanonicalPath(), new String[]{}, Environment.getRootDirectory());
BufferedReader in = new BufferedReader(new InputStreamReader(
du.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
String[] parts = line.split("\\s+");
String sizeStr = parts[0];
Long size = Long.parseLong(sizeStr);
String path = parts[1];
sizes.put(path, size);
}
} catch (IOException e) {
Log.w(TAG, "Could not execute DU command for "+dir.getAbsolutePath(), e);
}
return sizes;
}
public static void gotoPath(final String currentPath, final FileListActivity mContext) {
gotoPath(currentPath, mContext, null);
}
public static void gotoPath(final String currentPath, final FileListActivity mContext,final CancellationCallback callback) {
final EditText input = new EditText(mContext);
input.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
input.setSingleLine();
new Builder(mContext)
.setTitle(mContext.getString(R.string.goto_path))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence toPath = input.getText();
try
{
File toDir = new File(toPath.toString());
if(toDir.isDirectory() && toDir.exists())
{
mContext.listContents(toDir);
}
else
{
throw new FileNotFoundException();
}
}
catch (Exception e) {
Log.e(TAG, "Error navigating to path"+toPath, e);
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.path_not_exist))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
if(callback != null)
callback.onCancel();
}
})
.show();
input.setText(currentPath);
}
public static File getDownloadsFolder() {
return new File("/sdcard/"+Environment.DIRECTORY_DOWNLOADS);
}
public static File getDcimFolder() {
return new File("/sdcard/"+Environment.DIRECTORY_DCIM);
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/Util.java
|
Java
|
gpl3
| 11,837
|
package net.appositedesigns.fileexplorer.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* The class provides the utility method to zip files or folders uses
* java.util.zip package underneath
*/
public class ZipUtil {
static public void zipFolder(String srcFolder, String destZipFile,
AbortionFlag flag) throws Exception {
if (flag.isAborted()) {
return;
}
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try
{
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, flag, zip);
}
finally
{
zip.flush();
zip.close();
}
}
static public void zipFile(String srcFile, String destZipFile,
AbortionFlag flag) throws Exception {
if (flag.isAborted()) {
return;
}
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try
{
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFileToZip("", srcFile, flag, zip);
}
finally
{
zip.flush();
zip.close();
}
}
static private void addFileToZip(String path, String srcFile,
AbortionFlag flag, ZipOutputStream zip) throws Exception {
if (flag.isAborted()) {
return;
}
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, flag, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder,
AbortionFlag flag, ZipOutputStream zip) throws Exception {
if (flag.isAborted()) {
return;
}
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName,
flag, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
+ fileName, flag, zip);
}
}
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/ZipUtil.java
|
Java
|
gpl3
| 2,306
|
package net.appositedesigns.fileexplorer.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Instrumentation.ActivityResult;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.Toast;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.callbacks.CancellationCallback;
import net.appositedesigns.fileexplorer.callbacks.OperationCallback;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.workers.Trasher;
import net.appositedesigns.fileexplorer.workers.Unzipper;
import net.appositedesigns.fileexplorer.workers.Zipper;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class FileActionsHelper {
protected static final String TAG = FileActionsHelper.class.getName();
public static void copyFile(File file, FileListActivity mContext)
{
Util.setPasteSrcFile(file,Util.PASTE_MODE_COPY);
Toast.makeText(mContext.getApplicationContext(), mContext.getString(R.string.copied_toast, file.getName()), Toast.LENGTH_SHORT).show();
mContext.invalidateOptionsMenu();
}
public static void cutFile(final File file, final FileListActivity mContext)
{
Util.setPasteSrcFile(file,Util.PASTE_MODE_MOVE);
Toast.makeText(mContext.getApplicationContext(), mContext.getString(R.string.cut_toast, file.getName()), Toast.LENGTH_SHORT).show();
mContext.invalidateOptionsMenu();
}
public static void showProperties(final FileListEntry file, final FileListActivity mContext)
{
if(mContext!=null)
new Builder(mContext)
.setTitle(mContext.getString(R.string.properties_for, file.getName()))
.setItems(Util.getFileProperties(file, mContext), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
public static void deleteFile(final File file, final FileListActivity mContext,final OperationCallback<Void> callback)
{
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(true);
builder.setMessage(mContext.getString(R.string.confirm_delete, file.getName()))
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new Trasher(mContext, callback).execute(file);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setTitle(R.string.confirm);
AlertDialog confirm = builder.create();
if(mContext!=null)
{
confirm.show();
}
}
public static int[] getContextMenuOptions(File file, FileListActivity caller) {
PreferenceHelper prefs = new PreferenceHelper(caller);
if(Util.isProtected(file))
{
return new int[]{};
}
if(Util.isSdCard(file))
{
return new int[]{R.id.menu_props};
}
else if(file.isDirectory())
{
if(prefs.isZipEnabled())
{
return new int[]{R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_props};
}
return new int[]{R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props};
}
else if(Util.isUnzippable(file))
{
if(prefs.isZipEnabled())
{
return new int[]{R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_unzip, R.id.menu_props};
}
return new int[]{R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props};
}
else
{
if(prefs.isZipEnabled())
{
return new int[]{R.id.menu_share, R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_props};
}
return new int[]{R.id.menu_share, R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props};
}
}
public static void rename(final File file, final FileListActivity mContext, final OperationCallback<Void> callback)
{
final EditText input = new EditText(mContext);
input.setHint(mContext.getString(R.string.enter_new_name));
input.setSingleLine();
if(mContext!=null)
new Builder(mContext)
.setTitle(mContext.getString(R.string.rename_dialog_title, file.getName()))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence newName = input.getText();
try
{
File parentFolder = file.getParentFile();
if(file.renameTo(new File(parentFolder, newName.toString())))
{
if(callback!=null)
{
callback.onSuccess();
}
Toast.makeText(mContext, mContext.getString(R.string.rename_toast, file.getName(), newName), Toast.LENGTH_LONG).show();
mContext.refresh();
}
else
{
if(callback!=null)
{
callback.onFailure(new Exception());
}
if(mContext!=null)
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
catch (Exception e) {
if(callback!=null)
{
callback.onFailure(e);
}
Log.e(TAG, "Error occured while renaming path", e);
if(mContext!=null)
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
public static void zip(final File file, final FileListActivity mContext)
{
try
{
final File zipLoc = new PreferenceHelper(mContext).getZipDestinationDir();
if(zipLoc == null)
{
final EditText zipDestinationInput = new EditText(mContext);
zipDestinationInput.setSingleLine();
new Builder(mContext)
.setTitle(mContext.getString(R.string.unzip_destination))
.setView(zipDestinationInput)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence destinationPath = zipDestinationInput.getText();
try
{
File destination = new File(destinationPath.toString());
if(destination.isFile() && destination.exists())
{
throw new FileNotFoundException();
}
else
{
promptZipFileName(file, mContext, destination);
}
}
catch (Exception e) {
Log.e(TAG, "Error zipping to path"+destinationPath, e);
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.zip_failed))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
zipDestinationInput.setText(mContext.getCurrentDir().getAbsolutePath());
}
else
{
promptZipFileName(file, mContext, zipLoc);
}
}
catch (Exception e) {
Log.e(TAG, "Zip destination was invalid", e);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.zip_dest_invalid))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
}
private static void promptZipFileName(final File file,
final FileListActivity mContext,final File zipLoc) {
final EditText input = new EditText(mContext);
input.setHint(mContext.getString(R.string.enter_zip_file_name));
input.setSingleLine();
new Builder(mContext)
.setTitle(mContext.getString(R.string.zip_dialog, zipLoc.getAbsolutePath()))
.setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zipName = input.getText().toString();
new Zipper(zipName,zipLoc, mContext).execute(file);
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
public static void unzip(final FileListActivity mContext, final List<File> zipFiles, final CancellationCallback callback)
{
final EditText input = new EditText(mContext);
input.setSingleLine();
new Builder(mContext)
.setTitle(mContext.getString(R.string.unzip_destination))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence destinationPath = input.getText();
try
{
File destination = new File(destinationPath.toString());
if(destination.isFile() && destination.exists())
{
throw new FileNotFoundException();
}
else
{
new Unzipper(mContext, destination).execute((File[])(new ArrayList<File>(zipFiles).toArray(new File[0])));
}
}
catch (Exception e) {
Log.e(TAG, "Error unzipping to path"+destinationPath, e);
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.unzip_failed_dest_file))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
if(callback != null)
callback.onCancel();
}
})
.show();
input.setText(mContext.getCurrentDir().getAbsolutePath());
}
public static void doOperation(FileListEntry entry,int action, FileListActivity mContext, OperationCallback<Void> callback) {
File file = entry.getPath();
switch (action) {
case R.id.menu_cancel:
ActivityResult result = new ActivityResult(Activity.RESULT_CANCELED, null);
mContext.finish();
break;
case R.id.menu_copy:
copyFile(file, mContext);
break;
case R.id.menu_cut:
cutFile(file, mContext);
break;
case R.id.menu_delete:
deleteFile(file, mContext, callback);
break;
case R.id.menu_share:
share(file, mContext);
break;
case R.id.menu_rename:
rename(file, mContext, callback);
break;
case R.id.menu_zip:
zip(file, mContext);
break;
case R.id.menu_unzip:
List<File> zipFiles = new ArrayList<File>();
zipFiles.add(file);
unzip(mContext, zipFiles, null);
break;
case R.id.menu_props:
showProperties(entry, mContext);
break;
default:
break;
}
}
public static void rescanMedia(Activity mContext) {
mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
.parse("file://" + Environment.getExternalStorageDirectory())));
Toast.makeText(mContext, R.string.media_rescan_started, Toast.LENGTH_SHORT).show();
Notification noti = new Notification.Builder(mContext)
.setContentTitle(mContext.getString(R.string.media_rescan_started))
.setContentText(mContext.getString(R.string.media_rescan_started_desc))
.setSmallIcon(R.drawable.ic_notif_sdcard_rescan)
.setAutoCancel(true)
.build();
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
public static void share(File file, Context mContext) {
final Intent intent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setType(type);
intent.setAction(Intent.ACTION_SEND);
intent.setType(type==null?"*/*":type);
intent.putExtra(Intent.EXTRA_STREAM, uri);
mContext.startActivity(Intent.createChooser(intent,mContext.getString(R.string.share_via)));
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/FileActionsHelper.java
|
Java
|
gpl3
| 13,797
|
package net.appositedesigns.fileexplorer.util;
import java.util.Comparator;
import net.appositedesigns.fileexplorer.activity.BaseFileListActivity;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.PreferenceHelper.SortField;
public class FileListSorter implements Comparator<FileListEntry> {
private BaseFileListActivity mContext;
private boolean dirsOnTop = false;
private SortField sortField;
private int dir;
public FileListSorter(BaseFileListActivity context){
mContext = context;
PreferenceHelper util = new PreferenceHelper(mContext);
dirsOnTop = util.isShowDirsOnTop();
sortField = util.getSortField();
dir = util.getSortDir();
}
@Override
public int compare(FileListEntry file1, FileListEntry file2) {
if(dirsOnTop)
{
if(file1.getPath().isDirectory() && file2.getPath().isFile())
{
return -1;
}
else if(file2.getPath().isDirectory() && file1.getPath().isFile())
{
return 1;
}
}
switch (sortField) {
case NAME:
return dir * file1.getName().compareToIgnoreCase(file2.getName());
case MTIME:
return dir * file1.getLastModified().compareTo(file2.getLastModified());
case SIZE:
return dir * Long.valueOf(file1.getSize()).compareTo(file2.getSize());
default:
break;
}
return 0;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/FileListSorter.java
|
Java
|
gpl3
| 1,484
|
package net.appositedesigns.fileexplorer.util;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import net.appositedesigns.fileexplorer.activity.BookmarkListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public final class BookmarksHelper {
private Activity mContext;
private static List<String> bookmarkedPaths = new ArrayList<String>();
public static final String BOOKMARKS = "bookmarks";
public static final String BOOKMARKS_FILE = "bookmarks_v2.5";
public BookmarksHelper(Activity activity)
{
mContext = activity;
refreshBookmarkCache();
}
public void addBookmark(final String path) {
new Thread(new Runnable() {
@Override
public void run() {
final String bookmarkCsv = mContext.getSharedPreferences(
BOOKMARKS_FILE, Context.MODE_PRIVATE).getString(
BOOKMARKS, "");
StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n");
boolean found = false;
while (tokens.hasMoreTokens()) {
String bookmark = tokens.nextToken();
if (bookmark != null && bookmark.equalsIgnoreCase(path)) {
found = true;
break;
}
}
if (!found) {
SharedPreferences.Editor editor = mContext
.getSharedPreferences(BOOKMARKS_FILE,
Context.MODE_PRIVATE).edit();
editor.putString(BOOKMARKS, bookmarkCsv + "\n" + path);
editor.commit();
refreshBookmarkCache();
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mContext instanceof BookmarkListActivity)
{
BookmarkListActivity bookmarkListActivity = (BookmarkListActivity)mContext;
bookmarkListActivity.refresh();
}
}
});
}
}
}).start();
}
public List<FileListEntry> getBookmarks() {
String bookmarkCsv = mContext.getSharedPreferences(BOOKMARKS_FILE,
Context.MODE_PRIVATE).getString(BOOKMARKS, "");
StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n");
List<FileListEntry> files = new ArrayList<FileListEntry>();
while (tokens.hasMoreTokens()) {
String bookmark = tokens.nextToken();
File dir = new File(bookmark);
if (dir.exists() && dir.isDirectory()) {
FileListEntry entry = new FileListEntry(bookmark);
files.add(entry);
}
}
return files;
}
public boolean isBookmarked(String path) {
return bookmarkedPaths.contains(path);
}
private void refreshBookmarkCache() {
String bookmarkCsv = mContext.getSharedPreferences(BOOKMARKS_FILE,
Context.MODE_PRIVATE).getString(BOOKMARKS, "");
StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n");
bookmarkedPaths.clear();
while (tokens.hasMoreTokens()) {
String bookmark = tokens.nextToken();
File dir = new File(bookmark);
if (dir.exists() && dir.isDirectory()) {
synchronized (bookmarkedPaths) {
bookmarkedPaths.add(bookmark);
}
}
}
}
public void removeBookmark(final String path) {
AsyncTask<String, String, String> task = new AsyncTask<String, String, String>(){
@Override
protected String doInBackground(String... strings) {
String bookmarkCsv = mContext.getSharedPreferences(
BOOKMARKS_FILE, Context.MODE_PRIVATE).getString(
BOOKMARKS, "");
StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n");
final StringBuffer buffer = new StringBuffer();
while (tokens.hasMoreTokens()) {
String bookmark = tokens.nextToken();
if (bookmark != null && !bookmark.equals(path)) {
buffer.append("\n");
buffer.append(bookmark);
}
}
SharedPreferences.Editor editor = mContext
.getSharedPreferences(BOOKMARKS_FILE,
Context.MODE_PRIVATE).edit();
editor.putString(BOOKMARKS, buffer.toString());
editor.commit();
refreshBookmarkCache();
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
if(mContext instanceof BookmarkListActivity)
{
BookmarkListActivity bookmarkListActivity = (BookmarkListActivity)mContext;
bookmarkListActivity.refresh();
}
}
});
return null;
}
}.execute();
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/BookmarksHelper.java
|
Java
|
gpl3
| 5,004
|
package net.appositedesigns.fileexplorer.util;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import net.appositedesigns.fileexplorer.FileExplorerApp;
import net.appositedesigns.fileexplorer.exception.LocationInvalidException;
import java.io.File;
public final class PreferenceHelper {
public enum SortField {
NAME, MTIME, SIZE
}
private Activity mContext;
public static final String EULA_ACCEPTED = "eula_accepted_v2.5";
public static final String EULA_MARKER = "eula_marker_file_v2.5";
public static final String PREF_HOME_DIR = "homeDir";
public static final String PREF_SDCARD_OPTIONS = "sdCardOptions";
public static final String PREF_SHOW_DIR_SIZES = "showDirSizes";
public static final String PREF_SHOW_DIRS_FIRST = "showDirsFirst";
public static final String PREF_SHOW_HIDDEN = "showHidden";
public static final String PREF_SHOW_SYSFILES = "showSysFiles";
public static final String PREF_SORT_DIR = "sort.dir";
public static final String PREF_SORT_FIELD = "sort.field";
public static final String PREF_THEME = "theme";
public static final String PREF_USE_BACK_BUTTON = "useBackButton";
private static final String PREF_NAVIGATE_FOCUS_ON_PARENT = "focusOnParent";
public static final String PREF_USE_QUICKACTIONS = "useQuickActions";
public static final String PREF_ZIP_ENABLE = "zipEnable";
public static final String PREF_ZIP_USE_ZIP_FOLDER = "useZipFolder";
public static final String PREF_ZIP_LOCATION = "zipLocation";
public static final String PREF_MEDIA_EXCLUSIONS = "media_exclusions";
public static final String VALUE_SORT_DIR_ASC = "asc";
public static final String VALUE_SORT_DIR_DESC = "desc";
public static final String VALUE_SORT_FIELD_M_TIME = "mtime";
public static final String VALUE_SORT_FIELD_NAME = "name";
public static final String VALUE_SORT_FIELD_SIZE = "size";
public static final String VALUE_THEME_BLACK = "theme_black";
public static final String VALUE_THEME_WHITE = "theme_white";
public static final String VALUE_THEME_WHITE_BLACK = "theme_white_black";
public PreferenceHelper(Activity context) {
mContext = context;
}
public boolean isShowDirsOnTop() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_SHOW_DIRS_FIRST, true);
}
public boolean isShowHidden() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_SHOW_HIDDEN, false);
}
public boolean useBackNavigation() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_USE_BACK_BUTTON, false);
}
public boolean useQuickActions() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_USE_QUICKACTIONS, true);
}
public SortField getSortField() {
String field = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(PREF_SORT_FIELD, VALUE_SORT_FIELD_NAME);
if (VALUE_SORT_FIELD_NAME.equalsIgnoreCase(field)) {
return SortField.NAME;
} else if (VALUE_SORT_FIELD_M_TIME.equalsIgnoreCase(field)) {
return SortField.MTIME;
} else if (VALUE_SORT_FIELD_SIZE.equalsIgnoreCase(field)) {
return SortField.SIZE;
} else {
return SortField.NAME;
}
}
public int getSortDir() {
String field = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(PREF_SORT_DIR, "asc");
if (VALUE_SORT_DIR_ASC.equalsIgnoreCase(field)) {
return 1;
} else {
return -1;
}
}
public File getStartDir() {
String dirPath = PreferenceManager
.getDefaultSharedPreferences(mContext).getString(PREF_HOME_DIR,
"/");
File homeDir = new File(dirPath);
if (homeDir.exists() && homeDir.isDirectory()) {
return homeDir;
} else {
return new File("/");
}
}
public boolean isShowSystemFiles() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_SHOW_SYSFILES, true);
}
public File getZipDestinationDir() throws LocationInvalidException {
String dirPath = PreferenceManager
.getDefaultSharedPreferences(mContext).getString(
PREF_ZIP_LOCATION, "/sdcard/zipped");
Boolean useZipFolder = PreferenceManager.getDefaultSharedPreferences(
mContext).getBoolean(PREF_ZIP_USE_ZIP_FOLDER, false);
if (!useZipFolder) {
return null;
}
File dir = new File(dirPath);
if (dir.exists() && dir.isDirectory()) {
return dir;
} else if (!dir.exists()) {
dir.mkdirs();
return dir;
} else {
throw new LocationInvalidException(dirPath);
}
}
public boolean isEnableSdCardOptions() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_SDCARD_OPTIONS, true);
}
public boolean focusOnParent() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_NAVIGATE_FOCUS_ON_PARENT, true);
}
public boolean isZipEnabled() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_ZIP_ENABLE, false);
}
public boolean isMediaExclusionEnabled() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean(PREF_MEDIA_EXCLUSIONS, false);
}
public boolean isEulaAccepted() {
return mContext.getSharedPreferences(EULA_MARKER, Context.MODE_PRIVATE)
.getBoolean(EULA_ACCEPTED, false);
}
public void markEulaAccepted() {
SharedPreferences.Editor editor = mContext.getSharedPreferences(
EULA_MARKER, Context.MODE_PRIVATE).edit();
editor.putBoolean(EULA_ACCEPTED, true);
editor.commit();
}
public int getTheme() {
return FileExplorerApp.THEME_WHITE;
/*
String theme = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(PREF_THEME, VALUE_THEME_WHITE);
if (VALUE_THEME_BLACK.equalsIgnoreCase(theme)) {
return FileExplorerApp.THEME_BLACK;
} else if (VALUE_THEME_WHITE_BLACK.equalsIgnoreCase(theme)) {
return FileExplorerApp.THEME_WHITE_BLACK;
} else {
return FileExplorerApp.THEME_WHITE;
}
*/
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/util/PreferenceHelper.java
|
Java
|
gpl3
| 6,190
|
package net.appositedesigns.fileexplorer.workers;
import java.io.File;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.exception.LocationInvalidException;
import net.appositedesigns.fileexplorer.util.AbortionFlag;
import net.appositedesigns.fileexplorer.util.ZipUtil;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.util.Log;
public class Zipper extends AsyncTask<File, Integer, String> {
private static final String TAG = Zipper.class.getName();
private AbortionFlag flag;
private FileListActivity caller;
private String zipName;
private ProgressDialog zipProgress;
private boolean zippedAtleastOne;
private File destination;
public Zipper(String zipName, File destination, FileListActivity mContext) {
this.destination = destination;
this.flag = new AbortionFlag();
this.caller = mContext;
this.zipName = zipName;
}
@Override
protected void onPostExecute(String result) {
final String zipFile = result;
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if (zipProgress != null && zipProgress.isShowing()) {
zipProgress.dismiss();
}
}
});
if(zipFile!=null)
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
caller.refresh();
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(caller.getString(R.string.success))
.setMessage(caller.getString(R.string.zip_success, zipFile))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
}
@Override
protected String doInBackground(File... params) {
try
{
File zipDest = destination;
File zipFile = new File(zipDest, zipName+".zip");
zippedAtleastOne = false;
for(File fileToBeZipped : params)
{
if(flag.isAborted())
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
String message = zippedAtleastOne?caller.getString(R.string.zip_abort_partial):caller.getString(R.string.zip_aborted);
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(caller.getString(R.string.abort))
.setMessage(message)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
else
{
if(fileToBeZipped.isDirectory())
{
if(fileToBeZipped.listFiles().length==0)
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(caller.getString(R.string.zip))
.setMessage(caller.getString(R.string.zip_dir_empty))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
continue;
}
else
{
ZipUtil.zipFolder(fileToBeZipped.getAbsolutePath(), zipFile.getAbsolutePath(),flag);
zippedAtleastOne = true;
}
}
else
{
ZipUtil.zipFile(fileToBeZipped.getAbsolutePath(), zipFile.getAbsolutePath(),flag);
zippedAtleastOne = true;
}
}
if(zippedAtleastOne)
{
return zipFile.getAbsolutePath();
}
}
}
catch (LocationInvalidException e) {
Log.e(TAG, "Zip destination was invalid", e);
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(caller.getString(R.string.error))
.setMessage(caller.getString(R.string.zip_dest_invalid))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
catch(Exception e)
{
Log.e(TAG, "An error occured while running in background", e);
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(caller.getString(R.string.zip))
.setMessage(caller.getString(R.string.zip_dir_empty))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
return null;
}
@Override
protected void onPreExecute() {
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
zipProgress = new ProgressDialog(caller);
zipProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
zipProgress.setMessage(caller.getString(R.string.zip_in_progress));
zipProgress.setButton(caller.getString(R.string.run_in_background), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
zipProgress.setButton2(caller.getString(R.string.cancel), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
zipProgress.getButton(which).setText(R.string.cancelling);
Zipper.this.flag.abort();
}
});
zipProgress.show();
}
});
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/Zipper.java
|
Java
|
gpl3
| 6,303
|
package net.appositedesigns.fileexplorer.workers;
import java.io.File;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.util.AbortionFlag;
import net.appositedesigns.fileexplorer.util.Util;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class FileMover extends AsyncTask<File, Integer, Boolean>
{
private static final String TAG = FileMover.class.getName();
private int mode= 1;
private AbortionFlag flag;
private FileListActivity caller;
private ProgressDialog moveProgressDialog;
public FileMover(FileListActivity context, int mode) {
caller = context;
this.mode =mode;
flag = new AbortionFlag();
}
@Override
protected void onPostExecute(Boolean result) {
Log.v(TAG, "Inside post execute. Result of paste operation is - "+result);
if(result)
{
if(mode==Util.PASTE_MODE_MOVE)
{
Log.v(TAG, "Paste mode was MOVE - set src file to null");
Util.setPasteSrcFile(null, 0);
}
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(moveProgressDialog.isShowing())
{
moveProgressDialog.dismiss();
}
if(mode==Util.PASTE_MODE_COPY)
{
Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.copy_complete), Toast.LENGTH_LONG);
}
else
{
Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.move_complete), Toast.LENGTH_LONG);
}
caller.refresh();
}
});
}
else
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(moveProgressDialog.isShowing())
{
moveProgressDialog.dismiss();
}
Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.generic_operation_failed), Toast.LENGTH_LONG);
}
});
}
}
@Override
protected Boolean doInBackground(File... params) {
Log.v(TAG, "Started doInBackground");
File destDir = params[0];
return Util.paste(mode, destDir, flag);
}
@Override
protected void onPreExecute() {
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
String message = caller.getString(R.string.copying_path,Util.getFileToPaste().getName());
if(mode==Util.PASTE_MODE_MOVE)
{
message =
caller.getString(R.string.moving_path,Util.getFileToPaste().getName());
}
moveProgressDialog = new ProgressDialog(caller);
moveProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
moveProgressDialog.setMessage(message);
moveProgressDialog.setButton(caller.getString(R.string.run_in_background), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
moveProgressDialog.setButton2(caller.getString(R.string.cancel), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
FileMover.this.flag.abort();
}
});
moveProgressDialog.show();
}
});
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/FileMover.java
|
Java
|
gpl3
| 3,427
|
package net.appositedesigns.fileexplorer.workers;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.model.FileListing;
import net.appositedesigns.fileexplorer.util.FileListSorter;
import net.appositedesigns.fileexplorer.util.Util;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
public class Finder extends AsyncTask<File, Integer, FileListing>
{
private static final String TAG = Finder.class.getName();
private FileListActivity caller;
private ProgressDialog waitDialog;
private File currentDir;
public Finder(FileListActivity caller) {
this.caller = caller;
}
@Override
protected void onPostExecute(FileListing result) {
FileListing childFilesList = result;
Log.v(TAG, "Children for "+currentDir.getAbsolutePath()+" received");
if(waitDialog!=null && waitDialog.isShowing())
{
waitDialog.dismiss();
}
Log.v(TAG, "Children for "+currentDir.getAbsolutePath()+" passed to caller");
caller.setCurrentDirAndChilren(currentDir,childFilesList);
}
@Override
protected FileListing doInBackground(File... params) {
Thread waitForASec = new Thread() {
@Override
public void run() {
waitDialog = new ProgressDialog(caller);
waitDialog.setTitle("");
waitDialog.setMessage(caller.getString(R.string.querying_filesys));
waitDialog.setIndeterminate(true);
try {
Thread.sleep(100);
if(this.isInterrupted())
{
return;
}
else
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(waitDialog!=null)
waitDialog.show();
}
});
}
} catch (InterruptedException e) {
Log.e(TAG, "Progressbar waiting thread encountered exception ",e);
e.printStackTrace();
}
}
};
caller.runOnUiThread(waitForASec);
currentDir = params[0];
Log.v(TAG, "Received directory to list paths - "+currentDir.getAbsolutePath());
String[] children = currentDir.list();
FileListing listing = new FileListing(new ArrayList<FileListEntry>());
List<FileListEntry> childFiles = listing.getChildren();
boolean showHidden = caller.getPreferenceHelper().isShowHidden();
boolean showSystem = caller.getPreferenceHelper().isShowSystemFiles();
Map<String, Long> dirSizes = Util.getDirSizes(currentDir);
for(String fileName : children)
{
if(".nomedia".equals(fileName))
{
listing.setExcludeFromMedia(true);
}
File f = new File(currentDir.getAbsolutePath()+File.separator+fileName);
if(!f.exists())
{
continue;
}
if(Util.isProtected(f) && !showSystem)
{
continue;
}
if(f.isHidden() && !showHidden)
{
continue;
}
String fname = f.getName();
FileListEntry child = new FileListEntry();
child.setName(fname);
child.setPath(f);
if(f.isDirectory())
{
try
{
Long dirSize = dirSizes.get(f.getCanonicalPath());
child.setSize(dirSize);
}
catch (Exception e) {
Log.w(TAG, "Could not find size for "+child.getPath().getAbsolutePath());
child.setSize(0);
}
}
else
{
child.setSize(f.length());
}
child.setLastModified(new Date(f.lastModified()));
childFiles.add(child);
}
FileListSorter sorter = new FileListSorter(caller);
Collections.sort(childFiles, sorter);
Log.v(TAG, "Will now interrupt thread waiting to show progress bar");
if(waitForASec.isAlive())
{
try
{
waitForASec.interrupt();
}
catch (Exception e) {
Log.e(TAG, "Error while interrupting thread",e);
}
}
return listing;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/Finder.java
|
Java
|
gpl3
| 4,111
|
package net.appositedesigns.fileexplorer.workers;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.BookmarkListActivity;
import net.appositedesigns.fileexplorer.model.FileListEntry;
import net.appositedesigns.fileexplorer.util.FileListSorter;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
public class BookmarkLoader extends AsyncTask<File, Integer, List<FileListEntry>>
{
private static final String TAG = BookmarkLoader.class.getName();
private BookmarkListActivity caller;
private ProgressDialog waitDialog;
public BookmarkLoader(BookmarkListActivity caller) {
this.caller = caller;
}
@Override
protected void onPostExecute(List<FileListEntry> result) {
final List<FileListEntry> childFiles = result;
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(waitDialog!=null && waitDialog.isShowing())
{
waitDialog.dismiss();
}
Log.v(TAG, "Bookmarks for passed to caller");
caller.setBookmarks(childFiles);
if(childFiles.size()>0)
{
caller.getActionBar().setSubtitle(caller.getString(R.string.bookmarks_count, childFiles.size()));
}
else
{
caller.getActionBar().setSubtitle(caller.getString(R.string.bookmarks_count_0));
}
}
});
}
@Override
protected List<FileListEntry> doInBackground(File... params) {
Thread waitForASec = new Thread() {
@Override
public void run() {
waitDialog = new ProgressDialog(caller);
waitDialog.setTitle("");
waitDialog.setMessage(caller.getString(R.string.querying_filesys));
waitDialog.setIndeterminate(true);
try {
Thread.sleep(100);
if(this.isInterrupted())
{
return;
}
else
{
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(waitDialog!=null)
waitDialog.show();
}
});
}
} catch (InterruptedException e) {
Log.e(TAG, "Progressbar waiting thread encountered exception ",e);
e.printStackTrace();
}
}
};
caller.runOnUiThread(waitForASec);
List<FileListEntry> childFiles = new ArrayList<FileListEntry>(caller.getBookmarker().getBookmarks());
FileListSorter sorter = new FileListSorter(caller);
Collections.sort(childFiles, sorter);
Log.v(TAG, "Will now interrupt thread waiting to show progress bar");
if(waitForASec.isAlive())
{
try
{
waitForASec.interrupt();
}
catch (Exception e) {
Log.e(TAG, "Error while interrupting thread",e);
}
}
return childFiles;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/BookmarkLoader.java
|
Java
|
gpl3
| 2,891
|
package net.appositedesigns.fileexplorer.workers;
import java.io.File;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.callbacks.OperationCallback;
import net.appositedesigns.fileexplorer.util.Util;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class Trasher extends AsyncTask<File, Integer, Boolean>
{
private static final String TAG = Trasher.class.getName();
private File fileToBeDeleted;
private FileListActivity caller;
private ProgressDialog waitDialog;
private OperationCallback<Void> callback;
public Trasher(FileListActivity caller, OperationCallback<Void> callback) {
this.caller = caller;
if(callback!=null)
{
this.callback = callback;
}
else
{
this.callback = new OperationCallback<Void>() {
@Override
public Void onSuccess() {return null;}
@Override
public void onFailure(Throwable e) {Log.e(TAG, "Error occurred", e);}
};
}
}
@Override
protected void onPostExecute(Boolean result) {
Log.v(TAG, "In post execute. Result of deletion was - "+result);
if(result)
{
Log.i(TAG, fileToBeDeleted.getAbsolutePath()+" deleted successfully");
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
waitDialog.dismiss();
Toast.makeText(caller.getApplicationContext(), "Deleted", Toast.LENGTH_LONG);
if(callback!=null)
{
callback.onSuccess();
}
caller.refresh();
}
});
}
else
{
Util.setPasteSrcFile(fileToBeDeleted, Util.getPasteMode());
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
if(callback!=null)
{
callback.onFailure(new Exception());
}
waitDialog.dismiss();
new Builder(caller)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(caller.getString(R.string.error))
.setMessage(caller.getString(R.string.delete_failed, fileToBeDeleted.getName()))
.show();
}
});
}
}
@Override
protected Boolean doInBackground(File... params) {
fileToBeDeleted = params[0];
caller.runOnUiThread(new Runnable() {
@Override
public void run() {
waitDialog = new ProgressDialog(caller);
waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
waitDialog.setMessage(caller.getString(R.string.deleting_path,fileToBeDeleted.getName()));
waitDialog.setCancelable(false);
waitDialog.show();
}
});
try
{
Log.v(TAG, "Checking if file on clipboard is same as that being deleted");
if(Util.getFileToPaste() != null && Util.getFileToPaste().getCanonicalPath().equals(fileToBeDeleted.getCanonicalPath()))
{
Log.v(TAG, "File on clipboard is being deleted");
Util.setPasteSrcFile(null, Util.getPasteMode());
}
return Util.delete(fileToBeDeleted);
}
catch (Exception e) {
Log.e(TAG, "Error occured while deleting file "+fileToBeDeleted.getAbsolutePath(),e);
return false;
}
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/Trasher.java
|
Java
|
gpl3
| 3,281
|
package net.appositedesigns.fileexplorer.workers;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import net.appositedesigns.fileexplorer.R;
import net.appositedesigns.fileexplorer.activity.FileListActivity;
import net.appositedesigns.fileexplorer.util.AbortionFlag;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.util.Log;
public class Unzipper extends AsyncTask<File, String, List<String>> {
private static final String TAG = Unzipper.class.getName();
private FileListActivity mContext;
private AbortionFlag flag;
private ProgressDialog zipProgress;
private File destination;
private int unzippedCount;
public Unzipper(FileListActivity context, File destination) {
mContext = context;
unzippedCount = 0;
this.flag = new AbortionFlag();
this.destination = destination;
}
@Override
protected void onPostExecute(final List<String> result)
{
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
boolean unzippedAtleastOne = (result!=null) && (result.size()>0);
if (zipProgress != null && zipProgress.isShowing()) {
zipProgress.dismiss();
}
if(flag.isAborted())
{
mContext.refresh();
String message = unzippedAtleastOne?mContext.getString(R.string.unzip_abort_partial, destination.getAbsolutePath()):mContext.getString(R.string.unzip_aborted);
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(mContext.getString(R.string.abort))
.setMessage(message)
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
else if(unzippedAtleastOne)
{
mContext.refresh();
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(mContext.getString(R.string.success))
.setMessage(mContext.getString(R.string.unzip_success, result.size()))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
}
});
}
@Override
protected void onPreExecute() {
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
zipProgress = new ProgressDialog(mContext);
zipProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
zipProgress.setMessage(mContext.getString(R.string.unzip_progress));
zipProgress.setButton(mContext.getString(R.string.run_in_background), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
zipProgress.setButton2(mContext.getString(R.string.cancel), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
zipProgress.getButton(which).setText(R.string.cancelling);
Unzipper.this.flag.abort();
}
});
zipProgress.show();
}
});
}
@Override
protected List<String> doInBackground(File... files) {
List<String> extracted = new ArrayList<String>();
if(files!=null && files.length >= 1)
{
Log.i(TAG, "Zip files: "+files);
for(File zipFile : files)
{
try {
extractFolder(zipFile, extracted);
extracted.add(zipFile.getAbsolutePath());
} catch (Exception e) {
Log.e(TAG, "Failed to unzip "+zipFile.getAbsolutePath()+". File exists - "+zipFile.exists(), e);
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(mContext.getString(R.string.zip))
.setMessage(mContext.getString(R.string.unzip_failed_generic))
.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
}
}
else
{
return null;
}
return extracted;
}
@Override
protected void onProgressUpdate(String... values) {
if(values!=null && values.length > 0)
{
unzippedCount +=values.length;
final String curr = values[0];
mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
if(zipProgress!=null && zipProgress.isShowing())
{
zipProgress.setMessage(mContext.getString(R.string.unzip_progress, curr));
}
}
});
}
}
private void extractFolder(File zipFile, List<String> extracted) throws ZipException, IOException
{
Log.i(TAG,zipFile.getAbsolutePath());
int BUFFER = 2048;
File file = zipFile;
ZipFile zip = new ZipFile(file);
String newPath = destination.getAbsolutePath()+"/"+zipFile.getName().substring(0, zipFile.getName().length() - 4);
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements() && !flag.isAborted())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
//destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();
publishProgress(destinationParent.getName());
// create the parent directory structure if needed
destinationParent.mkdirs();
extracted.add(destinationParent.getAbsolutePath());
if (!entry.isDirectory())
{
publishProgress(entry.getName());
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
extracted.add(destFile.getAbsolutePath());
}
// if (currentEntry.endsWith(".zip"))
// {
// // found a zip file, try to open
// extractFolder(destFile.getAbsolutePath());
// }
}
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/workers/Unzipper.java
|
Java
|
gpl3
| 7,521
|
package net.appositedesigns.fileexplorer.exception;
public class LocationInvalidException extends Exception {
private static final long serialVersionUID = -4046926680600982016L;
private String location;
public LocationInvalidException(String location) {
super();
this.location = location;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/exception/LocationInvalidException.java
|
Java
|
gpl3
| 462
|
package net.appositedesigns.fileexplorer;
import android.app.Application;
import android.content.Intent;
public class FileExplorerApp extends Application {
public static final int THEME_BLACK = R.style.Theme_FileExplorer;
public static final int THEME_WHITE = R.style.Theme_FileExplorer_Light;
public static final int THEME_WHITE_BLACK = android.R.style.Theme_Holo_Light_DarkActionBar;
public static final String ACTION_OPEN_BOOKMARK = "net.appositedesigns.fileexplorer.action.OPEN_BOOKMARKS";
public static final String ACTION_OPEN_FOLDER = "net.appositedesigns.fileexplorer.action.OPEN_FOLDER";
public static final String EXTRA_IS_PICKER = "net.appositedesigns.fileexplorer.extra.IS_PICKER";
public static final int REQ_PICK_FILE = 10;
public static final int REQ_PICK_BOOKMARK = 11;
public static final String EXTRA_SELECTED_BOOKMARK = "net.appositedesigns.fileexplorer.extra.SELECTED_BOOKMARK";
public static final String EXTRA_FOLDER = "net.appositedesigns.fileexplorer.extra.FOLDER";
private Intent fileAttachIntent;
public Intent getFileAttachIntent() {
return fileAttachIntent;
}
public void setFileAttachIntent(Intent fileAttachIntent) {
this.fileAttachIntent = fileAttachIntent;
}
}
|
zzkkugou-android-file-explorer
|
src/net/appositedesigns/fileexplorer/FileExplorerApp.java
|
Java
|
gpl3
| 1,261
|
/**
* New node file
*/
|
zzz-tce
|
index.js
|
JavaScript
|
oos
| 25
|
body
padding: 50px
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
a
color: #00B7FF
|
zzz-tce
|
public/stylesheets/style.styl
|
Stylus
|
oos
| 102
|
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00b7ff;
}
|
zzz-tce
|
public/stylesheets/style.css
|
CSS
|
oos
| 110
|
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
|
zzz-tce
|
views/index.ejs
|
EJS
|
oos
| 231
|
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
zzz-tce
|
app.js
|
JavaScript
|
oos
| 1,027
|
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
|
zzz-tce
|
routes/index.js
|
JavaScript
|
oos
| 117
|
/*
* GET users listing.
*/
exports.list = function(req, res){
res.send("respond with a resource");
};
|
zzz-tce
|
routes/user.js
|
JavaScript
|
oos
| 114
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.prefs;
import group.pals.android.lib.ui.lockpattern.R;
import android.content.Context;
/**
* Display Preferences.
*
* @author Hai Bison
*/
public class DisplayPrefs extends Prefs {
/**
* Checks if the library is using stealth mode or not.
*
* @param context
* the context.
* @return {@code true} or {@code false}. Default is {@code false}.
*/
public static boolean isStealthMode(Context context) {
return p(context).getBoolean(
context.getString(R.string.alp_pkey_display_stealth_mode),
context.getResources().getBoolean(
R.bool.alp_pkey_display_stealth_mode_default));
}// isStealthMode()
/**
* Sets stealth mode.
*
* @param context
* the context.
* @param v
* the value.
*/
public static void setStealthMode(Context context, boolean v) {
p(context)
.edit()
.putBoolean(
context.getString(R.string.alp_pkey_display_stealth_mode),
v).commit();
}// setStealthMode()
/**
* Gets minimum wired dots allowed for a pattern.
*
* @param context
* the context.
* @return the minimum wired dots allowed for a pattern. Default is
* {@code 4}.
*/
public static int getMinWiredDots(Context context) {
return p(context).getInt(
context.getString(R.string.alp_pkey_display_min_wired_dots),
context.getResources().getInteger(
R.integer.alp_pkey_display_min_wired_dots_default));
}// getMinWiredDots()
/**
* Sets minimum wired dots allowed for a pattern.
*
* @param context
* the context.
* @param v
* the minimum wired dots allowed for a pattern.
*/
public static void setMinWiredDots(Context context, int v) {
if (v <= 0 || v > 9)
v = context.getResources().getInteger(
R.integer.alp_pkey_display_min_wired_dots_default);
p(context)
.edit()
.putInt(context
.getString(R.string.alp_pkey_display_min_wired_dots),
v).commit();
}// setMinWiredDots()
/**
* Gets max retry allowed in mode comparing pattern.
*
* @param context
* the context.
* @return the max retry allowed in mode comparing pattern. Default is
* {@code 5}.
*/
public static int getMaxRetry(Context context) {
return p(context).getInt(
context.getString(R.string.alp_pkey_display_max_retry),
context.getResources().getInteger(
R.integer.alp_pkey_display_max_retry_default));
}// getMaxRetry()
/**
* Sets max retry allowed in mode comparing pattern.
*
* @param context
* the context.
* @param v
* the max retry allowed in mode comparing pattern.
*/
public static void setMaxRetry(Context context, int v) {
if (v <= 0)
v = context.getResources().getInteger(
R.integer.alp_pkey_display_max_retry_default);
p(context)
.edit()
.putInt(context.getString(R.string.alp_pkey_display_max_retry),
v).commit();
}// setMaxRetry()
/**
* Gets wired dots for a "CAPTCHA" pattern.
*
* @param context
* the context.
* @return the wired dots for a "CAPTCHA" pattern. Default is {@code 4}.
*/
public static int getCaptchaWiredDots(Context context) {
return p(context)
.getInt(context
.getString(R.string.alp_pkey_display_captcha_wired_dots),
context.getResources()
.getInteger(
R.integer.alp_pkey_display_captcha_wired_dots_default));
}// getCaptchaWiredDots()
/**
* Sets wired dots for a "CAPTCHA" pattern.
*
* @param context
* the context.
* @param v
* the wired dots for a "CAPTCHA" pattern.
*/
public static void setCaptchaWiredDots(Context context, int v) {
if (v <= 0 || v > 9)
v = context.getResources().getInteger(
R.integer.alp_pkey_display_captcha_wired_dots_default);
p(context)
.edit()
.putInt(context
.getString(R.string.alp_pkey_display_captcha_wired_dots),
v).commit();
}// setCaptchaWiredDots()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/prefs/DisplayPrefs.java
|
Java
|
asf20
| 5,421
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.prefs;
import group.pals.android.lib.ui.lockpattern.util.Sys;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class Prefs {
/**
* This unique ID is used for storing preferences.
*
* @since v2.6 beta
*/
public static final String UID = "a6eedbe5-1cf9-4684-8134-ad4ec9f6a131";
/**
* Generates global preference filename of this library.
*
* @return the global preference filename.
*/
public static final String genPreferenceFilename() {
return String.format("%s_%s", Sys.LIB_NAME, UID);
}
/**
* Generates global database filename. the database filename.
*
* @return the global database filename.
*/
public static final String genDatabaseFilename(String name) {
return String.format("%s_%s_%s", Sys.LIB_NAME, UID, name);
}
/**
* Gets new {@link SharedPreferences}
*
* @param context
* the context.
* @return {@link SharedPreferences}
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static SharedPreferences p(Context context) {
// always use application context
return context.getApplicationContext().getSharedPreferences(
genPreferenceFilename(), Context.MODE_MULTI_PROCESS);
}
/**
* Setup {@code pm} to use global unique filename and global access mode.
* You must use this method if you let the user change preferences via UI
* (such as {@link PreferenceActivity}, {@link PreferenceFragment}...).
*
* @param context
* the context.
* @param pm
* {@link PreferenceManager}.
* @since v2.6 beta
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void setupPreferenceManager(Context context,
PreferenceManager pm) {
pm.setSharedPreferencesMode(Context.MODE_MULTI_PROCESS);
pm.setSharedPreferencesName(genPreferenceFilename());
}// setupPreferenceManager()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/prefs/Prefs.java
|
Java
|
asf20
| 2,882
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.prefs;
import group.pals.android.lib.ui.lockpattern.R;
import android.content.Context;
/**
* Security preferences.
*
* @author Hai Bison
*/
public class SecurityPrefs extends Prefs {
/**
* Checks if the library is using auto-save pattern mode.
*
* @param context
* the context.
* @return {@code true} or {@code false}. Default is {@code false}.
*/
public static boolean isAutoSavePattern(Context context) {
return p(context).getBoolean(
context.getString(R.string.alp_pkey_sys_auto_save_pattern),
context.getResources().getBoolean(
R.bool.alp_pkey_sys_auto_save_pattern_default));
}// isAutoSavePattern()
/**
* Sets auto-save pattern mode.
*
* @param context
* the context.
* @param v
* the auto-save mode.
*/
public static void setAutoSavePattern(Context context, boolean v) {
p(context)
.edit()
.putBoolean(
context.getString(R.string.alp_pkey_sys_auto_save_pattern),
v).commit();
if (!v)
setPattern(context, null);
}// setAutoSavePattern()
/**
* Gets the pattern.
*
* @param context
* the context.
* @return the pattern. Default is {@code null}.
*/
public static char[] getPattern(Context context) {
String pattern = p(context).getString(
context.getString(R.string.alp_pkey_sys_pattern), null);
return pattern == null ? null : pattern.toCharArray();
}// getPattern()
/**
* Sets the pattern.
*
* @param context
* the context.
* @param pattern
* the pattern, can be {@code null} to reset it.
*/
public static void setPattern(Context context, char[] pattern) {
p(context)
.edit()
.putString(context.getString(R.string.alp_pkey_sys_pattern),
pattern != null ? new String(pattern) : null).commit();
}// setPattern()
/**
* Gets encrypter class.
*
* @param context
* the context.
* @return the full name of encrypter class. Default is {@code null}.
*/
public static char[] getEncrypterClass(Context context) {
String clazz = p(context).getString(
context.getString(R.string.alp_pkey_sys_encrypter_class), null);
return clazz == null ? null : clazz.toCharArray();
}// getEncrypterClass()
/**
* Sets encrypter class.
*
* @param context
* the context.
* @param clazz
* the encrypter class, can be {@code null} if you don't want to
* use it.
*/
public static void setEncrypterClass(Context context, Class<?> clazz) {
setEncrypterClass(context, clazz != null ? clazz.getName()
.toCharArray() : null);
}// setEncrypterClass()
/**
* Sets encrypter class.
*
* @param context
* the context.
* @param clazz
* the full name of encrypter class, can be {@code null} if you
* don't want to use it.
*/
public static void setEncrypterClass(Context context, char[] clazz) {
p(context)
.edit()
.putString(
context.getString(R.string.alp_pkey_sys_encrypter_class),
clazz != null ? new String(clazz) : null).commit();
}// setEncrypterClass()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/prefs/SecurityPrefs.java
|
Java
|
asf20
| 4,281
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.util;
import group.pals.android.lib.ui.lockpattern.widget.LockPatternView.Cell;
import java.util.List;
import android.content.Context;
/**
* Interface for encrypter.
*
* @author Hai Bison
* @since v2 beta
*/
public interface IEncrypter {
/**
* Encrypts {@code pattern}.
*
* @param context
* the context.
* @param pattern
* the pattern in the form of a list of {@link Cell}.
* @return the encrypted char array of the pattern.
* @since v2.1 beta
*/
char[] encrypt(Context context, List<Cell> pattern);
/**
* Decrypts an encrypted pattern.
*
* @param context
* the context.
* @param encryptedPattern
* the encrypted pattern.
* @return the original pattern.
*/
List<Cell> decrypt(Context context, char[] encryptedPattern);
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/util/IEncrypter.java
|
Java
|
asf20
| 1,541
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.util;
import group.pals.android.lib.ui.lockpattern.BuildConfig;
import group.pals.android.lib.ui.lockpattern.R;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Window;
/**
* UI utilities.
*
* @author Hai Bison
*/
public class UI {
private static final String CLASSNAME = UI.class.getName();
/**
* Uses a fixed size for {@code dialog} in large screens.
*
* @param dialog
* the dialog.
*/
public static void adjustDialogSizeForLargeScreen(Dialog dialog) {
adjustDialogSizeForLargeScreen(dialog.getWindow());
}// adjustDialogSizeForLargeScreen()
/**
* Uses a fixed size for {@code dialogWindow} in large screens.
*
* @param dialogWindow
* the window <i>of the dialog</i>.
*/
public static void adjustDialogSizeForLargeScreen(final Window dialogWindow) {
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "adjustDialogSizeForLargeScreen()");
if (dialogWindow.isFloating()
&& dialogWindow.getContext().getResources()
.getBoolean(R.bool.alp_is_large_screen)) {
final DisplayMetrics metrics = dialogWindow.getContext()
.getResources().getDisplayMetrics();
final boolean isPortrait = metrics.widthPixels < metrics.heightPixels;
int width = metrics.widthPixels;// dialogWindow.getDecorView().getWidth();
int height = metrics.heightPixels;// dialogWindow.getDecorView().getHeight();
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, String.format("width = %,d | height = %,d",
width, height));
width = (int) dialogWindow
.getContext()
.getResources()
.getFraction(
isPortrait ? R.dimen.aosp_dialog_fixed_width_minor
: R.dimen.aosp_dialog_fixed_width_major,
width, width);
height = (int) dialogWindow
.getContext()
.getResources()
.getFraction(
isPortrait ? R.dimen.aosp_dialog_fixed_height_major
: R.dimen.aosp_dialog_fixed_height_minor,
height, height);
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, String.format(
"NEW >>> width = %,d | height = %,d", width, height));
dialogWindow.setLayout(width, height);
}
}// adjustDialogSizeForLargeScreen()
/**
* Convenient method for {@link Context#getTheme()} and
* {@link Resources.Theme#resolveAttribute(int, TypedValue, boolean)}.
*
* @param context
* the context.
* @param resId
* The resource identifier of the desired theme attribute.
* @return the resource ID that {@link TypedValue#resourceId} points to, or
* {@code 0} if not found.
*/
public static int resolveAttribute(Context context, int resId) {
TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(resId, typedValue, true))
return typedValue.resourceId;
return 0;
}// resolveAttribute()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/util/UI.java
|
Java
|
asf20
| 4,152
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.util;
import group.pals.android.lib.ui.lockpattern.collect.Lists;
import java.util.List;
import java.util.Random;
/**
* Random utilities.
*
* @author Hai Bison
*
*/
public class Randoms {
private static final Random RANDOM = new Random();
/**
* Generates a random integer.
*
* @return the random integer.
*/
public static int randInt() {
return RANDOM.nextInt((int) (System.nanoTime() % Integer.MAX_VALUE));
}// randInt()
/**
* Generates a random integer within {@code [0, n)}.
*
* @param n
* an arbitrary value.
* @return the random integer.
*/
public static int randInt(int n) {
return n > 0 ? randInt() % n : 0;
}// randInt()
/**
* Generates a random integer array which has length of {@code end - start},
* and is filled by all values from {@code start} to {@code end - 1} in
* randomized orders.
*
* @param start
* the starting value.
* @param end
* the ending value.
* @return the random integer array. If {@code end <= start}, an empty array
* returns.
*/
public static int[] randIntArray(int start, int end) {
if (end <= start)
return new int[0];
final List<Integer> values = Lists.newArrayList();
for (int i = start; i < end; i++)
values.add(i);
final int[] result = new int[values.size()];
for (int i = 0; i < result.length; i++) {
int k = randInt(values.size());
result[i] = values.get(k);
values.remove(k);
}// for
return result;
}// randIntArray()
/**
* Generates a random integer array which has length of {@code end}, and is
* filled by all values from {@code 0} to {@code end - 1} in randomized
* orders.
*
* @param end
* the ending value.
* @return the random integer array. If {@code end <= start}, an empty array
* returns.
*/
public static int[] randIntArray(int end) {
return randIntArray(0, end);
}// randIntArray()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/util/Randoms.java
|
Java
|
asf20
| 2,824
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.util;
/**
* Used to throw exception if given class is not implemented from
* {@link IEncrypter}.
*
* @author Hai Bison
* @since v2 beta
*/
public class InvalidEncrypterException extends RuntimeException {
/**
* Auto-generated by Eclipse.
*/
private static final long serialVersionUID = -1709666714042537187L;
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/util/InvalidEncrypterException.java
|
Java
|
asf20
| 998
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.util;
/**
* System utilities.
*
* @author Hai Bison
*
*/
public class Sys {
/**
* The library name.
*/
public static final String LIB_NAME = "android-lockpattern";
/**
* The library version code.
*/
public static final int LIB_VERSION_CODE = 32;
/**
* The library version name.
*/
public static final String LIB_VERSION_NAME = "3.0.1";
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/util/Sys.java
|
Java
|
asf20
| 1,064
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.widget;
import android.view.View;
/**
* Helper class for {@link View} in API 16+.
*
* @author Hai Bison
* @since v2.4 beta
*/
public class ViewCompat_v16 {
/**
* Wrapper for {@link View#announceForAccessibility(CharSequence)}.
*
* @param view
* a view.
* @param text
* The announcement text.
* @see View#announceForAccessibility(CharSequence)
*/
public static void announceForAccessibility(View view, CharSequence text) {
view.announceForAccessibility(text);
}// announceForAccessibility()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/widget/ViewCompat_v16.java
|
Java
|
asf20
| 1,245
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.widget;
import group.pals.android.lib.ui.lockpattern.R;
import group.pals.android.lib.ui.lockpattern.util.UI;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Debug;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
/**
* Displays and detects the user's unlock attempt, which is a drag of a finger
* across 9 regions of the screen.
* <p/>
* Is also capable of displaying a static pattern in "in progress", "wrong" or
* "correct" states.
*/
public class LockPatternView extends View {
// Aspect to use when rendering this view
private static final int ASPECT_SQUARE = 0; // View will be the minimum of
// width/height
private static final int ASPECT_LOCK_WIDTH = 1; // Fixed width; height will
// be minimum of (w,h)
private static final int ASPECT_LOCK_HEIGHT = 2; // Fixed height; width will
// be minimum of (w,h)
/**
* This is the width of the matrix (the number of dots per row and column).
* Change this value to change the dimension of the pattern's matrix.
*
* @since v2.7 beta
* @author Thomas Breitbach
*/
public static final int MATRIX_WIDTH = 3;
/**
* The size of the pattern's matrix.
*/
public static final int MATRIX_SIZE = MATRIX_WIDTH * MATRIX_WIDTH;
private static final boolean PROFILE_DRAWING = false;
private boolean mDrawingProfilingStarted = false;
private Paint mPaint = new Paint();
private Paint mPathPaint = new Paint();
// TODO: make this common with PhoneWindow
static final int STATUS_BAR_HEIGHT = 25;
/**
* How many milliseconds we spend animating each circle of a lock pattern if
* the animating mode is set. The entire animation should take this constant
* * the length of the pattern to complete.
*/
private static final int MILLIS_PER_CIRCLE_ANIMATING = 700;
private OnPatternListener mOnPatternListener;
private ArrayList<Cell> mPattern = new ArrayList<Cell>(MATRIX_SIZE);
/**
* Lookup table for the circles of the pattern we are currently drawing.
* This will be the cells of the complete pattern unless we are animating,
* in which case we use this to hold the cells we are drawing for the in
* progress animation.
*/
private boolean[][] mPatternDrawLookup = new boolean[MATRIX_WIDTH][MATRIX_WIDTH];
/**
* the in progress point: - during interaction: where the user's finger is -
* during animation: the current tip of the animating line
*/
private float mInProgressX = -1;
private float mInProgressY = -1;
private long mAnimatingPeriodStart;
private DisplayMode mPatternDisplayMode = DisplayMode.Correct;
private boolean mInputEnabled = true;
private boolean mInStealthMode = false;
private boolean mEnableHapticFeedback = true;
private boolean mPatternInProgress = false;
private float mDiameterFactor = 0.10f; // TODO: move to attrs
private final int mStrokeAlpha = 128;
private float mHitFactor = 0.6f;
private float mSquareWidth;
private float mSquareHeight;
private Bitmap mBitmapBtnDefault;
private Bitmap mBitmapBtnTouched;
private Bitmap mBitmapCircleDefault;
private Bitmap mBitmapCircleGreen;
private Bitmap mBitmapCircleRed;
private Bitmap mBitmapArrowGreenUp;
private Bitmap mBitmapArrowRedUp;
private final Path mCurrentPath = new Path();
private final Rect mInvalidate = new Rect();
private int mBitmapWidth;
private int mBitmapHeight;
private int mAspect;
private final Matrix mArrowMatrix = new Matrix();
private final Matrix mCircleMatrix = new Matrix();
private final int mPadding = 0;
private final int mPaddingLeft = mPadding;
private final int mPaddingRight = mPadding;
private final int mPaddingTop = mPadding;
private final int mPaddingBottom = mPadding;
/**
* Represents a cell in the MATRIX_WIDTH x MATRIX_WIDTH matrix of the unlock
* pattern view.
*/
public static class Cell implements Parcelable {
int mRow;
int mColumn;
// keep # objects limited to MATRIX_SIZE
static Cell[][] sCells = new Cell[MATRIX_WIDTH][MATRIX_WIDTH];
static {
for (int i = 0; i < MATRIX_WIDTH; i++) {
for (int j = 0; j < MATRIX_WIDTH; j++) {
sCells[i][j] = new Cell(i, j);
}
}
}
/**
* @param row
* The row of the cell.
* @param column
* The column of the cell.
*/
private Cell(int row, int column) {
checkRange(row, column);
this.mRow = row;
this.mColumn = column;
}
/**
* Gets the row index.
*
* @return the row index.
*/
public int getRow() {
return mRow;
}// getRow()
/**
* Gets the column index.
*
* @return the column index.
*/
public int getColumn() {
return mColumn;
}// getColumn()
/**
* Gets the ID.It is counted from left to right, top to bottom of the
* matrix, starting by zero.
*
* @return the ID.
*/
public int getId() {
return mRow * MATRIX_WIDTH + mColumn;
}// getId()
/**
* @param row
* The row of the cell.
* @param column
* The column of the cell.
*/
public static synchronized Cell of(int row, int column) {
checkRange(row, column);
return sCells[row][column];
}
/**
* Gets a cell from its ID.
*
* @param id
* the cell ID.
* @return the cell.
* @since v2.7 beta
* @author Hai Bison
*/
public static synchronized Cell of(int id) {
return of(id / MATRIX_WIDTH, id % MATRIX_WIDTH);
}// of()
private static void checkRange(int row, int column) {
if (row < 0 || row > MATRIX_WIDTH - 1) {
throw new IllegalArgumentException("row must be in range 0-"
+ (MATRIX_WIDTH - 1));
}
if (column < 0 || column > MATRIX_WIDTH - 1) {
throw new IllegalArgumentException("column must be in range 0-"
+ (MATRIX_WIDTH - 1));
}
}
@Override
public String toString() {
return "(ROW=" + getRow() + ",COL=" + getColumn() + ")";
}// toString()
@Override
public boolean equals(Object object) {
if (object instanceof Cell)
return getColumn() == ((Cell) object).getColumn()
&& getRow() == ((Cell) object).getRow();
return super.equals(object);
}// equals()
/*
* PARCELABLE
*/
@Override
public int describeContents() {
return 0;
}// describeContents()
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(getColumn());
dest.writeInt(getRow());
}// writeToParcel()
/**
* Reads data from parcel.
*
* @param in
* the parcel.
*/
public void readFromParcel(Parcel in) {
mColumn = in.readInt();
mRow = in.readInt();
}// readFromParcel()
public static final Parcelable.Creator<Cell> CREATOR = new Parcelable.Creator<Cell>() {
public Cell createFromParcel(Parcel in) {
return new Cell(in);
}// createFromParcel()
public Cell[] newArray(int size) {
return new Cell[size];
}// newArray()
};// CREATOR
private Cell(Parcel in) {
readFromParcel(in);
}// Cell()
}// Cell
/**
* How to display the current pattern.
*/
public enum DisplayMode {
/**
* The pattern drawn is correct (i.e draw it in a friendly color)
*/
Correct,
/**
* Animate the pattern (for demo, and help).
*/
Animate,
/**
* The pattern is wrong (i.e draw a foreboding color)
*/
Wrong
}
/**
* The call back interface for detecting patterns entered by the user.
*/
public static interface OnPatternListener {
/**
* A new pattern has begun.
*/
void onPatternStart();
/**
* The pattern was cleared.
*/
void onPatternCleared();
/**
* The user extended the pattern currently being drawn by one cell.
*
* @param pattern
* The pattern with newly added cell.
*/
void onPatternCellAdded(List<Cell> pattern);
/**
* A pattern was detected from the user.
*
* @param pattern
* The pattern.
*/
void onPatternDetected(List<Cell> pattern);
}
private final Context mContext;
public LockPatternView(Context context) {
this(context, null);
}
public LockPatternView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
// TypedArray a = context.obtainStyledAttributes(attrs,
// R.styleable.LockPatternView);
final String aspect = "";// a.getString(R.styleable.LockPatternView_aspect);
if ("square".equals(aspect)) {
mAspect = ASPECT_SQUARE;
} else if ("lock_width".equals(aspect)) {
mAspect = ASPECT_LOCK_WIDTH;
} else if ("lock_height".equals(aspect)) {
mAspect = ASPECT_LOCK_HEIGHT;
} else {
mAspect = ASPECT_SQUARE;
}
setClickable(true);
mPathPaint.setAntiAlias(true);
mPathPaint.setDither(true);
mPathPaint.setColor(getContext().getResources()
.getColor(
UI.resolveAttribute(getContext(),
R.attr.alp_color_pattern_path)));
mPathPaint.setAlpha(mStrokeAlpha);
mPathPaint.setStyle(Paint.Style.STROKE);
mPathPaint.setStrokeJoin(Paint.Join.ROUND);
mPathPaint.setStrokeCap(Paint.Cap.ROUND);
// lot's of bitmaps!
mBitmapBtnDefault = getBitmapFor(UI.resolveAttribute(getContext(),
R.attr.alp_drawable_btn_code_lock_default_holo));
mBitmapBtnTouched = getBitmapFor(UI.resolveAttribute(getContext(),
R.attr.alp_drawable_btn_code_lock_touched_holo));
mBitmapCircleDefault = getBitmapFor(UI
.resolveAttribute(
getContext(),
R.attr.alp_drawable_indicator_code_lock_point_area_default_holo));
mBitmapCircleGreen = getBitmapFor(UI.resolveAttribute(getContext(),
R.attr.aosp_drawable_indicator_code_lock_point_area_normal));
mBitmapCircleRed = getBitmapFor(R.drawable.aosp_indicator_code_lock_point_area_red_holo);
mBitmapArrowGreenUp = getBitmapFor(R.drawable.aosp_indicator_code_lock_drag_direction_green_up);
mBitmapArrowRedUp = getBitmapFor(R.drawable.aosp_indicator_code_lock_drag_direction_red_up);
// bitmaps have the size of the largest bitmap in this group
final Bitmap bitmaps[] = { mBitmapBtnDefault, mBitmapBtnTouched,
mBitmapCircleDefault, mBitmapCircleGreen, mBitmapCircleRed };
for (Bitmap bitmap : bitmaps) {
mBitmapWidth = Math.max(mBitmapWidth, bitmap.getWidth());
mBitmapHeight = Math.max(mBitmapHeight, bitmap.getHeight());
}
}// LockPatternView()
private Bitmap getBitmapFor(int resId) {
return BitmapFactory.decodeResource(getContext().getResources(), resId);
}
/**
* @return Whether the view is in stealth mode.
*/
public boolean isInStealthMode() {
return mInStealthMode;
}
/**
* @return Whether the view has tactile feedback enabled.
*/
public boolean isTactileFeedbackEnabled() {
return mEnableHapticFeedback;
}
/**
* Set whether the view is in stealth mode. If true, there will be no
* visible feedback as the user enters the pattern.
*
* @param inStealthMode
* Whether in stealth mode.
*/
public void setInStealthMode(boolean inStealthMode) {
mInStealthMode = inStealthMode;
}
/**
* Set whether the view will use tactile feedback. If true, there will be
* tactile feedback as the user enters the pattern.
*
* @param tactileFeedbackEnabled
* Whether tactile feedback is enabled
*/
public void setTactileFeedbackEnabled(boolean tactileFeedbackEnabled) {
mEnableHapticFeedback = tactileFeedbackEnabled;
}
/**
* Set the call back for pattern detection.
*
* @param onPatternListener
* The call back.
*/
public void setOnPatternListener(OnPatternListener onPatternListener) {
mOnPatternListener = onPatternListener;
}
/**
* Set the pattern explicitely (rather than waiting for the user to input a
* pattern).
*
* @param displayMode
* How to display the pattern.
* @param pattern
* The pattern.
*/
public void setPattern(DisplayMode displayMode, List<Cell> pattern) {
mPattern.clear();
mPattern.addAll(pattern);
clearPatternDrawLookup();
for (Cell cell : pattern) {
mPatternDrawLookup[cell.getRow()][cell.getColumn()] = true;
}
setDisplayMode(displayMode);
}
/**
* Set the display mode of the current pattern. This can be useful, for
* instance, after detecting a pattern to tell this view whether change the
* in progress result to correct or wrong.
*
* @param displayMode
* The display mode.
*/
public void setDisplayMode(DisplayMode displayMode) {
mPatternDisplayMode = displayMode;
if (displayMode == DisplayMode.Animate) {
if (mPattern.size() == 0) {
throw new IllegalStateException(
"you must have a pattern to "
+ "animate if you want to set the display mode to animate");
}
mAnimatingPeriodStart = SystemClock.elapsedRealtime();
final Cell first = mPattern.get(0);
mInProgressX = getCenterXForColumn(first.getColumn());
mInProgressY = getCenterYForRow(first.getRow());
clearPatternDrawLookup();
}
invalidate();
}
/**
* Retrieves last display mode. This method is useful in case of storing
* states and restoring them after screen orientation changed.
*
* @return {@link DisplayMode}
* @since v1.5.3 beta
*/
public DisplayMode getDisplayMode() {
return mPatternDisplayMode;
}
/**
* Retrieves current displaying pattern. This method is useful in case of
* storing states and restoring them after screen orientation changed.
*
* @return current displaying pattern. <b>Note:</b> This is an independent
* list with the view's pattern itself.
* @since v1.5.3 beta
*/
@SuppressWarnings("unchecked")
public List<Cell> getPattern() {
return (List<Cell>) mPattern.clone();
}
private void notifyCellAdded() {
sendAccessEvent(R.string.alp_lockscreen_access_pattern_cell_added);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternCellAdded(mPattern);
}
}
private void notifyPatternStarted() {
sendAccessEvent(R.string.alp_lockscreen_access_pattern_start);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternStart();
}
}
private void notifyPatternDetected() {
sendAccessEvent(R.string.alp_lockscreen_access_pattern_detected);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternDetected(mPattern);
}
}
private void notifyPatternCleared() {
sendAccessEvent(R.string.alp_lockscreen_access_pattern_cleared);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternCleared();
}
}
/**
* Clear the pattern.
*/
public void clearPattern() {
resetPattern();
}
/**
* Reset all pattern state.
*/
private void resetPattern() {
mPattern.clear();
clearPatternDrawLookup();
mPatternDisplayMode = DisplayMode.Correct;
invalidate();
}
/**
* Clear the pattern lookup table.
*/
private void clearPatternDrawLookup() {
for (int i = 0; i < MATRIX_WIDTH; i++) {
for (int j = 0; j < MATRIX_WIDTH; j++) {
mPatternDrawLookup[i][j] = false;
}
}
}
/**
* Disable input (for instance when displaying a message that will timeout
* so user doesn't get view into messy state).
*/
public void disableInput() {
mInputEnabled = false;
}
/**
* Enable input.
*/
public void enableInput() {
mInputEnabled = true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
final int width = w - mPaddingLeft - mPaddingRight;
mSquareWidth = width / (float) MATRIX_WIDTH;
final int height = h - mPaddingTop - mPaddingBottom;
mSquareHeight = height / (float) MATRIX_WIDTH;
}
private int resolveMeasured(int measureSpec, int desired) {
int result = 0;
int specSize = MeasureSpec.getSize(measureSpec);
switch (MeasureSpec.getMode(measureSpec)) {
case MeasureSpec.UNSPECIFIED:
result = desired;
break;
case MeasureSpec.AT_MOST:
result = Math.max(specSize, desired);
break;
case MeasureSpec.EXACTLY:
default:
result = specSize;
}
return result;
}
@Override
protected int getSuggestedMinimumWidth() {
// View should be large enough to contain MATRIX_WIDTH side-by-side
// target
// bitmaps
return MATRIX_WIDTH * mBitmapWidth;
}
@Override
protected int getSuggestedMinimumHeight() {
// View should be large enough to contain MATRIX_WIDTH side-by-side
// target
// bitmaps
return MATRIX_WIDTH * mBitmapWidth;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int minimumWidth = getSuggestedMinimumWidth();
final int minimumHeight = getSuggestedMinimumHeight();
int viewWidth = resolveMeasured(widthMeasureSpec, minimumWidth);
int viewHeight = resolveMeasured(heightMeasureSpec, minimumHeight);
switch (mAspect) {
case ASPECT_SQUARE:
viewWidth = viewHeight = Math.min(viewWidth, viewHeight);
break;
case ASPECT_LOCK_WIDTH:
viewHeight = Math.min(viewWidth, viewHeight);
break;
case ASPECT_LOCK_HEIGHT:
viewWidth = Math.min(viewWidth, viewHeight);
break;
}
// Log.v(TAG, "LockPatternView dimensions: " + viewWidth + "x" +
// viewHeight);
setMeasuredDimension(viewWidth, viewHeight);
}
/**
* Determines whether the point x, y will add a new point to the current
* pattern (in addition to finding the cell, also makes heuristic choices
* such as filling in gaps based on current pattern).
*
* @param x
* The x coordinate.
* @param y
* The y coordinate.
*/
private Cell detectAndAddHit(float x, float y) {
final Cell cell = checkForNewHit(x, y);
if (cell != null) {
// check for gaps in existing pattern
Cell fillInGapCell = null;
final ArrayList<Cell> pattern = mPattern;
if (!pattern.isEmpty()) {
final Cell lastCell = pattern.get(pattern.size() - 1);
int dRow = cell.mRow - lastCell.mRow;
int dColumn = cell.mColumn - lastCell.mColumn;
int fillInRow = lastCell.mRow;
int fillInColumn = lastCell.mColumn;
if (Math.abs(dRow) == 2 && Math.abs(dColumn) != 1) {
fillInRow = lastCell.mRow + ((dRow > 0) ? 1 : -1);
}
if (Math.abs(dColumn) == 2 && Math.abs(dRow) != 1) {
fillInColumn = lastCell.mColumn + ((dColumn > 0) ? 1 : -1);
}
fillInGapCell = Cell.of(fillInRow, fillInColumn);
}
if (fillInGapCell != null
&& !mPatternDrawLookup[fillInGapCell.mRow][fillInGapCell.mColumn]) {
addCellToPattern(fillInGapCell);
}
addCellToPattern(cell);
if (mEnableHapticFeedback) {
performHapticFeedback(
HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING
| HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
return cell;
}
return null;
}
private void addCellToPattern(Cell newCell) {
mPatternDrawLookup[newCell.getRow()][newCell.getColumn()] = true;
mPattern.add(newCell);
notifyCellAdded();
}
// helper method to find which cell a point maps to
private Cell checkForNewHit(float x, float y) {
final int rowHit = getRowHit(y);
if (rowHit < 0) {
return null;
}
final int columnHit = getColumnHit(x);
if (columnHit < 0) {
return null;
}
if (mPatternDrawLookup[rowHit][columnHit]) {
return null;
}
return Cell.of(rowHit, columnHit);
}
/**
* Helper method to find the row that y falls into.
*
* @param y
* The y coordinate
* @return The row that y falls in, or -1 if it falls in no row.
*/
private int getRowHit(float y) {
final float squareHeight = mSquareHeight;
float hitSize = squareHeight * mHitFactor;
float offset = mPaddingTop + (squareHeight - hitSize) / 2f;
for (int i = 0; i < MATRIX_WIDTH; i++) {
final float hitTop = offset + squareHeight * i;
if (y >= hitTop && y <= hitTop + hitSize) {
return i;
}
}
return -1;
}
/**
* Helper method to find the column x fallis into.
*
* @param x
* The x coordinate.
* @return The column that x falls in, or -1 if it falls in no column.
*/
private int getColumnHit(float x) {
final float squareWidth = mSquareWidth;
float hitSize = squareWidth * mHitFactor;
float offset = mPaddingLeft + (squareWidth - hitSize) / 2f;
for (int i = 0; i < MATRIX_WIDTH; i++) {
final float hitLeft = offset + squareWidth * i;
if (x >= hitLeft && x <= hitLeft + hitSize) {
return i;
}
}
return -1;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mInputEnabled || !isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
handleActionDown(event);
return true;
case MotionEvent.ACTION_UP:
handleActionUp(event);
return true;
case MotionEvent.ACTION_MOVE:
handleActionMove(event);
return true;
case MotionEvent.ACTION_CANCEL:
/*
* Original source check for mPatternInProgress == true first before
* calling next three lines. But if we do that, there will be
* nothing happened when the user taps at empty area and releases
* the finger. We want the pattern to be reset and the message will
* be updated after the user did that.
*/
mPatternInProgress = false;
resetPattern();
notifyPatternCleared();
if (PROFILE_DRAWING) {
if (mDrawingProfilingStarted) {
Debug.stopMethodTracing();
mDrawingProfilingStarted = false;
}
}
return true;
}
return false;
}
private void handleActionMove(MotionEvent event) {
// Handle all recent motion events so we don't skip any cells even when
// the device
// is busy...
final int historySize = event.getHistorySize();
for (int i = 0; i < historySize + 1; i++) {
final float x = i < historySize ? event.getHistoricalX(i) : event
.getX();
final float y = i < historySize ? event.getHistoricalY(i) : event
.getY();
final int patternSizePreHitDetect = mPattern.size();
Cell hitCell = detectAndAddHit(x, y);
final int patternSize = mPattern.size();
if (hitCell != null && patternSize == 1) {
mPatternInProgress = true;
notifyPatternStarted();
}
// note current x and y for rubber banding of in progress patterns
final float dx = Math.abs(x - mInProgressX);
final float dy = Math.abs(y - mInProgressY);
if (dx + dy > mSquareWidth * 0.01f) {
float oldX = mInProgressX;
float oldY = mInProgressY;
mInProgressX = x;
mInProgressY = y;
if (mPatternInProgress && patternSize > 0) {
final ArrayList<Cell> pattern = mPattern;
final float radius = mSquareWidth * mDiameterFactor * 0.5f;
final Cell lastCell = pattern.get(patternSize - 1);
float startX = getCenterXForColumn(lastCell.mColumn);
float startY = getCenterYForRow(lastCell.mRow);
float left;
float top;
float right;
float bottom;
final Rect invalidateRect = mInvalidate;
if (startX < x) {
left = startX;
right = x;
} else {
left = x;
right = startX;
}
if (startY < y) {
top = startY;
bottom = y;
} else {
top = y;
bottom = startY;
}
// Invalidate between the pattern's last cell and the
// current location
invalidateRect.set((int) (left - radius),
(int) (top - radius), (int) (right + radius),
(int) (bottom + radius));
if (startX < oldX) {
left = startX;
right = oldX;
} else {
left = oldX;
right = startX;
}
if (startY < oldY) {
top = startY;
bottom = oldY;
} else {
top = oldY;
bottom = startY;
}
// Invalidate between the pattern's last cell and the
// previous location
invalidateRect.union((int) (left - radius),
(int) (top - radius), (int) (right + radius),
(int) (bottom + radius));
// Invalidate between the pattern's new cell and the
// pattern's previous cell
if (hitCell != null) {
startX = getCenterXForColumn(hitCell.mColumn);
startY = getCenterYForRow(hitCell.mRow);
if (patternSize >= 2) {
// (re-using hitcell for old cell)
hitCell = pattern.get(patternSize - 1
- (patternSize - patternSizePreHitDetect));
oldX = getCenterXForColumn(hitCell.mColumn);
oldY = getCenterYForRow(hitCell.mRow);
if (startX < oldX) {
left = startX;
right = oldX;
} else {
left = oldX;
right = startX;
}
if (startY < oldY) {
top = startY;
bottom = oldY;
} else {
top = oldY;
bottom = startY;
}
} else {
left = right = startX;
top = bottom = startY;
}
final float widthOffset = mSquareWidth / 2f;
final float heightOffset = mSquareHeight / 2f;
invalidateRect.set((int) (left - widthOffset),
(int) (top - heightOffset),
(int) (right + widthOffset),
(int) (bottom + heightOffset));
}
invalidate(invalidateRect);
} else {
invalidate();
}
}
}
}
private void sendAccessEvent(int resId) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
setContentDescription(mContext.getString(resId));
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
setContentDescription(null);
} else
ViewCompat_v16.announceForAccessibility(this,
mContext.getString(resId));
}
private void handleActionUp(MotionEvent event) {
// report pattern detected
if (!mPattern.isEmpty()) {
mPatternInProgress = false;
notifyPatternDetected();
invalidate();
}
if (PROFILE_DRAWING) {
if (mDrawingProfilingStarted) {
Debug.stopMethodTracing();
mDrawingProfilingStarted = false;
}
}
}
private void handleActionDown(MotionEvent event) {
resetPattern();
final float x = event.getX();
final float y = event.getY();
final Cell hitCell = detectAndAddHit(x, y);
if (hitCell != null) {
mPatternInProgress = true;
mPatternDisplayMode = DisplayMode.Correct;
notifyPatternStarted();
} else {
/*
* Original source check for mPatternInProgress == true first before
* calling this block. But if we do that, there will be nothing
* happened when the user taps at empty area and releases the
* finger. We want the pattern to be reset and the message will be
* updated after the user did that.
*/
mPatternInProgress = false;
notifyPatternCleared();
}
if (hitCell != null) {
final float startX = getCenterXForColumn(hitCell.mColumn);
final float startY = getCenterYForRow(hitCell.mRow);
final float widthOffset = mSquareWidth / 2f;
final float heightOffset = mSquareHeight / 2f;
invalidate((int) (startX - widthOffset),
(int) (startY - heightOffset),
(int) (startX + widthOffset), (int) (startY + heightOffset));
}
mInProgressX = x;
mInProgressY = y;
if (PROFILE_DRAWING) {
if (!mDrawingProfilingStarted) {
Debug.startMethodTracing("LockPatternDrawing");
mDrawingProfilingStarted = true;
}
}
}
private float getCenterXForColumn(int column) {
return mPaddingLeft + column * mSquareWidth + mSquareWidth / 2f;
}
private float getCenterYForRow(int row) {
return mPaddingTop + row * mSquareHeight + mSquareHeight / 2f;
}
@Override
protected void onDraw(Canvas canvas) {
final ArrayList<Cell> pattern = mPattern;
final int count = pattern.size();
final boolean[][] drawLookup = mPatternDrawLookup;
if (mPatternDisplayMode == DisplayMode.Animate) {
// figure out which circles to draw
// + 1 so we pause on complete pattern
final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING;
final int spotInCycle = (int) (SystemClock.elapsedRealtime() - mAnimatingPeriodStart)
% oneCycle;
final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING;
clearPatternDrawLookup();
for (int i = 0; i < numCircles; i++) {
final Cell cell = pattern.get(i);
drawLookup[cell.getRow()][cell.getColumn()] = true;
}
// figure out in progress portion of ghosting line
final boolean needToUpdateInProgressPoint = numCircles > 0
&& numCircles < count;
if (needToUpdateInProgressPoint) {
final float percentageOfNextCircle = ((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING))
/ MILLIS_PER_CIRCLE_ANIMATING;
final Cell currentCell = pattern.get(numCircles - 1);
final float centerX = getCenterXForColumn(currentCell.mColumn);
final float centerY = getCenterYForRow(currentCell.mRow);
final Cell nextCell = pattern.get(numCircles);
final float dx = percentageOfNextCircle
* (getCenterXForColumn(nextCell.mColumn) - centerX);
final float dy = percentageOfNextCircle
* (getCenterYForRow(nextCell.mRow) - centerY);
mInProgressX = centerX + dx;
mInProgressY = centerY + dy;
}
// TODO: Infinite loop here...
invalidate();
}
final float squareWidth = mSquareWidth;
final float squareHeight = mSquareHeight;
float radius = (squareWidth * mDiameterFactor * 0.5f);
mPathPaint.setStrokeWidth(radius);
final Path currentPath = mCurrentPath;
currentPath.rewind();
// draw the circles
final int paddingTop = mPaddingTop;
final int paddingLeft = mPaddingLeft;
for (int i = 0; i < MATRIX_WIDTH; i++) {
float topY = paddingTop + i * squareHeight;
// float centerY = mPaddingTop + i * mSquareHeight + (mSquareHeight
// / 2);
for (int j = 0; j < MATRIX_WIDTH; j++) {
float leftX = paddingLeft + j * squareWidth;
drawCircle(canvas, (int) leftX, (int) topY, drawLookup[i][j]);
}
}
// TODO: the path should be created and cached every time we hit-detect
// a cell
// only the last segment of the path should be computed here
// draw the path of the pattern (unless the user is in progress, and
// we are in stealth mode)
final boolean drawPath = (!mInStealthMode || mPatternDisplayMode == DisplayMode.Wrong);
// draw the arrows associated with the path (unless the user is in
// progress, and
// we are in stealth mode)
boolean oldFlag = (mPaint.getFlags() & Paint.FILTER_BITMAP_FLAG) != 0;
mPaint.setFilterBitmap(true); // draw with higher quality since we
// render with transforms
if (drawPath) {
for (int i = 0; i < count - 1; i++) {
Cell cell = pattern.get(i);
Cell next = pattern.get(i + 1);
// only draw the part of the pattern stored in
// the lookup table (this is only different in the case
// of animation).
if (!drawLookup[next.mRow][next.mColumn]) {
break;
}
float leftX = paddingLeft + cell.mColumn * squareWidth;
float topY = paddingTop + cell.mRow * squareHeight;
drawArrow(canvas, leftX, topY, cell, next);
}
}
if (drawPath) {
boolean anyCircles = false;
for (int i = 0; i < count; i++) {
Cell cell = pattern.get(i);
// only draw the part of the pattern stored in
// the lookup table (this is only different in the case
// of animation).
if (!drawLookup[cell.mRow][cell.mColumn]) {
break;
}
anyCircles = true;
float centerX = getCenterXForColumn(cell.mColumn);
float centerY = getCenterYForRow(cell.mRow);
if (i == 0) {
currentPath.moveTo(centerX, centerY);
} else {
currentPath.lineTo(centerX, centerY);
}
}
// add last in progress section
if ((mPatternInProgress || mPatternDisplayMode == DisplayMode.Animate)
&& anyCircles && count > 1) {
currentPath.lineTo(mInProgressX, mInProgressY);
}
canvas.drawPath(currentPath, mPathPaint);
}
mPaint.setFilterBitmap(oldFlag); // restore default flag
}
private void drawArrow(Canvas canvas, float leftX, float topY, Cell start,
Cell end) {
boolean green = mPatternDisplayMode != DisplayMode.Wrong;
final int endRow = end.mRow;
final int startRow = start.mRow;
final int endColumn = end.mColumn;
final int startColumn = start.mColumn;
// offsets for centering the bitmap in the cell
final int offsetX = ((int) mSquareWidth - mBitmapWidth) / 2;
final int offsetY = ((int) mSquareHeight - mBitmapHeight) / 2;
// compute transform to place arrow bitmaps at correct angle inside
// circle.
// This assumes that the arrow image is drawn at 12:00 with it's top
// edge
// coincident with the circle bitmap's top edge.
Bitmap arrow = green ? mBitmapArrowGreenUp : mBitmapArrowRedUp;
final int cellWidth = mBitmapWidth;
final int cellHeight = mBitmapHeight;
// the up arrow bitmap is at 12:00, so find the rotation from x axis and
// add 90 degrees.
final float theta = (float) Math.atan2((double) (endRow - startRow),
(double) (endColumn - startColumn));
final float angle = (float) Math.toDegrees(theta) + 90.0f;
// compose matrix
float sx = Math.min(mSquareWidth / mBitmapWidth, 1.0f);
float sy = Math.min(mSquareHeight / mBitmapHeight, 1.0f);
mArrowMatrix.setTranslate(leftX + offsetX, topY + offsetY); // transform
// to cell
// position
mArrowMatrix.preTranslate(mBitmapWidth / 2, mBitmapHeight / 2);
mArrowMatrix.preScale(sx, sy);
mArrowMatrix.preTranslate(-mBitmapWidth / 2, -mBitmapHeight / 2);
mArrowMatrix.preRotate(angle, cellWidth / 2.0f, cellHeight / 2.0f); // rotate
// about
// cell
// center
mArrowMatrix.preTranslate((cellWidth - arrow.getWidth()) / 2.0f, 0.0f); // translate
// to
// 12:00
// pos
canvas.drawBitmap(arrow, mArrowMatrix, mPaint);
}
/**
* @param canvas
* @param leftX
* @param topY
* @param partOfPattern
* Whether this circle is part of the pattern.
*/
private void drawCircle(Canvas canvas, int leftX, int topY,
boolean partOfPattern) {
Bitmap outerCircle;
Bitmap innerCircle;
if (!partOfPattern
|| (mInStealthMode && mPatternDisplayMode != DisplayMode.Wrong)) {
// unselected circle
outerCircle = mBitmapCircleDefault;
innerCircle = mBitmapBtnDefault;
} else if (mPatternInProgress) {
// user is in middle of drawing a pattern
outerCircle = mBitmapCircleGreen;
innerCircle = mBitmapBtnTouched;
} else if (mPatternDisplayMode == DisplayMode.Wrong) {
// the pattern is wrong
outerCircle = mBitmapCircleRed;
innerCircle = mBitmapBtnDefault;
} else if (mPatternDisplayMode == DisplayMode.Correct
|| mPatternDisplayMode == DisplayMode.Animate) {
// the pattern is correct
outerCircle = mBitmapCircleGreen;
innerCircle = mBitmapBtnDefault;
} else {
throw new IllegalStateException("unknown display mode "
+ mPatternDisplayMode);
}
final int width = mBitmapWidth;
final int height = mBitmapHeight;
final float squareWidth = mSquareWidth;
final float squareHeight = mSquareHeight;
int offsetX = (int) ((squareWidth - width) / 2f);
int offsetY = (int) ((squareHeight - height) / 2f);
// Allow circles to shrink if the view is too small to hold them.
float sx = Math.min(mSquareWidth / mBitmapWidth, 1.0f);
float sy = Math.min(mSquareHeight / mBitmapHeight, 1.0f);
mCircleMatrix.setTranslate(leftX + offsetX, topY + offsetY);
mCircleMatrix.preTranslate(mBitmapWidth / 2, mBitmapHeight / 2);
mCircleMatrix.preScale(sx, sy);
mCircleMatrix.preTranslate(-mBitmapWidth / 2, -mBitmapHeight / 2);
canvas.drawBitmap(outerCircle, mCircleMatrix, mPaint);
canvas.drawBitmap(innerCircle, mCircleMatrix, mPaint);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState,
LockPatternUtils.patternToString(mPattern),
mPatternDisplayMode.ordinal(), mInputEnabled, mInStealthMode,
mEnableHapticFeedback);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setPattern(DisplayMode.Correct,
LockPatternUtils.stringToPattern(ss.getSerializedPattern()));
mPatternDisplayMode = DisplayMode.values()[ss.getDisplayMode()];
mInputEnabled = ss.isInputEnabled();
mInStealthMode = ss.isInStealthMode();
mEnableHapticFeedback = ss.isTactileFeedbackEnabled();
}
/**
* The parecelable for saving and restoring a lock pattern view.
*/
private static class SavedState extends BaseSavedState {
private final String mSerializedPattern;
private final int mDisplayMode;
private final boolean mInputEnabled;
private final boolean mInStealthMode;
private final boolean mTactileFeedbackEnabled;
/**
* Constructor called from {@link LockPatternView#onSaveInstanceState()}
*/
private SavedState(Parcelable superState, String serializedPattern,
int displayMode, boolean inputEnabled, boolean inStealthMode,
boolean tactileFeedbackEnabled) {
super(superState);
mSerializedPattern = serializedPattern;
mDisplayMode = displayMode;
mInputEnabled = inputEnabled;
mInStealthMode = inStealthMode;
mTactileFeedbackEnabled = tactileFeedbackEnabled;
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
mSerializedPattern = in.readString();
mDisplayMode = in.readInt();
mInputEnabled = (Boolean) in.readValue(null);
mInStealthMode = (Boolean) in.readValue(null);
mTactileFeedbackEnabled = (Boolean) in.readValue(null);
}
public String getSerializedPattern() {
return mSerializedPattern;
}
public int getDisplayMode() {
return mDisplayMode;
}
public boolean isInputEnabled() {
return mInputEnabled;
}
public boolean isInStealthMode() {
return mInStealthMode;
}
public boolean isTactileFeedbackEnabled() {
return mTactileFeedbackEnabled;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(mSerializedPattern);
dest.writeInt(mDisplayMode);
dest.writeValue(mInputEnabled);
dest.writeValue(mInStealthMode);
dest.writeValue(mTactileFeedbackEnabled);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/widget/LockPatternView.java
|
Java
|
asf20
| 47,483
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.widget;
import group.pals.android.lib.ui.lockpattern.BuildConfig;
import group.pals.android.lib.ui.lockpattern.collect.Lists;
import group.pals.android.lib.ui.lockpattern.util.Randoms;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.util.Log;
/**
* Utilities for the lock pattern and its settings.
*/
public class LockPatternUtils {
/**
* Used for debugging...
*/
private static final String CLASSNAME = LockPatternUtils.class.getName();
/**
* "UTF-8"
*/
public static final String UTF8 = "UTF-8";
/**
* "SHA-1"
*/
public static final String SHA1 = "SHA-1";
/**
* Deserialize a pattern.
*
* @param string
* The pattern serialized with {@link #patternToString}
* @return The pattern.
*/
public static List<LockPatternView.Cell> stringToPattern(String string) {
List<LockPatternView.Cell> result = Lists.newArrayList();
try {
final byte[] bytes = string.getBytes(UTF8);
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
result.add(LockPatternView.Cell.of(b / 3, b % 3));
}
} catch (UnsupportedEncodingException e) {
// never catch this
}
return result;
}// stringToPattern()
/**
* Serialize a pattern.
*
* @param pattern
* The pattern.
* @return The pattern in string form.
*/
public static String patternToString(List<LockPatternView.Cell> pattern) {
if (pattern == null) {
return "";
}
final int patternSize = pattern.size();
byte[] res = new byte[patternSize];
for (int i = 0; i < patternSize; i++) {
LockPatternView.Cell cell = pattern.get(i);
res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
}
try {
return new String(res, UTF8);
} catch (UnsupportedEncodingException e) {
// never catch this
return "";
}
}// patternToString()
/**
* Serializes a pattern
*
* @param pattern
* The pattern
* @return The SHA-1 string of the pattern got from
* {@link #patternToString(List)}
*/
public static String patternToSha1(List<LockPatternView.Cell> pattern) {
try {
MessageDigest md = MessageDigest.getInstance(SHA1);
md.update(patternToString(pattern).getBytes(UTF8));
byte[] digest = md.digest();
BigInteger bi = new BigInteger(1, digest);
return String.format((Locale) null,
"%0" + (digest.length * 2) + "x", bi).toLowerCase();
} catch (NoSuchAlgorithmException e) {
// never catch this
return "";
} catch (UnsupportedEncodingException e) {
// never catch this
return "";
}
}// patternToSha1()
/**
* Generates a random "CAPTCHA" pattern. By saying "CAPTCHA", this method
* ensures that the generated pattern is easy for the user to re-draw.
* <p>
* <b>Notes:</b> This method is <b>not</b> optimized and <b>not</b>
* benchmarked yet for large size of the pattern's matrix. Currently it
* works fine with a matrix of {@code 3x3} cells. Be careful when the size
* increases.
* </p>
*
* @param size
* the size of the pattern to be generated.
* @return the generated pattern.
* @throws IndexOutOfBoundsException
* if {@code size <= 0} or {@code size > }
* {@link LockPatternView#MATRIX_SIZE}.
* @since v2.7 beta
* @author Hai Bison
*/
public static ArrayList<LockPatternView.Cell> genCaptchaPattern(int size)
throws IndexOutOfBoundsException {
if (size <= 0 || size > LockPatternView.MATRIX_SIZE)
throw new IndexOutOfBoundsException(
"`size` must be in range [1, `LockPatternView.MATRIX_SIZE`]");
final List<Integer> usedIds = Lists.newArrayList();
int lastId = Randoms.randInt(LockPatternView.MATRIX_SIZE);
usedIds.add(lastId);
while (usedIds.size() < size) {
/*
* We start from an empty matrix, so there's always a break point to
* exit this loop.
*/
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, " >> lastId = " + lastId);
final int lastRow = lastId / LockPatternView.MATRIX_WIDTH;
final int lastCol = lastId % LockPatternView.MATRIX_WIDTH;
/*
* This is the max available rows/ columns that we can reach from
* the cell of `lastId` to the border of the matrix.
*/
final int maxDistance = Math.max(
Math.max(lastRow, LockPatternView.MATRIX_WIDTH - lastRow),
Math.max(lastCol, LockPatternView.MATRIX_WIDTH - lastCol));
lastId = -1;
/*
* Starting from `distance` = 1, find the closest-available
* neighbour value of the cell [lastRow, lastCol].
*/
for (int distance = 1; distance <= maxDistance; distance++) {
/*
* Now we have a square surrounding the current cell. We call it
* ABCD, in which A is top-left, and C is bottom-right.
*/
final int rowA = lastRow - distance;
final int colA = lastCol - distance;
final int rowC = lastRow + distance;
final int colC = lastCol + distance;
int[] randomValues;
/*
* Process randomly AB, BC, CD, and DA. Break the loop as soon
* as we find one value.
*/
final int[] lines = Randoms.randIntArray(4);
for (int line : lines) {
switch (line) {
case 0: {
if (rowA >= 0) {
randomValues = Randoms.randIntArray(Math.max(0,
colA), Math.min(
LockPatternView.MATRIX_WIDTH, colC + 1));
for (int c : randomValues) {
lastId = rowA * LockPatternView.MATRIX_WIDTH
+ c;
if (usedIds.contains(lastId))
lastId = -1;
else
break;
}
}
break;
}// AB
case 1: {
if (colC < LockPatternView.MATRIX_WIDTH) {
randomValues = Randoms.randIntArray(Math.max(0,
rowA + 1), Math.min(
LockPatternView.MATRIX_WIDTH, rowC + 1));
for (int r : randomValues) {
lastId = r * LockPatternView.MATRIX_WIDTH
+ colC;
if (usedIds.contains(lastId))
lastId = -1;
else
break;
}
}
break;
}// BC
case 2: {
if (rowC < LockPatternView.MATRIX_WIDTH) {
randomValues = Randoms.randIntArray(Math.max(0,
colA), Math.min(
LockPatternView.MATRIX_WIDTH, colC));
for (int c : randomValues) {
lastId = rowC * LockPatternView.MATRIX_WIDTH
+ c;
if (usedIds.contains(lastId))
lastId = -1;
else
break;
}
}
break;
}// DC
case 3: {
if (colA >= 0) {
randomValues = Randoms.randIntArray(Math.max(0,
rowA + 1), Math.min(
LockPatternView.MATRIX_WIDTH, rowC));
for (int r : randomValues) {
lastId = r * LockPatternView.MATRIX_WIDTH
+ colA;
if (usedIds.contains(lastId))
lastId = -1;
else
break;
}
}
break;
}// AD
}
if (lastId >= 0)
break;
}// for line
if (lastId >= 0)
break;
}// for distance
usedIds.add(lastId);
}// while
final ArrayList<LockPatternView.Cell> result = Lists.newArrayList();
for (int id : usedIds)
result.add(LockPatternView.Cell.of(id));
return result;
}// genCaptchaPattern()
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/widget/LockPatternUtils.java
|
Java
|
asf20
| 10,471
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityManager;
/**
* Helper class for {@link LockPatternView} in API 14+.
* <p>
* <b>Minimum API: 14</b>
* </p>
*
* @author Hai Bison
* @since v2.4 beta
*/
public class LockPatternView_v14 extends LockPatternView {
private final AccessibilityManager mAccessibilityManager;
public LockPatternView_v14(Context context) {
this(context, null);
}
public LockPatternView_v14(Context context, AttributeSet attrs) {
super(context, attrs);
mAccessibilityManager = isInEditMode() ? null
: (AccessibilityManager) context
.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
@Override
public boolean onHoverEvent(MotionEvent event) {
if (mAccessibilityManager != null
&& mAccessibilityManager.isTouchExplorationEnabled()) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_HOVER_ENTER:
event.setAction(MotionEvent.ACTION_DOWN);
break;
case MotionEvent.ACTION_HOVER_MOVE:
event.setAction(MotionEvent.ACTION_MOVE);
break;
case MotionEvent.ACTION_HOVER_EXIT:
event.setAction(MotionEvent.ACTION_UP);
break;
}
onTouchEvent(event);
event.setAction(action);
}
return super.onHoverEvent(event);
}
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/widget/LockPatternView_v14.java
|
Java
|
asf20
| 2,289
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern.collect;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
* <p/>
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
* <p/>
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
* <p/>
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
* <p/>
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
* <p/>
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/collect/Lists.java
|
Java
|
asf20
| 2,227
|
/*
* Copyright 2012 Hai Bison
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package group.pals.android.lib.ui.lockpattern;
import group.pals.android.lib.ui.lockpattern.prefs.DisplayPrefs;
import group.pals.android.lib.ui.lockpattern.prefs.SecurityPrefs;
import group.pals.android.lib.ui.lockpattern.util.IEncrypter;
import group.pals.android.lib.ui.lockpattern.util.InvalidEncrypterException;
import group.pals.android.lib.ui.lockpattern.util.UI;
import group.pals.android.lib.ui.lockpattern.widget.LockPatternUtils;
import group.pals.android.lib.ui.lockpattern.widget.LockPatternView;
import group.pals.android.lib.ui.lockpattern.widget.LockPatternView.Cell;
import group.pals.android.lib.ui.lockpattern.widget.LockPatternView.DisplayMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
/**
* Main activity for this library.
* <p>
* You can deliver result to {@link PendingIntent}'s and/ or
* {@link ResultReceiver} too. See {@link #EXTRA_PENDING_INTENT_OK},
* {@link #EXTRA_PENDING_INTENT_CANCELLED} and {@link #EXTRA_RESULT_RECEIVER}
* for more details.
* </p>
*
* <h1>NOTES</h1>
* <ul>
* <li>
* You must use one of built-in actions when calling this activity. They start
* with {@code ACTION_*}. Otherwise the library might behave strangely (we don't
* cover those cases).</li>
* <li>You must use one of the themes that this library provides. They start
* with {@code R.style.Alp_Theme_*}. The reason is the themes contain resources
* that the library needs.</li>
* <li>With {@link #ACTION_COMPARE_PATTERN}, there are <b><i>4 possible result
* codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED},
* {@link #RESULT_FAILED} and {@link #RESULT_FORGOT_PATTERN}.</li>
* <li>With {@link #ACTION_VERIFY_CAPTCHA}, there are <b><i>3 possible result
* codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED},
* and {@link #RESULT_FAILED}.</li>
* </ul>
*
* @author Hai Bison
* @since v1.0
*/
public class LockPatternActivity extends Activity {
private static final String CLASSNAME = LockPatternActivity.class.getName();
/**
* Use this action to create new pattern. You can provide an
* {@link IEncrypter} with
* {@link SecurityPrefs#setEncrypterClass(android.content.Context, Class)}
* to improve security.
* <p>
* If the user created a pattern, {@link Activity#RESULT_OK} returns with
* the pattern ({@link #EXTRA_PATTERN}). Otherwise
* {@link Activity#RESULT_CANCELED} returns.
* </p>
*
* @see #EXTRA_PENDING_INTENT_OK
* @see #EXTRA_PENDING_INTENT_CANCELLED
* @since v2.4 beta
*/
public static final String ACTION_CREATE_PATTERN = CLASSNAME
+ ".create_pattern";
/**
* Use this action to compare pattern. You provide the pattern to be
* compared with {@link #EXTRA_PATTERN}.
* <p>
* If you enabled feature auto-save pattern before (with
* {@link SecurityPrefs#setAutoSavePattern(android.content.Context, boolean)}
* ), then you don't need {@link #EXTRA_PATTERN} at this time. But if you
* use this extra, its priority is higher than the one stored in shared
* preferences.
* </p>
* <p>
* You can use {@link #EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN} to help your
* users in case they forgot the patterns.
* </p>
* <p>
* If the user passes, {@link Activity#RESULT_OK} returns. If not,
* {@link #RESULT_FAILED} returns.
* </p>
* <p>
* If the user cancels the task, {@link Activity#RESULT_CANCELED} returns.
* </p>
* <p>
* In any case, there will be key {@link #EXTRA_RETRY_COUNT} available in
* the intent result.
* </p>
*
* @see #EXTRA_PATTERN
* @see #EXTRA_PENDING_INTENT_OK
* @see #EXTRA_PENDING_INTENT_CANCELLED
* @see #RESULT_FAILED
* @see #EXTRA_RETRY_COUNT
* @since v2.4 beta
*/
public static final String ACTION_COMPARE_PATTERN = CLASSNAME
+ ".compare_pattern";
/**
* Use this action to let the activity generate a random pattern and ask the
* user to re-draw it to verify.
* <p>
* The default length of the auto-generated pattern is {@code 4}. You can
* change it with
* {@link DisplayPrefs#setCaptchaWiredDots(android.content.Context, int)}.
* </p>
*
* @since v2.7 beta
*/
public static final String ACTION_VERIFY_CAPTCHA = CLASSNAME
+ ".verify_captcha";
/**
* If you use {@link #ACTION_COMPARE_PATTERN} and the user fails to "login"
* after a number of tries, this activity will finish with this result code.
*
* @see #ACTION_COMPARE_PATTERN
* @see #EXTRA_RETRY_COUNT
*/
public static final int RESULT_FAILED = RESULT_FIRST_USER + 1;
/**
* If you use {@link #ACTION_COMPARE_PATTERN} and the user forgot his/ her
* pattern and decided to ask for your help with recovering the pattern (
* {@link #EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN}), this activity will finish
* with this result code.
*
* @see #ACTION_COMPARE_PATTERN
* @see #EXTRA_RETRY_COUNT
* @see #EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN
* @since v2.8 beta
*/
public static final int RESULT_FORGOT_PATTERN = RESULT_FIRST_USER + 2;
/**
* If you use {@link #ACTION_COMPARE_PATTERN}, and the user fails to "login"
* after a number of tries, this key holds that number.
*
* @see #ACTION_COMPARE_PATTERN
* @see DisplayPrefs#setMaxRetry(android.content.Context, int)
*/
public static final String EXTRA_RETRY_COUNT = CLASSNAME + ".retry_count";
/**
* Sets value of this key to a theme in {@code R.style.Alp_Theme_*}. Default
* is the one you set in your {@code AndroidManifest.xml}.
*
* @since v1.5.3 beta
*/
public static final String EXTRA_THEME = CLASSNAME + ".theme";
/**
* Key to hold the pattern. It must be a {@code char[]} array.
* <p/>
* <ul>
* <li>If you use encrypter, it should be an encrypted array.</li>
* <li>If you don't use encrypter, it should be the SHA-1 value of the
* actual pattern. You can generate the value by
* {@link LockPatternUtils#patternToSha1(List)}.</li>
* </ul>
*
* @since v2 beta
*/
public static final String EXTRA_PATTERN = CLASSNAME + ".pattern";
/**
* You can provide an {@link ResultReceiver} with this key. The activity
* will notify your receiver the same result code and intent data as you
* will receive them in {@link #onActivityResult(int, int, Intent)}.
*
* @since v2.4 beta
*/
public static final String EXTRA_RESULT_RECEIVER = CLASSNAME
+ ".result_receiver";
/**
* Put a {@link PendingIntent} into this key. It will be sent before
* {@link Activity#RESULT_OK} will be returning. If you were calling this
* activity with {@link #ACTION_CREATE_PATTERN}, key {@link #EXTRA_PATTERN}
* will be attached to the original intent which the pending intent holds.
*
* <h1>Notes</h1>
* <ul>
* <li>If you're going to use an activity, you don't need
* {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent, since the library
* will call it inside {@link LockPatternActivity} .</li>
* </ul>
*/
public static final String EXTRA_PENDING_INTENT_OK = CLASSNAME
+ ".pending_intent_ok";
/**
* Put a {@link PendingIntent} into this key. It will be sent before
* {@link Activity#RESULT_CANCELED} will be returning.
*
* <h1>Notes</h1>
* <ul>
* <li>If you're going to use an activity, you don't need
* {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent, since the library
* will call it inside {@link LockPatternActivity} .</li>
* </ul>
*/
public static final String EXTRA_PENDING_INTENT_CANCELLED = CLASSNAME
+ ".pending_intent_cancelled";
/**
* You put a {@link Intent} of <i>{@link Activity}</i> into this extra. The
* library will show a button <i>"Forgot pattern?"</i> and call your intent
* later when the user taps it.
*
* <h1>Notes</h1>
* <ul>
* <li>You don't need {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent,
* since the library will call it inside {@link LockPatternActivity} .</li>
* <li>{@link LockPatternActivity} will finish with
* {@link #RESULT_FORGOT_PATTERN} <i><b>after</b> making a call</i> to start
* your activity.</li>
* <li>It is your responsibility to make sure the Intent is good. The
* library doesn't cover any errors when calling your intent.</li>
* </ul>
*
* @see #ACTION_COMPARE_PATTERN
* @since v2.8 beta
* @author Thanks to Yan Cheng Cheok for his idea.
*/
public static final String EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN = CLASSNAME
+ ".intent_activity_forgot_pattern";
/**
* Helper enum for button OK commands. (Because we use only one "OK" button
* for different commands).
*
* @author Hai Bison
*/
private static enum ButtonOkCommand {
CONTINUE, FORGOT_PATTERN, DONE
}// ButtonOkCommand
/**
* Delay time to reload the lock pattern view after a wrong pattern.
*/
private static final long DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW = DateUtils.SECOND_IN_MILLIS;
/*
* FIELDS
*/
private int mMaxRetry;
private boolean mAutoSave;
private IEncrypter mEncrypter;
private int mMinWiredDots;
private ButtonOkCommand mBtnOkCmd;
private Intent mIntentResult;
private int mRetryCount = 0;
/*
* CONTROLS
*/
private TextView mTextInfo;
private LockPatternView mLockPatternView;
private View mFooter;
private Button mBtnCancel;
private Button mBtnConfirm;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "ClassName = " + CLASSNAME);
/*
* EXTRA_THEME
*/
if (getIntent().hasExtra(EXTRA_THEME))
setTheme(getIntent().getIntExtra(EXTRA_THEME,
R.style.Alp_Theme_Dark));
super.onCreate(savedInstanceState);
mMinWiredDots = DisplayPrefs.getMinWiredDots(this);
mMaxRetry = DisplayPrefs.getMaxRetry(this);
mAutoSave = SecurityPrefs.isAutoSavePattern(this);
/*
* Encrypter.
*/
char[] encrypterClass = SecurityPrefs.getEncrypterClass(this);
if (encrypterClass != null) {
try {
mEncrypter = (IEncrypter) Class.forName(
new String(encrypterClass), false, getClassLoader())
.newInstance();
} catch (Throwable t) {
throw new InvalidEncrypterException();
}
}
mIntentResult = new Intent();
setResult(RESULT_CANCELED, mIntentResult);
initContentView();
}// onCreate()
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(CLASSNAME, "onConfigurationChanged()");
super.onConfigurationChanged(newConfig);
initContentView();
}// onConfigurationChanged()
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* Use this hook instead of onBackPressed(), because onBackPressed()
* is not available in API 4.
*/
finishWithNegativeResult(RESULT_CANCELED);
return true;
}
return super.onKeyDown(keyCode, event);
}// onKeyDown()
@Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "onDestroy()");
}// onDestroy()
/**
* Initializes UI...
*/
private void initContentView() {
/*
* Save all controls' state to restore later.
*/
CharSequence infoText = mTextInfo != null ? mTextInfo.getText() : null;
Boolean btnOkEnabled = mBtnConfirm != null ? mBtnConfirm.isEnabled()
: null;
LockPatternView.DisplayMode lastDisplayMode = mLockPatternView != null ? mLockPatternView
.getDisplayMode() : null;
List<Cell> lastPattern = mLockPatternView != null ? mLockPatternView
.getPattern() : null;
setContentView(R.layout.alp_lock_pattern_activity);
UI.adjustDialogSizeForLargeScreen(getWindow());
mTextInfo = (TextView) findViewById(R.id.alp_textview_info);
mLockPatternView = (LockPatternView) findViewById(R.id.alp_view_lock_pattern);
mFooter = findViewById(R.id.alp_viewgroup_footer);
mBtnCancel = (Button) findViewById(R.id.alp_button_cancel);
mBtnConfirm = (Button) findViewById(R.id.alp_button_confirm);
/*
* LOCK PATTERN VIEW
*/
if (getResources().getBoolean(R.bool.alp_is_large_screen)) {
int size = getResources().getDimensionPixelSize(
R.dimen.alp_lockpatternview_size);
LayoutParams lp = mLockPatternView.getLayoutParams();
lp.width = size;
lp.height = size;
mLockPatternView.setLayoutParams(lp);
}
/*
* Haptic feedback.
*/
boolean hapticFeedbackEnabled = false;
try {
hapticFeedbackEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0;
} catch (Throwable t) {
/*
* Ignore it.
*/
}
mLockPatternView.setTactileFeedbackEnabled(hapticFeedbackEnabled);
mLockPatternView.setInStealthMode(DisplayPrefs.isStealthMode(this)
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()));
mLockPatternView.setOnPatternListener(mLockPatternViewListener);
if (lastPattern != null && lastDisplayMode != null
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()))
mLockPatternView.setPattern(lastDisplayMode, lastPattern);
/*
* COMMAND BUTTONS
*/
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
mBtnCancel.setOnClickListener(mBtnCancelOnClickListener);
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnCancel.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
if (infoText != null)
mTextInfo.setText(infoText);
else
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
/*
* BUTTON OK
*/
if (mBtnOkCmd == null)
mBtnOkCmd = ButtonOkCommand.CONTINUE;
switch (mBtnOkCmd) {
case CONTINUE:
mBtnConfirm.setText(R.string.alp_cmd_continue);
break;
case DONE:
mBtnConfirm.setText(R.string.alp_cmd_confirm);
break;
default:
/*
* Do nothing.
*/
break;
}
if (btnOkEnabled != null)
mBtnConfirm.setEnabled(btnOkEnabled);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
if (TextUtils.isEmpty(infoText))
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
else
mTextInfo.setText(infoText);
if (getIntent().hasExtra(EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN)) {
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnConfirm.setText(R.string.alp_cmd_forgot_pattern);
mBtnConfirm.setEnabled(true);
mFooter.setVisibility(View.VISIBLE);
}
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
/*
* NOTE: EXTRA_PATTERN should hold a char[] array. In this case we
* use it as a temporary variable to hold a list of Cell.
*/
final ArrayList<Cell> pattern;
if (getIntent().hasExtra(EXTRA_PATTERN))
pattern = getIntent()
.getParcelableArrayListExtra(EXTRA_PATTERN);
else
getIntent().putParcelableArrayListExtra(
EXTRA_PATTERN,
pattern = LockPatternUtils
.genCaptchaPattern(DisplayPrefs
.getCaptchaWiredDots(this)));
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// initContentView()
/**
* Compares {@code pattern} to the given pattern (
* {@link #ACTION_COMPARE_PATTERN}) or to the generated "CAPTCHA" pattern (
* {@link #ACTION_VERIFY_CAPTCHA}). Then finishes the activity if they
* match.
*
* @param pattern
* the pattern to be compared.
*/
private void doComparePattern(List<Cell> pattern) {
if (pattern == null)
return;
boolean okey = false;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
char[] currentPattern = getIntent()
.getCharArrayExtra(EXTRA_PATTERN);
if (currentPattern == null)
currentPattern = SecurityPrefs.getPattern(this);
if (currentPattern != null) {
if (mEncrypter != null)
okey = pattern.equals(mEncrypter.decrypt(this,
currentPattern));
else
okey = Arrays.equals(currentPattern, LockPatternUtils
.patternToSha1(pattern).toCharArray());
} else
okey = false;
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
okey = pattern.equals(getIntent().getParcelableArrayListExtra(
EXTRA_PATTERN));
}// ACTION_VERIFY_CAPTCHA
if (okey)
finishWithResultOk(null);
else {
mRetryCount++;
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
if (mRetryCount >= mMaxRetry)
finishWithNegativeResult(RESULT_FAILED);
else {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(R.string.alp_msg_try_again);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
}
}// doComparePattern()
/**
* Checks and creates the pattern.
*
* @param pattern
* the current pattern of lock pattern view.
*/
private void doCheckAndCreatePattern(List<Cell> pattern) {
if (pattern.size() < mMinWiredDots) {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(getResources().getQuantityString(
R.plurals.alp_pmsg_connect_x_dots, mMinWiredDots,
mMinWiredDots));
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
return;
}
if (getIntent().hasExtra(EXTRA_PATTERN)) {
final boolean okey;
if (mEncrypter != null)
okey = pattern.equals(mEncrypter.decrypt(this, getIntent()
.getCharArrayExtra(EXTRA_PATTERN)));
else
okey = Arrays.equals(
getIntent().getCharArrayExtra(EXTRA_PATTERN),
LockPatternUtils.patternToSha1(pattern).toCharArray());
if (okey) {
mTextInfo.setText(R.string.alp_msg_your_new_unlock_pattern);
mBtnConfirm.setEnabled(true);
} else {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setEnabled(false);
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
} else {
getIntent().putExtra(
EXTRA_PATTERN,
mEncrypter != null ? mEncrypter.encrypt(this, pattern)
: LockPatternUtils.patternToSha1(pattern)
.toCharArray());
mTextInfo.setText(R.string.alp_msg_pattern_recorded);
mBtnConfirm.setEnabled(true);
}
}// doCheckAndCreatePattern()
/**
* Finishes activity with {@link Activity#RESULT_OK}.
*
* @param pattern
* the pattern, if this is in mode creating pattern. In any
* cases, it can be set to {@code null}.
*/
private void finishWithResultOk(char[] pattern) {
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be zero.
*/
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
setResult(RESULT_OK, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle bundle = new Bundle();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
bundle.putCharArray(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be
* zero.
*/
bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
receiver.send(RESULT_OK, bundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_OK);
if (pi != null) {
try {
pi.send(this, RESULT_OK, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithResultOk()
/**
* Finishes the activity with negative result (
* {@link Activity#RESULT_CANCELED}, {@link #RESULT_FAILED} or
* {@link #RESULT_FORGOT_PATTERN}).
*/
private void finishWithNegativeResult(int resultCode) {
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
setResult(resultCode, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle resultBundle = null;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
resultBundle = new Bundle();
resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount);
}
receiver.send(resultCode, resultBundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_CANCELLED);
if (pi != null) {
try {
pi.send(this, resultCode, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithNegativeResult()
/*
* LISTENERS
*/
private final LockPatternView.OnPatternListener mLockPatternViewListener = new LockPatternView.OnPatternListener() {
@Override
public void onPatternStart() {
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
mLockPatternView.setDisplayMode(DisplayMode.Correct);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_release_finger_when_done);
mBtnConfirm.setEnabled(false);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE)
getIntent().removeExtra(EXTRA_PATTERN);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_VERIFY_CAPTCHA
}// onPatternStart()
@Override
public void onPatternDetected(List<Cell> pattern) {
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
doCheckAndCreatePattern(pattern);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
doComparePattern(pattern);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
if (!DisplayMode.Animate.equals(mLockPatternView
.getDisplayMode()))
doComparePattern(pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternDetected()
@Override
public void onPatternCleared() {
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mBtnConfirm.setEnabled(false);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
getIntent().removeExtra(EXTRA_PATTERN);
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
} else
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
List<Cell> pattern = getIntent().getParcelableArrayListExtra(
EXTRA_PATTERN);
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternCleared()
@Override
public void onPatternCellAdded(List<Cell> pattern) {
// TODO Auto-generated method stub
}// onPatternCellAdded()
};// mLockPatternViewListener
private final View.OnClickListener mBtnCancelOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
finishWithNegativeResult(RESULT_CANCELED);
}// onClick()
};// mBtnCancelOnClickListener
private final View.OnClickListener mBtnConfirmOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
mBtnOkCmd = ButtonOkCommand.DONE;
mLockPatternView.clearPattern();
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setText(R.string.alp_cmd_confirm);
mBtnConfirm.setEnabled(false);
} else {
final char[] pattern = getIntent().getCharArrayExtra(
EXTRA_PATTERN);
if (mAutoSave)
SecurityPrefs.setPattern(LockPatternActivity.this,
pattern);
finishWithResultOk(pattern);
}
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* We don't need to verify the extra. First, this button is only
* visible if there is this extra in the intent. Second, it is
* the responsibility of the caller to make sure the extra is an
* Intent of Activity.
*/
startActivity((Intent) getIntent().getParcelableExtra(
EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN));
finishWithNegativeResult(RESULT_FORGOT_PATTERN);
}// ACTION_COMPARE_PATTERN
}// onClick()
};// mBtnConfirmOnClickListener
/**
* This reloads the {@link #mLockPatternView} after a wrong pattern.
*/
private final Runnable mLockPatternViewReloader = new Runnable() {
@Override
public void run() {
mLockPatternView.clearPattern();
mLockPatternViewListener.onPatternCleared();
}// run()
};// mLockPatternViewReloader
}
|
zzljob-android-lockpattern
|
code/src/group/pals/android/lib/ui/lockpattern/LockPatternActivity.java
|
Java
|
asf20
| 31,512
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Debug;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.List;
/**
* Displays and detects the user's unlock attempt, which is a drag of a finger
* across 9 regions of the screen.
*
* Is also capable of displaying a static pattern in "in progress", "wrong" or
* "correct" states.
*/
public class LockPatternView extends View {
private static final String TAG = "LockPatternView";
// Aspect to use when rendering this view
private static final int ASPECT_SQUARE = 0; // View will be the minimum of width/height
private static final int ASPECT_LOCK_WIDTH = 1; // Fixed width; height will be minimum of (w,h)
private static final int ASPECT_LOCK_HEIGHT = 2; // Fixed height; width will be minimum of (w,h)
private static final boolean PROFILE_DRAWING = false;
private boolean mDrawingProfilingStarted = false;
private Paint mPaint = new Paint();
private Paint mPathPaint = new Paint();
// TODO: make this common with PhoneWindow
static final int STATUS_BAR_HEIGHT = 25;
/**
* How many milliseconds we spend animating each circle of a lock pattern
* if the animating mode is set. The entire animation should take this
* constant * the length of the pattern to complete.
*/
private static final int MILLIS_PER_CIRCLE_ANIMATING = 700;
private OnPatternListener mOnPatternListener;
private ArrayList<Cell> mPattern = new ArrayList<Cell>(9);
/**
* Lookup table for the circles of the pattern we are currently drawing.
* This will be the cells of the complete pattern unless we are animating,
* in which case we use this to hold the cells we are drawing for the in
* progress animation.
*/
private boolean[][] mPatternDrawLookup = new boolean[3][3];
/**
* the in progress point:
* - during interaction: where the user's finger is
* - during animation: the current tip of the animating line
*/
private float mInProgressX = -1;
private float mInProgressY = -1;
private long mAnimatingPeriodStart;
private DisplayMode mPatternDisplayMode = DisplayMode.Correct;
private boolean mInputEnabled = true;
private boolean mInStealthMode = false;
private boolean mEnableHapticFeedback = true;
private boolean mPatternInProgress = false;
private float mDiameterFactor = 0.10f; // TODO: move to attrs
private final int mStrokeAlpha = 128;
private float mHitFactor = 0.6f;
private float mSquareWidth;
private float mSquareHeight;
private Bitmap mBitmapBtnDefault;
private Bitmap mBitmapBtnTouched;
private Bitmap mBitmapCircleDefault;
private Bitmap mBitmapCircleGreen;
private Bitmap mBitmapCircleRed;
private Bitmap mBitmapArrowGreenUp;
private Bitmap mBitmapArrowRedUp;
private final Path mCurrentPath = new Path();
private final Rect mInvalidate = new Rect();
private int mBitmapWidth;
private int mBitmapHeight;
private int mAspect;
private final Matrix mArrowMatrix = new Matrix();
private final Matrix mCircleMatrix = new Matrix();
/**
* Represents a cell in the 3 X 3 matrix of the unlock pattern view.
*/
public static class Cell {
int row;
int column;
// keep # objects limited to 9
static Cell[][] sCells = new Cell[3][3];
static {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sCells[i][j] = new Cell(i, j);
}
}
}
/**
* @param row The row of the cell.
* @param column The column of the cell.
*/
private Cell(int row, int column) {
checkRange(row, column);
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
/**
* @param row The row of the cell.
* @param column The column of the cell.
*/
public static synchronized Cell of(int row, int column) {
checkRange(row, column);
return sCells[row][column];
}
private static void checkRange(int row, int column) {
if (row < 0 || row > 2) {
throw new IllegalArgumentException("row must be in range 0-2");
}
if (column < 0 || column > 2) {
throw new IllegalArgumentException("column must be in range 0-2");
}
}
public String toString() {
return "(row=" + row + ",clmn=" + column + ")";
}
}
/**
* How to display the current pattern.
*/
public enum DisplayMode {
/**
* The pattern drawn is correct (i.e draw it in a friendly color)
*/
Correct,
/**
* Animate the pattern (for demo, and help).
*/
Animate,
/**
* The pattern is wrong (i.e draw a foreboding color)
*/
Wrong
}
/**
* The call back interface for detecting patterns entered by the user.
*/
public static interface OnPatternListener {
/**
* A new pattern has begun.
*/
void onPatternStart();
/**
* The pattern was cleared.
*/
void onPatternCleared();
/**
* The user extended the pattern currently being drawn by one cell.
* @param pattern The pattern with newly added cell.
*/
void onPatternCellAdded(List<Cell> pattern);
/**
* A pattern was detected from the user.
* @param pattern The pattern.
*/
void onPatternDetected(List<Cell> pattern);
}
public LockPatternView(Context context) {
this(context, null);
}
public LockPatternView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LockPatternView);
final String aspect = a.getString(R.styleable.LockPatternView_aspect);
if ("square".equals(aspect)) {
mAspect = ASPECT_SQUARE;
} else if ("lock_width".equals(aspect)) {
mAspect = ASPECT_LOCK_WIDTH;
} else if ("lock_height".equals(aspect)) {
mAspect = ASPECT_LOCK_HEIGHT;
} else {
mAspect = ASPECT_SQUARE;
}
setClickable(true);
mPathPaint.setAntiAlias(true);
mPathPaint.setDither(true);
mPathPaint.setColor(Color.WHITE); // TODO this should be from the style
mPathPaint.setAlpha(mStrokeAlpha);
mPathPaint.setStyle(Paint.Style.STROKE);
mPathPaint.setStrokeJoin(Paint.Join.ROUND);
mPathPaint.setStrokeCap(Paint.Cap.ROUND);
// lot's of bitmaps!
mBitmapBtnDefault = getBitmapFor(R.drawable.btn_code_lock_default_holo);
mBitmapBtnTouched = getBitmapFor(R.drawable.btn_code_lock_touched_holo);
mBitmapCircleDefault = getBitmapFor(R.drawable.indicator_code_lock_point_area_default_holo);
mBitmapCircleGreen = getBitmapFor(R.drawable.indicator_code_lock_point_area_green_holo);
mBitmapCircleRed = getBitmapFor(R.drawable.indicator_code_lock_point_area_red_holo);
mBitmapArrowGreenUp = getBitmapFor(R.drawable.indicator_code_lock_drag_direction_green_up);
mBitmapArrowRedUp = getBitmapFor(R.drawable.indicator_code_lock_drag_direction_red_up);
// bitmaps have the size of the largest bitmap in this group
final Bitmap bitmaps[] = { mBitmapBtnDefault, mBitmapBtnTouched, mBitmapCircleDefault,
mBitmapCircleGreen, mBitmapCircleRed };
for (Bitmap bitmap : bitmaps) {
mBitmapWidth = Math.max(mBitmapWidth, bitmap.getWidth());
mBitmapHeight = Math.max(mBitmapHeight, bitmap.getHeight());
}
}
private Bitmap getBitmapFor(int resId) {
return BitmapFactory.decodeResource(getContext().getResources(), resId);
}
/**
* @return Whether the view is in stealth mode.
*/
public boolean isInStealthMode() {
return mInStealthMode;
}
/**
* @return Whether the view has tactile feedback enabled.
*/
public boolean isTactileFeedbackEnabled() {
return mEnableHapticFeedback;
}
/**
* Set whether the view is in stealth mode. If true, there will be no
* visible feedback as the user enters the pattern.
*
* @param inStealthMode Whether in stealth mode.
*/
public void setInStealthMode(boolean inStealthMode) {
mInStealthMode = inStealthMode;
}
/**
* Set whether the view will use tactile feedback. If true, there will be
* tactile feedback as the user enters the pattern.
*
* @param tactileFeedbackEnabled Whether tactile feedback is enabled
*/
public void setTactileFeedbackEnabled(boolean tactileFeedbackEnabled) {
mEnableHapticFeedback = tactileFeedbackEnabled;
}
/**
* Set the call back for pattern detection.
* @param onPatternListener The call back.
*/
public void setOnPatternListener(
OnPatternListener onPatternListener) {
mOnPatternListener = onPatternListener;
}
/**
* Set the pattern explicitely (rather than waiting for the user to input
* a pattern).
* @param displayMode How to display the pattern.
* @param pattern The pattern.
*/
public void setPattern(DisplayMode displayMode, List<Cell> pattern) {
mPattern.clear();
mPattern.addAll(pattern);
clearPatternDrawLookup();
for (Cell cell : pattern) {
mPatternDrawLookup[cell.getRow()][cell.getColumn()] = true;
}
setDisplayMode(displayMode);
}
/**
* Set the display mode of the current pattern. This can be useful, for
* instance, after detecting a pattern to tell this view whether change the
* in progress result to correct or wrong.
* @param displayMode The display mode.
*/
public void setDisplayMode(DisplayMode displayMode) {
mPatternDisplayMode = displayMode;
if (displayMode == DisplayMode.Animate) {
if (mPattern.size() == 0) {
throw new IllegalStateException("you must have a pattern to "
+ "animate if you want to set the display mode to animate");
}
mAnimatingPeriodStart = SystemClock.elapsedRealtime();
final Cell first = mPattern.get(0);
mInProgressX = getCenterXForColumn(first.getColumn());
mInProgressY = getCenterYForRow(first.getRow());
clearPatternDrawLookup();
}
invalidate();
}
private void notifyCellAdded() {
sendAccessEvent(R.string.lockscreen_access_pattern_cell_added);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternCellAdded(mPattern);
}
}
private void notifyPatternStarted() {
sendAccessEvent(R.string.lockscreen_access_pattern_start);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternStart();
}
}
private void notifyPatternDetected() {
sendAccessEvent(R.string.lockscreen_access_pattern_detected);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternDetected(mPattern);
}
}
private void notifyPatternCleared() {
sendAccessEvent(R.string.lockscreen_access_pattern_cleared);
if (mOnPatternListener != null) {
mOnPatternListener.onPatternCleared();
}
}
/**
* Clear the pattern.
*/
public void clearPattern() {
resetPattern();
}
/**
* Reset all pattern state.
*/
private void resetPattern() {
mPattern.clear();
clearPatternDrawLookup();
mPatternDisplayMode = DisplayMode.Correct;
invalidate();
}
/**
* Clear the pattern lookup table.
*/
private void clearPatternDrawLookup() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
mPatternDrawLookup[i][j] = false;
}
}
}
/**
* Disable input (for instance when displaying a message that will
* timeout so user doesn't get view into messy state).
*/
public void disableInput() {
mInputEnabled = false;
}
/**
* Enable input.
*/
public void enableInput() {
mInputEnabled = true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
final int width = w - mPaddingLeft - mPaddingRight;
mSquareWidth = width / 3.0f;
final int height = h - mPaddingTop - mPaddingBottom;
mSquareHeight = height / 3.0f;
}
private int resolveMeasured(int measureSpec, int desired)
{
int result = 0;
int specSize = MeasureSpec.getSize(measureSpec);
switch (MeasureSpec.getMode(measureSpec)) {
case MeasureSpec.UNSPECIFIED:
result = desired;
break;
case MeasureSpec.AT_MOST:
result = Math.max(specSize, desired);
break;
case MeasureSpec.EXACTLY:
default:
result = specSize;
}
return result;
}
@Override
protected int getSuggestedMinimumWidth() {
// View should be large enough to contain 3 side-by-side target bitmaps
return 3 * mBitmapWidth;
}
@Override
protected int getSuggestedMinimumHeight() {
// View should be large enough to contain 3 side-by-side target bitmaps
return 3 * mBitmapWidth;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int minimumWidth = getSuggestedMinimumWidth();
final int minimumHeight = getSuggestedMinimumHeight();
int viewWidth = resolveMeasured(widthMeasureSpec, minimumWidth);
int viewHeight = resolveMeasured(heightMeasureSpec, minimumHeight);
switch (mAspect) {
case ASPECT_SQUARE:
viewWidth = viewHeight = Math.min(viewWidth, viewHeight);
break;
case ASPECT_LOCK_WIDTH:
viewHeight = Math.min(viewWidth, viewHeight);
break;
case ASPECT_LOCK_HEIGHT:
viewWidth = Math.min(viewWidth, viewHeight);
break;
}
// Log.v(TAG, "LockPatternView dimensions: " + viewWidth + "x" + viewHeight);
setMeasuredDimension(viewWidth, viewHeight);
}
/**
* Determines whether the point x, y will add a new point to the current
* pattern (in addition to finding the cell, also makes heuristic choices
* such as filling in gaps based on current pattern).
* @param x The x coordinate.
* @param y The y coordinate.
*/
private Cell detectAndAddHit(float x, float y) {
final Cell cell = checkForNewHit(x, y);
if (cell != null) {
// check for gaps in existing pattern
Cell fillInGapCell = null;
final ArrayList<Cell> pattern = mPattern;
if (!pattern.isEmpty()) {
final Cell lastCell = pattern.get(pattern.size() - 1);
int dRow = cell.row - lastCell.row;
int dColumn = cell.column - lastCell.column;
int fillInRow = lastCell.row;
int fillInColumn = lastCell.column;
if (Math.abs(dRow) == 2 && Math.abs(dColumn) != 1) {
fillInRow = lastCell.row + ((dRow > 0) ? 1 : -1);
}
if (Math.abs(dColumn) == 2 && Math.abs(dRow) != 1) {
fillInColumn = lastCell.column + ((dColumn > 0) ? 1 : -1);
}
fillInGapCell = Cell.of(fillInRow, fillInColumn);
}
if (fillInGapCell != null &&
!mPatternDrawLookup[fillInGapCell.row][fillInGapCell.column]) {
addCellToPattern(fillInGapCell);
}
addCellToPattern(cell);
if (mEnableHapticFeedback) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING
| HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
return cell;
}
return null;
}
private void addCellToPattern(Cell newCell) {
mPatternDrawLookup[newCell.getRow()][newCell.getColumn()] = true;
mPattern.add(newCell);
notifyCellAdded();
}
// helper method to find which cell a point maps to
private Cell checkForNewHit(float x, float y) {
final int rowHit = getRowHit(y);
if (rowHit < 0) {
return null;
}
final int columnHit = getColumnHit(x);
if (columnHit < 0) {
return null;
}
if (mPatternDrawLookup[rowHit][columnHit]) {
return null;
}
return Cell.of(rowHit, columnHit);
}
/**
* Helper method to find the row that y falls into.
* @param y The y coordinate
* @return The row that y falls in, or -1 if it falls in no row.
*/
private int getRowHit(float y) {
final float squareHeight = mSquareHeight;
float hitSize = squareHeight * mHitFactor;
float offset = mPaddingTop + (squareHeight - hitSize) / 2f;
for (int i = 0; i < 3; i++) {
final float hitTop = offset + squareHeight * i;
if (y >= hitTop && y <= hitTop + hitSize) {
return i;
}
}
return -1;
}
/**
* Helper method to find the column x fallis into.
* @param x The x coordinate.
* @return The column that x falls in, or -1 if it falls in no column.
*/
private int getColumnHit(float x) {
final float squareWidth = mSquareWidth;
float hitSize = squareWidth * mHitFactor;
float offset = mPaddingLeft + (squareWidth - hitSize) / 2f;
for (int i = 0; i < 3; i++) {
final float hitLeft = offset + squareWidth * i;
if (x >= hitLeft && x <= hitLeft + hitSize) {
return i;
}
}
return -1;
}
@Override
public boolean onHoverEvent(MotionEvent event) {
if (AccessibilityManager.getInstance(mContext).isTouchExplorationEnabled()) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_HOVER_ENTER:
event.setAction(MotionEvent.ACTION_DOWN);
break;
case MotionEvent.ACTION_HOVER_MOVE:
event.setAction(MotionEvent.ACTION_MOVE);
break;
case MotionEvent.ACTION_HOVER_EXIT:
event.setAction(MotionEvent.ACTION_UP);
break;
}
onTouchEvent(event);
event.setAction(action);
}
return super.onHoverEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mInputEnabled || !isEnabled()) {
return false;
}
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
handleActionDown(event);
return true;
case MotionEvent.ACTION_UP:
handleActionUp(event);
return true;
case MotionEvent.ACTION_MOVE:
handleActionMove(event);
return true;
case MotionEvent.ACTION_CANCEL:
if (mPatternInProgress) {
mPatternInProgress = false;
resetPattern();
notifyPatternCleared();
}
if (PROFILE_DRAWING) {
if (mDrawingProfilingStarted) {
Debug.stopMethodTracing();
mDrawingProfilingStarted = false;
}
}
return true;
}
return false;
}
private void handleActionMove(MotionEvent event) {
// Handle all recent motion events so we don't skip any cells even when the device
// is busy...
final int historySize = event.getHistorySize();
for (int i = 0; i < historySize + 1; i++) {
final float x = i < historySize ? event.getHistoricalX(i) : event.getX();
final float y = i < historySize ? event.getHistoricalY(i) : event.getY();
final int patternSizePreHitDetect = mPattern.size();
Cell hitCell = detectAndAddHit(x, y);
final int patternSize = mPattern.size();
if (hitCell != null && patternSize == 1) {
mPatternInProgress = true;
notifyPatternStarted();
}
// note current x and y for rubber banding of in progress patterns
final float dx = Math.abs(x - mInProgressX);
final float dy = Math.abs(y - mInProgressY);
if (dx + dy > mSquareWidth * 0.01f) {
float oldX = mInProgressX;
float oldY = mInProgressY;
mInProgressX = x;
mInProgressY = y;
if (mPatternInProgress && patternSize > 0) {
final ArrayList<Cell> pattern = mPattern;
final float radius = mSquareWidth * mDiameterFactor * 0.5f;
final Cell lastCell = pattern.get(patternSize - 1);
float startX = getCenterXForColumn(lastCell.column);
float startY = getCenterYForRow(lastCell.row);
float left;
float top;
float right;
float bottom;
final Rect invalidateRect = mInvalidate;
if (startX < x) {
left = startX;
right = x;
} else {
left = x;
right = startX;
}
if (startY < y) {
top = startY;
bottom = y;
} else {
top = y;
bottom = startY;
}
// Invalidate between the pattern's last cell and the current location
invalidateRect.set((int) (left - radius), (int) (top - radius),
(int) (right + radius), (int) (bottom + radius));
if (startX < oldX) {
left = startX;
right = oldX;
} else {
left = oldX;
right = startX;
}
if (startY < oldY) {
top = startY;
bottom = oldY;
} else {
top = oldY;
bottom = startY;
}
// Invalidate between the pattern's last cell and the previous location
invalidateRect.union((int) (left - radius), (int) (top - radius),
(int) (right + radius), (int) (bottom + radius));
// Invalidate between the pattern's new cell and the pattern's previous cell
if (hitCell != null) {
startX = getCenterXForColumn(hitCell.column);
startY = getCenterYForRow(hitCell.row);
if (patternSize >= 2) {
// (re-using hitcell for old cell)
hitCell = pattern.get(patternSize - 1 - (patternSize - patternSizePreHitDetect));
oldX = getCenterXForColumn(hitCell.column);
oldY = getCenterYForRow(hitCell.row);
if (startX < oldX) {
left = startX;
right = oldX;
} else {
left = oldX;
right = startX;
}
if (startY < oldY) {
top = startY;
bottom = oldY;
} else {
top = oldY;
bottom = startY;
}
} else {
left = right = startX;
top = bottom = startY;
}
final float widthOffset = mSquareWidth / 2f;
final float heightOffset = mSquareHeight / 2f;
invalidateRect.set((int) (left - widthOffset),
(int) (top - heightOffset), (int) (right + widthOffset),
(int) (bottom + heightOffset));
}
invalidate(invalidateRect);
} else {
invalidate();
}
}
}
}
private void sendAccessEvent(int resId) {
announceForAccessibility(mContext.getString(resId));
}
private void handleActionUp(MotionEvent event) {
// report pattern detected
if (!mPattern.isEmpty()) {
mPatternInProgress = false;
notifyPatternDetected();
invalidate();
}
if (PROFILE_DRAWING) {
if (mDrawingProfilingStarted) {
Debug.stopMethodTracing();
mDrawingProfilingStarted = false;
}
}
}
private void handleActionDown(MotionEvent event) {
resetPattern();
final float x = event.getX();
final float y = event.getY();
final Cell hitCell = detectAndAddHit(x, y);
if (hitCell != null) {
mPatternInProgress = true;
mPatternDisplayMode = DisplayMode.Correct;
notifyPatternStarted();
} else if (mPatternInProgress) {
mPatternInProgress = false;
notifyPatternCleared();
}
if (hitCell != null) {
final float startX = getCenterXForColumn(hitCell.column);
final float startY = getCenterYForRow(hitCell.row);
final float widthOffset = mSquareWidth / 2f;
final float heightOffset = mSquareHeight / 2f;
invalidate((int) (startX - widthOffset), (int) (startY - heightOffset),
(int) (startX + widthOffset), (int) (startY + heightOffset));
}
mInProgressX = x;
mInProgressY = y;
if (PROFILE_DRAWING) {
if (!mDrawingProfilingStarted) {
Debug.startMethodTracing("LockPatternDrawing");
mDrawingProfilingStarted = true;
}
}
}
private float getCenterXForColumn(int column) {
return mPaddingLeft + column * mSquareWidth + mSquareWidth / 2f;
}
private float getCenterYForRow(int row) {
return mPaddingTop + row * mSquareHeight + mSquareHeight / 2f;
}
@Override
protected void onDraw(Canvas canvas) {
final ArrayList<Cell> pattern = mPattern;
final int count = pattern.size();
final boolean[][] drawLookup = mPatternDrawLookup;
if (mPatternDisplayMode == DisplayMode.Animate) {
// figure out which circles to draw
// + 1 so we pause on complete pattern
final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING;
final int spotInCycle = (int) (SystemClock.elapsedRealtime() -
mAnimatingPeriodStart) % oneCycle;
final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING;
clearPatternDrawLookup();
for (int i = 0; i < numCircles; i++) {
final Cell cell = pattern.get(i);
drawLookup[cell.getRow()][cell.getColumn()] = true;
}
// figure out in progress portion of ghosting line
final boolean needToUpdateInProgressPoint = numCircles > 0
&& numCircles < count;
if (needToUpdateInProgressPoint) {
final float percentageOfNextCircle =
((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING)) /
MILLIS_PER_CIRCLE_ANIMATING;
final Cell currentCell = pattern.get(numCircles - 1);
final float centerX = getCenterXForColumn(currentCell.column);
final float centerY = getCenterYForRow(currentCell.row);
final Cell nextCell = pattern.get(numCircles);
final float dx = percentageOfNextCircle *
(getCenterXForColumn(nextCell.column) - centerX);
final float dy = percentageOfNextCircle *
(getCenterYForRow(nextCell.row) - centerY);
mInProgressX = centerX + dx;
mInProgressY = centerY + dy;
}
// TODO: Infinite loop here...
invalidate();
}
final float squareWidth = mSquareWidth;
final float squareHeight = mSquareHeight;
float radius = (squareWidth * mDiameterFactor * 0.5f);
mPathPaint.setStrokeWidth(radius);
final Path currentPath = mCurrentPath;
currentPath.rewind();
// draw the circles
final int paddingTop = mPaddingTop;
final int paddingLeft = mPaddingLeft;
for (int i = 0; i < 3; i++) {
float topY = paddingTop + i * squareHeight;
//float centerY = mPaddingTop + i * mSquareHeight + (mSquareHeight / 2);
for (int j = 0; j < 3; j++) {
float leftX = paddingLeft + j * squareWidth;
drawCircle(canvas, (int) leftX, (int) topY, drawLookup[i][j]);
}
}
// TODO: the path should be created and cached every time we hit-detect a cell
// only the last segment of the path should be computed here
// draw the path of the pattern (unless the user is in progress, and
// we are in stealth mode)
final boolean drawPath = (!mInStealthMode || mPatternDisplayMode == DisplayMode.Wrong);
// draw the arrows associated with the path (unless the user is in progress, and
// we are in stealth mode)
boolean oldFlag = (mPaint.getFlags() & Paint.FILTER_BITMAP_FLAG) != 0;
mPaint.setFilterBitmap(true); // draw with higher quality since we render with transforms
if (drawPath) {
for (int i = 0; i < count - 1; i++) {
Cell cell = pattern.get(i);
Cell next = pattern.get(i + 1);
// only draw the part of the pattern stored in
// the lookup table (this is only different in the case
// of animation).
if (!drawLookup[next.row][next.column]) {
break;
}
float leftX = paddingLeft + cell.column * squareWidth;
float topY = paddingTop + cell.row * squareHeight;
drawArrow(canvas, leftX, topY, cell, next);
}
}
if (drawPath) {
boolean anyCircles = false;
for (int i = 0; i < count; i++) {
Cell cell = pattern.get(i);
// only draw the part of the pattern stored in
// the lookup table (this is only different in the case
// of animation).
if (!drawLookup[cell.row][cell.column]) {
break;
}
anyCircles = true;
float centerX = getCenterXForColumn(cell.column);
float centerY = getCenterYForRow(cell.row);
if (i == 0) {
currentPath.moveTo(centerX, centerY);
} else {
currentPath.lineTo(centerX, centerY);
}
}
// add last in progress section
if ((mPatternInProgress || mPatternDisplayMode == DisplayMode.Animate)
&& anyCircles) {
currentPath.lineTo(mInProgressX, mInProgressY);
}
canvas.drawPath(currentPath, mPathPaint);
}
mPaint.setFilterBitmap(oldFlag); // restore default flag
}
private void drawArrow(Canvas canvas, float leftX, float topY, Cell start, Cell end) {
boolean green = mPatternDisplayMode != DisplayMode.Wrong;
final int endRow = end.row;
final int startRow = start.row;
final int endColumn = end.column;
final int startColumn = start.column;
// offsets for centering the bitmap in the cell
final int offsetX = ((int) mSquareWidth - mBitmapWidth) / 2;
final int offsetY = ((int) mSquareHeight - mBitmapHeight) / 2;
// compute transform to place arrow bitmaps at correct angle inside circle.
// This assumes that the arrow image is drawn at 12:00 with it's top edge
// coincident with the circle bitmap's top edge.
Bitmap arrow = green ? mBitmapArrowGreenUp : mBitmapArrowRedUp;
final int cellWidth = mBitmapWidth;
final int cellHeight = mBitmapHeight;
// the up arrow bitmap is at 12:00, so find the rotation from x axis and add 90 degrees.
final float theta = (float) Math.atan2(
(double) (endRow - startRow), (double) (endColumn - startColumn));
final float angle = (float) Math.toDegrees(theta) + 90.0f;
// compose matrix
float sx = Math.min(mSquareWidth / mBitmapWidth, 1.0f);
float sy = Math.min(mSquareHeight / mBitmapHeight, 1.0f);
mArrowMatrix.setTranslate(leftX + offsetX, topY + offsetY); // transform to cell position
mArrowMatrix.preTranslate(mBitmapWidth/2, mBitmapHeight/2);
mArrowMatrix.preScale(sx, sy);
mArrowMatrix.preTranslate(-mBitmapWidth/2, -mBitmapHeight/2);
mArrowMatrix.preRotate(angle, cellWidth / 2.0f, cellHeight / 2.0f); // rotate about cell center
mArrowMatrix.preTranslate((cellWidth - arrow.getWidth()) / 2.0f, 0.0f); // translate to 12:00 pos
canvas.drawBitmap(arrow, mArrowMatrix, mPaint);
}
/**
* @param canvas
* @param leftX
* @param topY
* @param partOfPattern Whether this circle is part of the pattern.
*/
private void drawCircle(Canvas canvas, int leftX, int topY, boolean partOfPattern) {
Bitmap outerCircle;
Bitmap innerCircle;
if (!partOfPattern || (mInStealthMode && mPatternDisplayMode != DisplayMode.Wrong)) {
// unselected circle
outerCircle = mBitmapCircleDefault;
innerCircle = mBitmapBtnDefault;
} else if (mPatternInProgress) {
// user is in middle of drawing a pattern
outerCircle = mBitmapCircleGreen;
innerCircle = mBitmapBtnTouched;
} else if (mPatternDisplayMode == DisplayMode.Wrong) {
// the pattern is wrong
outerCircle = mBitmapCircleRed;
innerCircle = mBitmapBtnDefault;
} else if (mPatternDisplayMode == DisplayMode.Correct ||
mPatternDisplayMode == DisplayMode.Animate) {
// the pattern is correct
outerCircle = mBitmapCircleGreen;
innerCircle = mBitmapBtnDefault;
} else {
throw new IllegalStateException("unknown display mode " + mPatternDisplayMode);
}
final int width = mBitmapWidth;
final int height = mBitmapHeight;
final float squareWidth = mSquareWidth;
final float squareHeight = mSquareHeight;
int offsetX = (int) ((squareWidth - width) / 2f);
int offsetY = (int) ((squareHeight - height) / 2f);
// Allow circles to shrink if the view is too small to hold them.
float sx = Math.min(mSquareWidth / mBitmapWidth, 1.0f);
float sy = Math.min(mSquareHeight / mBitmapHeight, 1.0f);
mCircleMatrix.setTranslate(leftX + offsetX, topY + offsetY);
mCircleMatrix.preTranslate(mBitmapWidth/2, mBitmapHeight/2);
mCircleMatrix.preScale(sx, sy);
mCircleMatrix.preTranslate(-mBitmapWidth/2, -mBitmapHeight/2);
canvas.drawBitmap(outerCircle, mCircleMatrix, mPaint);
canvas.drawBitmap(innerCircle, mCircleMatrix, mPaint);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState,
LockPatternUtils.patternToString(mPattern),
mPatternDisplayMode.ordinal(),
mInputEnabled, mInStealthMode, mEnableHapticFeedback);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setPattern(
DisplayMode.Correct,
LockPatternUtils.stringToPattern(ss.getSerializedPattern()));
mPatternDisplayMode = DisplayMode.values()[ss.getDisplayMode()];
mInputEnabled = ss.isInputEnabled();
mInStealthMode = ss.isInStealthMode();
mEnableHapticFeedback = ss.isTactileFeedbackEnabled();
}
/**
* The parecelable for saving and restoring a lock pattern view.
*/
private static class SavedState extends BaseSavedState {
private final String mSerializedPattern;
private final int mDisplayMode;
private final boolean mInputEnabled;
private final boolean mInStealthMode;
private final boolean mTactileFeedbackEnabled;
/**
* Constructor called from {@link LockPatternView#onSaveInstanceState()}
*/
private SavedState(Parcelable superState, String serializedPattern, int displayMode,
boolean inputEnabled, boolean inStealthMode, boolean tactileFeedbackEnabled) {
super(superState);
mSerializedPattern = serializedPattern;
mDisplayMode = displayMode;
mInputEnabled = inputEnabled;
mInStealthMode = inStealthMode;
mTactileFeedbackEnabled = tactileFeedbackEnabled;
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
mSerializedPattern = in.readString();
mDisplayMode = in.readInt();
mInputEnabled = (Boolean) in.readValue(null);
mInStealthMode = (Boolean) in.readValue(null);
mTactileFeedbackEnabled = (Boolean) in.readValue(null);
}
public String getSerializedPattern() {
return mSerializedPattern;
}
public int getDisplayMode() {
return mDisplayMode;
}
public boolean isInputEnabled() {
return mInputEnabled;
}
public boolean isInStealthMode() {
return mInStealthMode;
}
public boolean isTactileFeedbackEnabled(){
return mTactileFeedbackEnabled;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(mSerializedPattern);
dest.writeInt(mDisplayMode);
dest.writeValue(mInputEnabled);
dest.writeValue(mInStealthMode);
dest.writeValue(mTactileFeedbackEnabled);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
|
zzljob-android-lockpattern
|
resources/original source/LockPatternView.java
|
Java
|
asf20
| 41,812
|
package cat.model;
public class Budget {
private Integer id;
private Integer categoryID;
private String year;
private String month;
private String color75;
private String color90;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryID() {
return categoryID;
}
public void setCategoryID(Integer categoryID) {
this.categoryID = categoryID;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getColor75() {
return color75;
}
public void setColor75(String color75) {
this.color75 = color75;
}
public String getColor90() {
return color90;
}
public void setColor90(String color90) {
this.color90 = color90;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
}
|
zzuoqiang-
|
src/cat/model/Budget.java
|
Java
|
mit
| 1,096
|
package cat.model;
public class Overdraw {
private int id;
private long time;
private float money;
private String remark;
private String address;
private long returnTime;
private float returnMoney;
private String returnRemark;
private int completed;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getReturnTime() {
return returnTime;
}
public void setReturnTime(long returnTime) {
this.returnTime = returnTime;
}
public float getReturnMoney() {
return returnMoney;
}
public void setReturnMoney(float returnMoney) {
this.returnMoney = returnMoney;
}
public String getReturnRemark() {
return returnRemark;
}
public void setReturnRemark(String returnRemark) {
this.returnRemark = returnRemark;
}
public int getCompleted() {
return completed;
}
public void setCompleted(int completed) {
this.completed = completed;
}
}
|
zzuoqiang-
|
src/cat/model/Overdraw.java
|
Java
|
mit
| 1,458
|
package cat.model;
public class Category {
private Integer id;
private Integer parentID;
private String type;
private String name;
private Integer displayOrder;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentID() {
return parentID;
}
public void setParentID(Integer parentID) {
this.parentID = parentID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
}
|
zzuoqiang-
|
src/cat/model/Category.java
|
Java
|
mit
| 816
|
package cat.model;
public class Item {
private Integer id;
private String title;
private Long time;
private Float money;
private Integer categoryID;
private String remark;
private String user;
private String address;
private String categoryName;
private String parentCategoryName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
public Integer getCategoryID() {
return categoryID;
}
public void setCategoryID(Integer categoryID) {
this.categoryID = categoryID;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getParentCategoryName() {
return parentCategoryName;
}
public void setParentCategoryName(String parentCategoryName) {
this.parentCategoryName = parentCategoryName;
}
}
|
zzuoqiang-
|
src/cat/model/Item.java
|
Java
|
mit
| 1,646
|
package cat.model;
import java.util.Vector;
public class NavigatePage {
private int totalPage;
private int total;
private Vector<Vector> currentPageResult;
private Float totalIncome = 0f;
private Float totalExpenditure = 0f;
private Float totalBalance = 0f;
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public Vector<Vector> getCurrentPageResult() {
return currentPageResult;
}
public void setCurrentPageResult(Vector<Vector> currentPageResult) {
this.currentPageResult = currentPageResult;
}
public Float getTotalIncome() {
return totalIncome;
}
public void setTotalIncome(Float totalIncome) {
this.totalIncome = totalIncome;
}
public Float getTotalExpenditure() {
return totalExpenditure;
}
public void setTotalExpenditure(Float totalExpenditure) {
this.totalExpenditure = totalExpenditure;
}
public Float getTotalBalance() {
return totalBalance;
}
public void setTotalBalance(Float totalBalance) {
this.totalBalance = totalBalance;
}
}
|
zzuoqiang-
|
src/cat/model/NavigatePage.java
|
Java
|
mit
| 1,239
|
package cat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class RFClientOne implements DiscoveryListener {
public static void main(String args[]) throws BluetoothStateException {
LocalDevice localdev = null;
RFClientOne listener = new RFClientOne();
try {
localdev = LocalDevice.getLocalDevice();
} catch (BluetoothStateException e) {
System.out.println("ERROR: cannot access local device");
System.exit(1);
}
DiscoveryAgent agent = localdev.getDiscoveryAgent();
try {
// startInquiry() is non-blocking.
agent.startInquiry(DiscoveryAgent.GIAC, listener);
} catch (BluetoothStateException e) {
System.out.println("ERROR: device inquiry failed");
System.exit(2);
}
// pause for a while
// NOTE: if there is no remote device, this may go into infinite loop
// this program also shows that to start services from a client it's
// better to have a GUI interface.
while (remote == null)
try {
Thread.sleep(5000);
} catch (Exception e) {
}
UUID[] uuidSet = new UUID[1];
uuidSet[0] = new UUID("102030405060708090A0B0C0D0E0F011", false);
System.out.println("XXXXXXXXX " + remote);
int trans;
try {
trans = agent.searchServices(null, uuidSet, remote, listener);
System.out.println("XXXXXXXXX trans " + trans);
} catch (BluetoothStateException e) {
System.out.println("device unable to begin service inquiry");
}
}
// implement required listener methods.
private static RemoteDevice remote = null;
private static ServiceRecord first = null;
public void deviceDiscovered(RemoteDevice rt, DeviceClass cod) {
remote = rt;
System.out.println("A Remote Device Found:");
System.out.println("Address: " + rt.getBluetoothAddress());
try {
System.out.println(" Name: " + rt.getFriendlyName(true));
} catch (IOException e) {
}
}
public void inquiryCompleted(int distype) {
System.out.println("<<<<<<WWW");
if (distype == INQUIRY_TERMINATED)
System.out.println("Application Terminated");
else if (distype == INQUIRY_COMPLETED)
System.out.println("Inquiry Completed");
else
System.out.println("ERROR: Inquiry aborted");
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
first = servRecord[0];
System.out.println("<<<<<<<<<<< " + servRecord.length);
String url = first
.getConnectionURL(first.AUTHENTICATE_NOENCRYPT, false);
try {
StreamConnection conn = (StreamConnection) Connector.open(url);
String message = "What time is it now?";
InputStream is = conn.openInputStream();
OutputStream os = conn.openOutputStream();
byte[] rbuf = new byte[100];
os.write(message.getBytes());
is.read(rbuf);
System.out.println(new String(rbuf));
is.close();
os.close();
conn.close();
} catch (Exception e) {
System.out.println("ERROR: connection error");
}
}
public void serviceSearchCompleted(int transID, int respCode) {
System.out.println("<<<<<<WWWxxxxxxxx");
if (respCode == SERVICE_SEARCH_COMPLETED)
System.out.println("Services successfully located");
else if (respCode == SERVICE_SEARCH_TERMINATED)
System.out.println("Service inquiry was cancelled");
else if (respCode == SERVICE_SEARCH_DEVICE_NOT_REACHABLE)
System.out.println("Service connection cannot be established");
else if (respCode == SERVICE_SEARCH_NO_RECORDS)
System.out.println("No service found");
else
System.out.println("ERROR: service inquiry failed");
}
}
|
zzuoqiang-
|
src/cat/RFClientOne.java
|
Java
|
mit
| 4,001
|
package cat;
import java.awt.Component;
import net.sf.nachocalendar.components.DateField;
import net.sf.nachocalendar.components.DefaultHeaderRenderer;
import net.sf.nachocalendar.components.HeaderPanel;
import net.sf.nachocalendar.components.HeaderRenderer;
public class DateField2
extends DateField
{
// DateField datefield;
public DateField2()
{
// datefield = CalendarFactory.createDateField();
this.setHeaderRenderer(new HeaderRenderer()
{
public Component getHeaderRenderer(HeaderPanel panel, Object value, boolean isHeader, boolean isWorking)
{
DefaultHeaderRenderer render = new DefaultHeaderRenderer();
String header = value.toString();
render.setText(header.substring(header.length() - 1, header.length()));
return render;
}
});
this.setDateFormat(Configure.dateFormat);
}
}
|
zzuoqiang-
|
src/cat/DateField2.java
|
Java
|
mit
| 907
|
#include <windows.h>
#include <jni.h>
#define PATH_SEPARATOR ';' /* define it to be ':' on Solaris */
#define USER_CLASSPATH "core.jar;dependencies/nachocalendar-0.23.jar;dependencies/jcommon-1.0.16.jar;dependencies/jfreechart-1.0.13.jar;dependencies/poi-3.7-20101029.jar;dependencies/sqlitejdbc-v056.jar"
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jclass stringClass;
jobjectArray args;
#ifdef JNI_VERSION_1_2
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString =
"-Djava.class.path=" USER_CLASSPATH;
vm_args.version = 0x00010002;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
#else
JDK1_1InitArgs vm_args;
char classpath[1024];
vm_args.version = 0x00010001;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
/* Append USER_CLASSPATH to the default system class path */
sprintf(classpath, "%s%c%s",
vm_args.classpath, PATH_SEPARATOR, USER_CLASSPATH);
vm_args.classpath = classpath;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
#endif /* JNI_VERSION_1_2 */
if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
exit(1);
}
cls = (*env)->FindClass(env, "cat/AccountPanel");
if (cls == NULL) {
goto destroy;
}
mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
if (mid == NULL) {
goto destroy;
}
/*jstr = (*env)->NewStringUTF(env, " from C!");
if (jstr == NULL) {
goto destroy;
}
stringClass = (*env)->FindClass(env, "java/lang/String");
args = (*env)->NewObjectArray(env, 1, stringClass, jstr);
if (args == NULL) {
goto destroy;
}*/
(*env)->CallStaticVoidMethod(env, cls, mid, NULL);
destroy:
if ((*env)->ExceptionOccurred(env)) {
(*env)->ExceptionDescribe(env);
}
(*jvm)->DestroyJavaVM(jvm);
}
|
zzuoqiang-
|
wrap/vc/wrapper.c
|
C
|
mit
| 2,306
|
all:
cd vc && nmake deploy
clean:
cd vc && nmake clean
|
zzuoqiang-
|
wrap/Makefile
|
Makefile
|
mit
| 65
|
#include <stdlib.h>
#include <stdio.h>
int main(){
// puts("hello java");
system("start javaw -jar core.jar");
return 0;
}
|
zzuoqiang-
|
wrap/gcc/wrapper.c
|
C
|
mit
| 135
|
package backup;
import cat.DateField2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
public class DateCellEditor extends AbstractCellEditor implements
TableCellEditor {
Logger log = Logger.getLogger("DateCellEditor");
DateField2 field;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
public DateCellEditor() {
field = new DateField2();
field.setDateFormat(sf);
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
Date date = (Date) field.getValue();
try {
date = sf.parse((String) value);
} catch (ParseException e) {
e.printStackTrace();
}
field.setValue(date);
return field;
}
public Object getCellEditorValue() {
return sf.format(field.getValue());
}
}
|
zzuoqiang-
|
old/backup/DateCellEditor.java
|
Java
|
mit
| 1,043
|
import texture.TexturePacket;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
public class RockMan extends Actor {
Vector2 position = new Vector2();
Vector2 accleration = new Vector2();
Vector2 velocity = new Vector2();
Rectangle bound = new Rectangle();
final int WIDTH = 10;
final int HEIGHT = 10;
Animation atk;
public enum state {
IDLE, RUN, ATK, DIE
}
public RockMan(Vector2 pos) {
position = pos;
bound.width = WIDTH;
bound.height = HEIGHT;
// atk = new Animation(0.2f, TexturePacket.getInstance().getRegions("f1"));
}
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
ShapeRenderer shapeRenderer = new ShapeRenderer();
shapeRenderer.begin(ShapeType.Rectangle);
shapeRenderer.setColor(Color.CYAN);
shapeRenderer.rect(50, 50, 100, 100);
shapeRenderer.end();
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/RockMan.java
|
Java
|
art
| 1,198
|
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
public class GameScreen implements Screen {
World world;
WorldRender worldRender;
@Override
public void dispose() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void render(float arg0) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
worldRender.render(arg0);
}
@Override
public void resize(int arg0, int arg1) {
}
@Override
public void resume() {
}
@Override
public void show() {
world = new World();
worldRender = new WorldRender(world);
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/GameScreen.java
|
Java
|
art
| 671
|
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
public class World extends Group {
public RockMan rockMan;
public World() {
rockMan = new RockMan(new Vector2(1, 1));
addActor(rockMan);
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/World.java
|
Java
|
art
| 245
|
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = "Rock Man";
cfg.useGL20 = false;
cfg.width = 800;
cfg.height = 480;
new LwjglApplication(new MyGame(), cfg);
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/Main.java
|
Java
|
art
| 447
|
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class FlashScreen implements Screen {
MyGame myGame;
Texture textureBg;
SpriteBatch spriteBatch;
public FlashScreen(MyGame myGame) {
this.myGame = myGame;
}
@Override
public void dispose() {
textureBg = null;
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void render(float arg0) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
spriteBatch.draw(textureBg, 0, 0);
spriteBatch.end();
if (Gdx.input.isTouched()) {
myGame.setScreen(new GameScreen());
}
}
@Override
public void resize(int arg0, int arg1) {
}
@Override
public void resume() {
}
@Override
public void show() {
textureBg = new Texture(Gdx.files.internal("res/28105041-snsd6.jpg"));
spriteBatch = new SpriteBatch();
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/FlashScreen.java
|
Java
|
art
| 1,056
|
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
public class MyGame extends com.badlogic.gdx.Game {
FlashScreen flashScreen;
public static int WIDTH;
public static int HEIGHT;
@Override
public void create() {
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
flashScreen = new FlashScreen(this);
Texture.setEnforcePotImages(false);
setScreen(flashScreen);
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/MyGame.java
|
Java
|
art
| 438
|
package texture;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class TexturePacket {
public TextureAtlas atlas;
static TexturePacket self;
public static TexturePacket getInstance() {
if (self != null) {
return self;
}
return new TexturePacket();
}
public TexturePacket() {
atlas = new TextureAtlas(Gdx.files.internal("res/pack"));
self = this;
// List<> regions = (List<AtlasRegion>) atlas.findRegion("f1");
// List<TextureRegion> regions = (List<TextureRegion>) atlas
// .findRegion("f1");
}
public TextureRegion[] getRegions(String fname) {
List<TextureRegion> regions = (List<TextureRegion>) atlas.findRegion("f1");
return (TextureRegion[]) regions.toArray();
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/texture/TexturePacket.java
|
Java
|
art
| 852
|
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class WorldRender {
World world;
ShapeRenderer shapeRenderer;
Stage stage;
public WorldRender(World w) {
stage = new Stage();
this.world = w;
stage.addActor(world);
shapeRenderer = new ShapeRenderer();
}
public void render(float delta) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act();
// shapeRenderer.begin(ShapeType.Rectangle);
// Rectangle r = world.rockMan.bound;
// shapeRenderer.setColor(new Color(0, 1, 0, 1));
// float _x = world.rockMan.position.x;
// float _y = world.rockMan.position.y;
// shapeRenderer.rect(_x, _y, r.width, r.height);
// shapeRenderer.end();
}
}
|
zzzzzzzzzzzzzzzzz
|
trunk/src/WorldRender.java
|
Java
|
art
| 826
|
// JavaScript Document
var UU = new Array(0, 0, 1, -1);
var VV = new Array(1, -1, 0, 0);
function getRandom(n) {
return Math.round(Math.random() * (n - 1));
}
function newArray(col) {
var a = new Array;
for (var i = 0; i < col; i++)
a[i] = new Array;
return a;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Rectangle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
function getNewMatrix() {
var a = newArray(18);
var i, j, k, t, remain, key;
var stop;
for (i = 0; i < 18; i++)
for (j = 0; j < 11; j++) a[i][j] = 0;
remain = 144;
for (k = 1; k <= 36; k++) {
for (t = 1; t <= 4; t++) {
key = getRandom(remain--) + 1;
stop = false;
for (i = 1; i <= 16; i++) {
if (stop)
break;
else
for (j = 1; j <= 9; j++)
if (a[i][j] == 0) {
key--;
if (key == 0) {
stop = true;
a[i][j] = k;
break;
}
}
}
}
}
return a;
}
function checkPath(a, i1, j1, i2, j2) {
if (i1 == i2 && j1 == j2) return null;
if (a[i1][j1] == 0 || a[i2][j2] == 0) return null;
if (a[i1][j1] != a[i2][j2]) return null;
var fist, last, i, j, t;
var queue = new Array;
var dad = newArray(18);
var count = newArray(18);
for (i = 0; i < 198; i++) queue[i] = new Point(0, 0);
fist = 0; last = 0;
queue[0].x = i1;
queue[0].y = j1;
for (i = 0; i < 18; i++)
for (j = 0; j < 11; j++) dad[i][j] = new Point(-1, -1);
dad[i1][j1].x = -2;
count[i1][j1] = 0;
var canGo = new Array;
var p = new Array;
var q = new Array;
while (fist <= last) {
i = queue[fist].x;
j = queue[fist].y;
fist++;
for (t = 0; t < 4; t++) {
canGo[t] = true;
p[t] = i;
q[t] = j;
}
do {
for (t = 0; t < 4; t++)
if (canGo[t]) {
p[t] += UU[t];
q[t] += VV[t];
if (!myInside(p[t], q[t])) {
canGo[t] = false;
continue;
}
if (p[t] == i2 && q[t] == j2) {
dad[p[t]][q[t]].x = i;
dad[p[t]][q[t]].y = j;
return createArrayList(dad, i2, j2);
}
if (a[p[t]][q[t]] > 0) {
canGo[t] = false;
continue;
}
if (dad[p[t]][q[t]].x != -1) continue;
if (count[i][j] == 2) continue;
last++;
queue[last].x = p[t];
queue[last].y = q[t];
dad[p[t]][q[t]].x = i;
dad[p[t]][q[t]].y = j;
count[p[t]][q[t]] = count[i][j] + 1;
}
} while (canGo[0] || canGo[1] || canGo[2] || canGo[3]);
}
return null;
}
function myInside(i, j) {
return i >= 0 && i < 18 && j >= 0 && j < 11;
}
function createArrayList(dad, i, j) {
arrayList = new Array;
var p, q;
do {
arrayList.push(new Point(i, j));
p = dad[i][j].x;
q = dad[i][j].y;
i = p;
j = q;
} while (i != -2);
return arrayList;
}
function isEnd(a) {
var i, j;
for (i = 1; i <= 16; i++)
for (j = 1; j <= 9; j++)
if (a[i][j] > 0)
if (findTwin(a, i, j) != null)
return false;
return true;
}
function findTwin(a, i1, j1) {
var fist, last, i, j, t;
var queue = new Array;
var cx = newArray(18);
var count = newArray(18);
for (i = 0; i < 198; i++) queue[i] = new Point();
fist = 0; last = 0;
queue[0].x = i1;
queue[0].y = j1;
for (i = 0; i < 18; i++)
for (j = 0; j < 11; j++) cx[i][j] = true;
cx[i1][j1] = false;
count[i1][j1] = 0;
var canGo = new Array;
var p = new Array;
var q = new Array;
while (fist <= last) {
i = queue[fist].x;
j = queue[fist].y;
fist++;
for (t = 0; t < 4; t++) {
canGo[t] = true;
p[t] = i;
q[t] = j;
}
do {
for (t = 0; t < 4; t++)
if (canGo[t]) {
p[t] += UU[t];
q[t] += VV[t];
if (!myInside(p[t], q[t])) {
canGo[t] = false;
continue;
}
if (a[p[t]][q[t]] == a[i1][j1] && cx[p[t]][q[t]])
return new Point(p[t], q[t]);
if (a[p[t]][q[t]] > 0) {
canGo[t] = false;
continue;
}
if (!cx[p[t]][q[t]]) continue;
if (count[i][j] == 2) continue;
last++;
queue[last].x = p[t];
queue[last].y = q[t];
cx[p[t]][q[t]] = false;
count[p[t]][q[t]] = count[i][j] + 1;
}
} while (canGo[0] || canGo[1] || canGo[2] || canGo[3]);
}
return null;
}
function findCheat(a) {
var i, j;
var b = new Array;
var c = new Array;
var k = 0;
for (i = 1; i <= 16; i++)
for (j = 1; j <= 9; j++)
if (a[i][j] > 0) {
b[k] = i;
c[k] = j;
k++;
}
mixArray2(b, c, k);
for (i = 0; i < k - 1; i++)
for (j = k - 1; j > i; j--)
if (checkPath(a, b[i], c[i], b[j], c[j]) != null)
return new Rectangle(b[i], c[i], b[j], c[j]);
return null;
}
function repairMatrix(a) {
var b = new Array;
var i, j, k = 0;
for (i = 1; i <= 16; i++)
for (j = 1; j <= 9; j++)
if (a[i][j] > 0) b[k++] = a[i][j];
mixArray(b, k);
k = 0;
for (i = 1; i <= 16; i++)
for (j = 1; j <= 9; j++)
if (a[i][j] > 0) a[i][j] = b[k++];
var tmp = newArray(18);
for (i = 0; i < 18; i++)
for (j = 0; j < 11; j++) tmp[i][j] = a[i][j] > 0 ? 1 : 0;
var rect = findCheat(tmp);
var k = 0;
var u = 0, v = 0;
for (i = 1; i <= 16; i++)
if (k > 0) break;
else
for (j = 1; j <= 9; j++)
if (i != rect.x || j != rect.y)
if (a[i][j] == a[rect.x][rect.y]) {
u = i;
v = j;
k = 1;
break;
}
swap(a, rect.width, rect.height, u, v);
}
function fixMatrix(a, fixType) {
if (fixType == 1) return;
if (fixType == 2) {
fixZone(a, 1, 1, 16, 9, 0);
} else if (fixType == 3) {
fixZone(a, 1, 1, 16, 9, 1);
} else if (fixType == 4) {
fixZone(a, 1, 1, 16, 9, 3);
} else if (fixType == 5) {
fixZone(a, 1, 1, 16, 9, 2);
} else if (fixType == 6) {
fixZone(a, 1, 5, 16, 9, 0);
fixZone(a, 1, 1, 16, 4, 1);
} else if (fixType == 7) {
fixZone(a, 1, 5, 16, 9, 1);
fixZone(a, 1, 1, 16, 4, 0);
} else if (fixType == 8) {
fixZone(a, 1, 1, 8, 9, 3);
fixZone(a, 9, 1, 16, 9, 2);
} else {
fixZone(a, 1, 1, 8, 9, 2);
fixZone(a, 9, 1, 16, 9, 3);
}
}
function fixZone(a, i1, j1, i2, j2, vector) {
var i, j, p, q;
var stop;
do {
stop = true;
for (i = i1; i <= i2; i++)
for (j = j1; j <= j2; j++)
if (a[i][j] > 0) {
p = i + UU[vector];
q = j + VV[vector];
if (p >= 1 && p <= 16 && q >= 1 && q <= 9) {
if (a[p][q] == 0) {
swap(a, i, j, p, q);
stop = false;
}
}
}
} while (!stop);
}
function swap(a, i1, j1, i2, j2) {
var tmp = a[i1][j1];
a[i1][j1] = a[i2][j2];
a[i2][j2] = tmp;
}
function generateHV(n) {
var a = new Array;
var i, j, k, t;
for (i = 0; i < n; i++) a[i] = n;
j = n;
for (i = 0; i < n; i++) {
k = getRandom(j--) + 1;
t = 0;
while (k > 0) {
if (a[t++] == n) k--;
}
a[t - 1] = i;
}
return a;
}
function mixArray(a, n) {
var b = generateHV(n);
var c = new Array;
for (var i = 0; i < n; i++)
c[i] = a[b[i]];
for (var i = 0; i < n; i++)
a[i] = c[i];
}
function mixArray2(a, aa, n) {
var b = generateHV(n);
var c = new Array;
var i;
for (i = 0; i < n; i++)
c[i] = a[b[i]];
for (i = 0; i < n; i++)
a[i] = c[i];
for (i = 0; i < n; i++)
c[i] = aa[b[i]];
for (i = 0; i < n; i++)
aa[i] = c[i];
}
|
zzzzzzzzzzzzzzzzz
|
trunk/Algorithms.js
|
JavaScript
|
art
| 7,035
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define _GNU_SOURCE
#include <getopt.h>
#include "common.h"
#define PORT 42380
#define BUF_SIZE 256
#define SCREENSHOT_CMD "SCREEN"
#ifdef DEBUG
FILE* logFile;
#endif
inline void Log(const char* msg)
{
#ifdef DEBUG
if (errno != 0 && logFile == stderr)
{
char buf[BUF_SIZE];
snprintf (buf, BUF_SIZE, "%s (errno=%d)", msg, errno);
perror (buf);
exit (1);
}
else fprintf(logFile, "%s\n", msg);
fflush (logFile);
#endif
}
volatile sig_atomic_t end = 0;
void sig_INT(int sig) { fprintf(logFile, "------ Caught signal %d -----\n", sig); if (sig == SIGINT || sig == SIGSEGV) end = 1; }
ssize_t Receive(int sfd, char* buf, size_t count, int flags)
{
int c;
size_t len = 0;
do
{
c = recv(sfd, buf, count, flags);
if (c < 0) return c;
if (c == 0) return len;
buf += c;
len += c;
count -= c;
} while (count > 0);
return len;
}
ssize_t Send(int sfd, const char* buf, ssize_t count, int flags)
{
int c;
size_t len = 0;
do
{
c = send(sfd, buf, count, flags);
if (c < 0) return c;
buf += c;
len += c;
count -= c;
//#ifdef DEBUG
// char msg[BUF_SIZE];
// snprintf (msg, BUF_SIZE, "-- Sent %d bytes (%d total, %d remaining)", c, len, count);
// Log (msg);
//#endif
} while (count > 0);
return len;
}
int start_server()
{
Log("Starting server...");
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) return -1;
Log("- Socket creation");
struct sockaddr_in sin;
sin.sin_family = PF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind (sfd, (struct sockaddr*)&sin, sizeof(struct sockaddr_in)) < 0)
return -1;
Log("- Socket binding");
if (listen (sfd, 5) < 0) return -1;
Log ("- Socket in listening mode");
struct linger l = { 0, 0 };
if (setsockopt(sfd, SOL_SOCKET, SO_LINGER, (const void*)&l, sizeof(struct linger)) < 0)
return -1;
Log("Server started.");
// get local address and display it
#if DEBUG
socklen_t sin_len = sizeof(struct sockaddr_in);
getsockname (sfd, (struct sockaddr*)&sin, &sin_len);
char msg[BUF_SIZE];
snprintf (msg, BUF_SIZE, "Listening on %s:%d", inet_ntoa(sin.sin_addr), PORT);
Log (msg);
#endif
return sfd;
}
int setup_signals()
{
Log("Signal handling setup");
struct sigaction sa;
// // handle SIGINT
// sa.sa_handler = sig_INT;
// sigemptyset (&sa.sa_mask);
// sa.sa_flags = 0;
// if (sigaction(SIGINT, &sa, NULL) < 0) return -1;
//
// // ignore SIGHUP
// sa.sa_handler = SIG_IGN;
// sigemptyset (&sa.sa_mask);
// sa.sa_flags = 0;
// if (sigaction(SIGHUP, &sa, NULL) < 0) return -1;
int i;
for (i = 1; i < 30; ++i) {
sa.sa_handler = sig_INT;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sigaction(i, &sa, NULL);
}
errno = 0;
return 0;
}
int accept_client(int servfd, int** client_fd, int* client_count)
{
Log ("Incoming client connection");
int cfd = accept(servfd, NULL, NULL);
if (cfd < 0) return -1;
Log ("- Connection accepted");
/* check whether the client comes from local system; detach if not */
struct sockaddr_in client_addr;
socklen_t ca_len = sizeof(struct sockaddr_in);
if (getpeername(cfd, (struct sockaddr*)&client_addr, &ca_len) < 0) return -1;
if (strcmp(inet_ntoa(client_addr.sin_addr), "127.0.0.1") != 0) {
Log ("- Remote client detected -- closing connection.");
shutdown (cfd, SHUT_RDWR);
close (cfd);
return 0;
}
*client_fd = (int*)realloc(*client_fd, sizeof(int) * (*client_count + 1));
(*client_fd)[(*client_count)++] = cfd; // (*client_fd)[...] != *client_fd[...] -- f'kin precedence ;/
return cfd;
}
int handle_client_input(int cfd, char* fddev)
{
Log ("Client socket signaled for input");
struct picture pict;
char buf[BUF_SIZE];
int c;
/* read input and parse it */
Log ("- Retreiving data");
c = Receive(cfd, buf, strlen(SCREENSHOT_CMD), 0);
if (c == 0 || (c < 0 && errno == EINTR)) return 0;
if (c < 0) return -1;
if (c >= strlen(SCREENSHOT_CMD) && (buf[strlen(SCREENSHOT_CMD)] = '\0', strcmp(buf, SCREENSHOT_CMD) == 0))
{
Log ("- Command identified as " SCREENSHOT_CMD);
/* screenshot command read; take screenshot and post it through socket */
Log ("- Taking screenshot");
if (TakeScreenshot(fddev, &pict) < 0) return -1;
Log ("- Screenshot taken");
/* header: width height BPP */
memset (buf, 0, BUF_SIZE * sizeof(char));
snprintf (buf, BUF_SIZE, "%d %d %d", pict.xres, pict.yres, pict.bps);
if (Send(cfd, buf, (strlen(buf) + 1) * sizeof(char), 0) < 0) /* incl. \0 */
return -1;
Log (buf);
Log ("- Response header sent.");
/* content */
if (Send(cfd, pict.buffer, pict.xres * pict.yres * pict.bps / 8, 0) < 0)
return -1;
Log ("- Screenshot sent");
}
return c;
}
int cleanup(int servfd, int* client_fd, int client_count)
{
Log ("Shutdown");
int i;
for (i = 0; i < client_count; ++i)
if (close(client_fd[i]) < 0) return -1;
free (client_fd);
Log ("- Closing server socket");
if (close(servfd) < 0) return -1;
Log ("Shutdown complete");
#ifdef DEBUG
if (logFile != stderr) fclose (logFile);
#endif
return 0;
}
int do_work(int servfd, char* fbDevice)
{
int* client_fd = NULL;
int client_count = 0;
int max_fd;
fd_set readfs;
int i, c;
Log ("Starting main loop.");
while (!end)
{
/* fill fd_set to check sockets for reading (client and server ones) */
Log ("<< select() on sockets... >>");
FD_ZERO(&readfs); max_fd = 0;
FD_SET(servfd, &readfs);
if (servfd > max_fd) max_fd = servfd;
for (i = 0; i < client_count; ++i)
{
if (client_fd[i] < 0) continue;
FD_SET (client_fd[i], &readfs);
if (client_fd[i] > max_fd) max_fd = client_fd[i];
}
if (select(max_fd + 1, &readfs, NULL, NULL, NULL) == -1)
{
if (errno == EINTR) { errno = 0; continue; }
return -1;
}
/* check for input on client socket and handle it */
for (i = 0; i < client_count; ++i)
{
if (client_fd[i] < 0) continue;
if (FD_ISSET(client_fd[i], &readfs))
{
c = handle_client_input (client_fd[i], fbDevice);
if (c < 0 && errno != EPIPE && errno!= ECONNRESET) return -1;
/* connection finished */
close (client_fd[i]);
client_fd[i] = -1; // no socket
}
}
/* check whether we have incoming connection */
if (FD_ISSET(servfd, &readfs))
if (accept_client (servfd, &client_fd, &client_count) < 0)
return -1;
}
Log ("- Caught SIGINT");
return cleanup(servfd, client_fd, client_count);
}
int main(int argc, char* argv [])
{
#ifdef DEBUG
// optional logging to file
if (argc >= 2) {
logFile = fopen(argv[1], "a+");
}
else
logFile = stderr;
#endif
Log ("Program initialized");
char* device;
device = "/dev/graphics/fb0";
int server_socket = start_server();
if (server_socket < 0)
Log ("Error while starting server");
if (setup_signals() < 0)
Log ("Error while setting up signals");
// Log ("Going into background -- have nice day.");
// if (setsid () < 0) Log("Error while going into background");
if (do_work (server_socket, device) < 0)
Log ("Error in main loop");
}
|
zzou-screenshot
|
native/main.c
|
C
|
bsd
| 7,145
|
/*
* fbshot.c -- FrameBuffer Screen Capture Utility
* (C)opyright 2002 sfires@sfires.net
*
* Originally Written by: Stephan Beyer <PH-Linex@gmx.net>
* Further changes by: Paul Mundt <lethal@chaoticdreams.org>
* Rewriten and maintained by: Dariusz Swiderski <sfires@sfires.net>
* Modular version by: Karol Kuczmarski <karol.kuczmarski@polidea.pl>
*
* This is a simple program that generates a
* screenshot of the specified framebuffer device and
* terminal and writes it to a specified file using
* the PNG format.
*
* See ChangeLog for modifications, CREDITS for credits.
*
* fbshot 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.
*
* fbshot 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 with fbshot; if not, please write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <fcntl.h>
#include <byteswap.h>
#include <sys/types.h>
#include <asm/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <mntent.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/vt.h>
#include <linux/fb.h>
#include "common.h"
#define DEFAULT_FB "/dev/fb0"
#define PACKAGE "fbshot"
#define VERSION "0.3.1"
#define MAINTAINER_NAME "Dariusz Swiderski"
#define MAINTAINER_ADDR "sfires@sfires.net"
static int waitbfg=0; /* wait before grabbing (for -C )... */
/* some conversion macros */
#define RED565(x) ((((x) >> (11 )) & 0x1f) << 3)
#define GREEN565(x) ((((x) >> (5 )) & 0x3f) << 2)
#define BLUE565(x) ((((x) >> (0)) & 0x1f) << 3)
#define ALPHA1555(x) ((((x) >> (15)) & 0x1 ) << 0)
#define RED1555(x) ((((x) >> (10)) & 0x1f) << 3)
#define GREEN1555(x) ((((x) >> (5 )) & 0x1f) << 3)
#define BLUE1555(x) ((((x) >> (0 )) & 0x1f) << 3)
void FatalError(char* err){
fprintf(stderr,"An error occured: %s %s\nExiting now...\n",err,strerror(errno));
fflush(stderr);
exit (1);
}
void Usage(char *binary){
printf("Usage: %s [-ghi] [-{C|c} vt] [-d dev] [-s n] filename.png\n", binary);
}
void Help(char *binary){
printf("FBShot - makes screenshots from framebuffer, v%s\n", VERSION);
printf("\t\tby Dariusz Swiderski <sfires@sfires.net>\n\n");
Usage(binary);
printf("\nPossible options:\n");
printf("\t-C n \tgrab from console n, for slower framebuffers\n");
printf("\t-c n \tgrab from console n\n");
printf("\t-d dev\tuse framebuffer device dev instead of default\n");
/* not supported as for now
printf("\t-g \tsave a grayscaled PNG\n");
*/
printf("\t-h \tprint this usage information\n");
printf("\t-i \tturns OFF interlacing\n");
printf("\t-s n \tsleep n seconds before making screenshot\n");
printf("\nSend feedback !!!\n");
}
void chvt(int num){
int fd;
if(!(fd = open("/dev/console", O_RDWR)))
FatalError("cannot open /dev/console");
if (ioctl(fd, VT_ACTIVATE, num))
FatalError("ioctl VT_ACTIVATE ");
if (ioctl(fd, VT_WAITACTIVE, num))
FatalError("ioctl VT_WAITACTIVE");
close(fd);
if (waitbfg)
sleep (3);
}
unsigned int create_bitmask(struct fb_bitfield* bf) {
return ~(~0u << bf->length) << bf->offset;
}
// Unifies the picture's pixel format to be 32-bit ARGB
void unify(struct picture *pict, struct fb_var_screeninfo *fb_varinfo) {
__u32 red_mask, green_mask, blue_mask;
__u32 c;
__u32 r, g, b;
__u32* out;
int i, j = 0, bytes_pp;
// build masks for extracting colour bits
red_mask = create_bitmask(&fb_varinfo->red);
green_mask = create_bitmask(&fb_varinfo->green);
blue_mask = create_bitmask(&fb_varinfo->blue);
// go through the image and put the bits in place
out = (__u32*)malloc(pict->xres * pict->yres * sizeof(__u32));
bytes_pp = pict->bps >> 3;
for (i = 0; i < pict->xres * pict->yres * bytes_pp; i += bytes_pp) {
memcpy (((char*)&c) + (sizeof(__u32) - bytes_pp), pict->buffer + i, bytes_pp);
// get the colors
r = ((c & red_mask) >> fb_varinfo->red.offset) & ~(~0u << fb_varinfo->red.length);
g = ((c & green_mask) >> fb_varinfo->green.offset) & ~(~0u << fb_varinfo->green.length);
b = ((c & blue_mask) >> fb_varinfo->blue.offset) & ~(~0u << fb_varinfo->blue.length);
// format the new pixel
out[j++] = (0xFF << 24) | (b << 16) | (g << 8) | r;
}
pict->buffer = (char*)out;
pict->bps = 32;
}
int read_fb(char *device, int vt_num, struct picture *pict){
int fd, vt_old, i,j;
struct fb_fix_screeninfo fb_fixinfo;
struct fb_var_screeninfo fb_varinfo;
struct vt_stat vt_info;
if (vt_num!=-1){
if ((fd = open("/dev/console", O_RDONLY)) == -1)
FatalError("could not open /dev/console");
if (ioctl(fd, VT_GETSTATE, &vt_info))
FatalError("ioctl VT_GETSTATE");
close (fd);
vt_old=vt_info.v_active;
}
if(!(fd=open(device, O_RDONLY)))
FatalError("Couldn't open framebuffer device");
if (ioctl(fd, FBIOGET_FSCREENINFO, &fb_fixinfo))
FatalError("ioctl FBIOGET_FSCREENINFO");
if (ioctl(fd, FBIOGET_VSCREENINFO, &fb_varinfo))
FatalError("ioctl FBIOGET_VSCREENINFO");
pict->xres=fb_varinfo.xres;
pict->yres=fb_varinfo.yres;
pict->bps=fb_varinfo.bits_per_pixel;
pict->gray=fb_varinfo.grayscale;
if(fb_fixinfo.visual==FB_VISUAL_PSEUDOCOLOR){
pict->colormap=(struct fb_cmap*)malloc(sizeof(struct fb_cmap));
pict->colormap->red=(__u16*)malloc(sizeof(__u16)*(1<<pict->bps));
pict->colormap->green=(__u16*)malloc(sizeof(__u16)*(1<<pict->bps));
pict->colormap->blue=(__u16*)malloc(sizeof(__u16)*(1<<pict->bps));
pict->colormap->transp=(__u16*)malloc(sizeof(__u16)*(1<<pict->bps));
pict->colormap->start=0;
pict->colormap->len=1<<pict->bps;
if (ioctl(fd, FBIOGETCMAP, pict->colormap))
FatalError("ioctl FBIOGETCMAP");
}
if (vt_num!=-1)
chvt(vt_old);
switch(pict->bps){
case 15:
i=2;
break;
default:
i=pict->bps>>3;
}
if(!(pict->buffer=malloc(pict->xres*pict->yres*i)))
FatalError("couldnt malloc");
// fprintf(stdout, "Framebuffer %s is %i bytes.\n", device,
// (fb_varinfo.xres * fb_varinfo.yres * i));
// fprintf(stdout, "Grabbing %ix%i ... \n", fb_varinfo.xres, fb_varinfo.yres);
//
//#ifdef DEBUG
///* Output some more information bout actual graphics mode
// */
// fprintf(stdout, "%ix%i [%i,%i] %ibps %igr\n",
// fb_varinfo.xres_virtual, fb_varinfo.yres_virtual,
// fb_varinfo.xoffset, fb_varinfo.yoffset,
// fb_varinfo.bits_per_pixel, fb_varinfo.grayscale);
// fprintf(stdout, "FIX: card:%s mem:0x%.8X mem_len:%d visual:%i type:%i type_aux:%i line_len:%i accel:%i\n",
// fb_fixinfo.id,fb_fixinfo.smem_start,fb_fixinfo.smem_len,fb_fixinfo.visual,
// fb_fixinfo.type,fb_fixinfo.type_aux,fb_fixinfo.line_length,fb_fixinfo.accel);
//#endif
fflush(stdout);
if (vt_num!=-1)
chvt(vt_num);
j= (read(fd, pict->buffer, ((pict->xres * pict->yres) * i) )!=
(pict->xres * pict->yres *i ));
//#ifdef DEBUG
// printf("to read:%i read:%i\n",(pict->xres* pict->yres * i), j);
//#endif
if (vt_num!=-1)
chvt(vt_old);
// if(j)
// FatalError("couldn't read the framebuffer");
// else
// fprintf(stdout,"done.\n");
close (fd);
unify(pict, &fb_varinfo);
return 0;
}
void convert8to32(struct picture *pict){
int i;
int j=0;
__u8 c;
char *out=(char*)malloc(pict->xres*pict->yres*4);
for (i=0; i<pict->xres*pict->yres; i++)
{
c = ((__u8*)(pict->buffer))[i];
out[j++]=(char)(pict->colormap->red[c]);
out[j++]=(char)(pict->colormap->green[c]);
out[j++]=(char)(pict->colormap->blue[c]);
out[j++]=(char)(pict->colormap->transp[c]);
}
free(pict->buffer);
pict->buffer=out;
}
void convert1555to32(struct picture *pict){
int i;
int j=0;
__u16 t,c;
char *out=(char*)malloc(pict->xres*pict->yres*4);
for (i=0; i<pict->xres*pict->yres; i++)
{
c = ( (__u16*)(pict->buffer))[i];
out[j++]=(char)RED1555(c);
out[j++]=(char)GREEN1555(c);
out[j++]=(char)BLUE1555(c);
out[j++]=(char)ALPHA1555(c);
}
free(pict->buffer);
pict->buffer=out;
}
void convert565to32(struct picture *pict){ // ARGB_8888
int i;
int j=0;
__u16 t,c;
char *out=(char*)malloc(pict->xres*pict->yres*4);
for (i=0; i<pict->xres*pict->yres; i++)
{
c = ( (__u16*)(pict->buffer))[i];
out[j++]=(char)0xff;
out[j++]=(char)RED565(c);
out[j++]=(char)GREEN565(c);
out[j++]=(char)BLUE565(c);
}
free(pict->buffer);
pict->buffer=out;
}
static int Write(int fd, char* buf, int c)
{
int i = 0, r;
while (i < c)
{
r = write(fd, (const void*)(buf + i), c - i);
i += r;
}
return i;
}
#if 0
static int Write_RAW(struct picture* pict, char* filename)
{
int fd = open(filename, O_CREAT | O_WRONLY | O_SYNC, 0777);
if (fd < 0) return -1;
// convert picture to 32-bit format
printf ("BPS: %d\n", pict->bps);
switch (pict->bps)
{
case 8:
convert8to32 (pict);
break;
case 15:
convert1555to32 (pict);
break;
case 16:
convert565to32 (pict);
break;
case 32:
break;
default:
return -1;
}
Write (fd, pict->buffer, pict->xres*pict->yres*4);
close (fd);
return 0;
}
#endif
static char optstring[] = "hiC:c:d:s:";
static struct option long_options[] = {
{"slowcon", 1, 0, 'C'},
{"console", 1, 0, 'c'},
{"device", 1, 0, 'd'},
{"help", 0, 0, 'h'},
{"noint", 0, 0, 'i'},
{"sleep", 1, 0, 's'},
{0, 0, 0, 0}
};
int TakeScreenshot (char* device, struct picture* pict)
{
int vt_num = -1;
return read_fb(device, vt_num, pict);
}
|
zzou-screenshot
|
native/fbshot.c
|
C
|
bsd
| 9,985
|
#ifndef COMMON_H
#define COMMON_H
struct picture{
int xres,yres;
char *buffer;
struct fb_cmap *colormap;
char bps,gray;
};
int TakeScreenshot (char* device, struct picture* pict);
#endif
|
zzou-screenshot
|
native/common.h
|
C
|
bsd
| 198
|
@ set GCC=arm-none-linux-gnueabi-gcc.exe
@ set C_FLAGS=-DDEBUG
@ set ADB=C:\Android\tools\adb.exe
@echo Compiling...
@ %GCC% %C_FLAGS% -c main.c -o main.o
@if not ERRORLEVEL 0 goto Error
@ %GCC% %C_FLAGS% -c fbshot.c -o fbshot.o
@if not ERRORLEVEL 0 goto Error
@echo Linking...
@ %GCC% --static fbshot.o main.o -o asl-native
@if not ERRORLEVEL 0 goto Error
@echo Pushing to device...
@ %ADB% push ./asl-native /data/local/asl-native
@echo Running...
@ %ADB% shell /system/bin/chmod 0777 /data/local/asl-native
@ start /B %ADB% shell "/data/local/asl-native /data/local/asl-native.log"
@goto Exit
:Error
@echo Error while compiling/linking.
:Exit
|
zzou-screenshot
|
native/make.bat
|
Batchfile
|
bsd
| 680
|
# Android Screenshot Library
# -- Native Android application --
# Makefile
x86_GCC=gcc
ARM_GCC=/opt/local/arm-2010q1/bin/arm-none-linux-gnueabi-gcc
C_FLAGS=-DDEBUG
L_FLAGS=--static
ADB=/var/lib/google/android-sdk-linux_86/tools/adb
DEVICE_FILE=/data/local/asl-native
native: fbshot main
${ARM_GCC} ${L_FLAGS} fbshot.o main.o -o native
fbshot: fbshot.c common.h
${ARM_GCC} -c ${C_FLAGS} fbshot.c -o fbshot.o
main: main.c common.h
${ARM_GCC} -c ${C_FLAGS} main.c -o main.o
clean:
rm native*
rm *.o
upload: native
${ADB} push ./native ${DEVICE_FILE}
x86: main.c fbshot.c common.h
${x86_GCC} -c ${C_FLAGS} main.c -o main-x86.o
${x86_GCC} -c ${C_FLAGS} fbshot.c -o fbshot-x86.o
${x86_GCC} ${L_FLAGS} fbshot-x86.o main-x86.o -o native-x86
|
zzou-screenshot
|
native/makefile
|
Makefile
|
bsd
| 755
|
cmd /c make.bat
|
zzou-screenshot
|
native/make.ps1
|
PowerShell
|
bsd
| 15
|
### Android Screenshot Library ###
##################################
### Startup script ###
"Android Screenshot Library -- initializing..." | Out-Host
try
{
# Check whether ANDROID environmental variable is set
if ([String]::IsNullOrEmpty($Env:ANDROID)) {
"*** Android SDK not found. ***" | Out-Host
"Make sure ANDROID variable is pointing to Android SDK root directory." | Out-Host
}
else
{
$adb = [IO.Path]::Combine([IO.Path]::Combine($Env:ANDROID, "platform-tools"), "adb.exe")
# Check whether device is connected and wait for one
$adbState = (& $adb get-state)
if ($adbState -ne "device") {
"Device not found -- connect one to continue..." | Out-Host
& $adb wait-for-device
"Device connected." | Out-Host
}
# Install service
"Installing native service..." | Out-Host
& $adb push ./asl-native /data/local/asl-native
& $adb shell /system/bin/chmod 0777 /data/local/asl-native
# If the service is already running, kill it
$ps = (& $adb shell ps) | Where-Object { $_.Contains("asl-native") }
if (-not [String]::IsNullOrEmpty($ps)) {
"Service already running -- do you want to restart it?" | Out-Host
$answer = Read-Host -Prompt "(Y)es/(N)o"
if ($answer.ToLower()[0] -ne 'y') { return }
# Get PID of the service's process
"Terminating service..." | Out-Host
for ($i = 0; $i -lt $ps.Length; ++$i)
{
$psLine = $ps[$i].ToString().Split(" ", [StringSplitOptions]::RemoveEmptyEntries)
& $adb shell kill -9 $psLine[1]
}
"Service terminated." | Out-Host
}
# Start the service
"Starting service..." | Out-Host
cmd /c start /B $adb shell "/data/local/asl-native /data/local/asl-native.log"
"Service started successfully." | Out-Host
}
}
catch [Exception]
{
"*** An error has occured ***" | Out-Host
$_ | Out-Host
}
|
zzou-screenshot
|
desktop/run.ps1
|
PowerShell
|
bsd
| 1,886
|
@echo off
echo Android Screenshot Library -- Initializing...
if not defined ANDROID goto SdkPathNotDefined
echo Waiting for device to be connected...
%ANDROID%\platform-tools\adb.exe wait-for-device
echo - Installing native service...
%ANDROID%\platform-tools\adb.exe push ./asl-native /data/local/asl-native
%ANDROID%\platform-tools\adb.exe shell /system/bin/chmod 0777 /data/local/asl-native
echo Starting...
%ANDROID%\platform-tools\adb.exe shell kill -9 "/data/local/asl-native"
start /B %ANDROID%\platform-tools\adb.exe shell "/data/local/asl-native /data/local/asl-native.log"
echo Service started successfully.
goto Finish
:SdkPathNotDefined
echo *** Android SDK not found ***
echo Make sure ANDROID variable is set to root folder of Android SDK.
:Finish
|
zzou-screenshot
|
desktop/run.bat
|
Batchfile
|
bsd
| 799
|
#!/bin/bash
# Android Screenshot Library #
##############################
# Startup script #
echo "Android Screenshot Library -- initializing..."
#
if [ -z $ANDROID ]; then
echo "*** Android SDK not found ***"
echo "Make sure the ANDROID variable is pointing to Android SDK root directory"
else
adb="$ANDROID/platform-tools/adb"
# Check whether device is connected or wait for one
adbState=`$adb get-state`
if [ $adbState = "device" ]; then
echo "Device not found -- connect one to continue..."
$adb wait-for-device
echo "Device connected."
fi
# Install service
echo "Installing native service..."
$adb push ./asl-native /data/local/asl-native
$adb shell /system/bin/chmod 0777 /data/local/asl-native
# Start the service
echo "Starting service..."
$adb shell "/data/local/asl-native /data/local/asl-native.log" &
echo "Service started successfully."
fi
|
zzou-screenshot
|
desktop/run.sh
|
Shell
|
bsd
| 893
|
<html>
<head>
<meta http-equiv="Refresh" content="0; url=http://code.google.com/p/android-screenshot-library/wiki/Usage">
<title>Android Screenshot Library</title>
</head>
<body>You should be redirected to ASL wiki page. If not, click <a href="http://code.google.com/p/android-screenshot-library/wiki/Usage">here</a>.</body>
</html>
|
zzou-screenshot
|
readme.html
|
HTML
|
bsd
| 345
|
package pl.polidea.asl;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.InvalidParameterException;
import java.util.UUID;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
public class ScreenshotService extends Service {
/*
* Action name for intent used to bind to service.
*/
public static final String BIND = "pl.polidea.asl.ScreenshotService.BIND";
/*
* Name of the native process.
*/
private static final String NATIVE_PROCESS_NAME = "asl-native";
/*
* Port number used to communicate with native process.
*/
private static final int PORT = 42380;
/*
* Timeout allowed in communication with native process.
*/
private static final int TIMEOUT = 1000;
/*
* Directory where screenshots are being saved.
*/
private static final String SCREENSHOT_FOLDER = "/sdcard/screens/";
/*
* An implementation of interface used by clients to take screenshots.
*/
private final IScreenshotProvider.Stub mBinder = new IScreenshotProvider.Stub() {
@Override
public String takeScreenshot() throws RemoteException {
try {
return ScreenshotService.this.takeScreenshot();
}
catch(Exception e) { return null; }
}
@Override
public boolean isAvailable() throws RemoteException {
return isNativeRunning();
}
};
@Override
public void onCreate() {
Log.i("service", "Service created.");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/*
* Checks whether the internal native application is running,
*/
private boolean isNativeRunning() {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("localhost", PORT), 10); // short timeout
}
catch (Exception e) {
return false;
}
return true;
// ActivityManager am = (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE);
// List<ActivityManager.RunningAppProcessInfo> ps = am.getRunningAppProcesses();
//
// if (am != null) {
// for (ActivityManager.RunningAppProcessInfo rapi : ps) {
// if (rapi.processName.contains(NATIVE_PROCESS_NAME))
// // native application found
// return true;
// }
//
// }
// return false;
}
/*
* Internal class describing a screenshot.
*/
static final class Screenshot {
public Buffer pixels;
public int width;
public int height;
public int bpp;
public boolean isValid() {
if (pixels == null || pixels.capacity() == 0 || pixels.limit() == 0) return false;
if (width <= 0 || height <= 0) return false;
return true;
}
}
/*
* Determines whether the phone's screen is rotated.
*/
private int getScreenRotation() {
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
Display disp = wm.getDefaultDisplay();
// check whether we operate under Android 2.2 or later
try {
Class<?> displayClass = disp.getClass();
Method getRotation = displayClass.getMethod("getRotation");
int rot = ((Integer)getRotation.invoke(disp)).intValue();
switch (rot) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return 270;
default: return 0;
}
} catch (NoSuchMethodException e) {
// no getRotation() method -- fall back to getOrientation()
int orientation = disp.getOrientation();
// Sometimes you may get undefined orientation Value is 0
// simple logic solves the problem compare the screen
// X,Y Co-ordinates and determine the Orientation in such cases
if(orientation==Configuration.ORIENTATION_UNDEFINED){
Configuration config = getResources().getConfiguration();
orientation = config.orientation;
if(orientation==Configuration.ORIENTATION_UNDEFINED){
//if height and widht of screen are equal then
// it is square orientation
if(disp.getWidth()==disp.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
}else{ //if widht is less than height than it is portrait
if(disp.getWidth() < disp.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else{ // if it is not any of the above it will defineitly be landscape
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
}
}
return orientation == 1 ? 0 : 90; // 1 for portrait, 2 for landscape
} catch (Exception e) {
return 0; // bad, I know ;P
}
}
/*
* Communicates with the native service and retrieves a screenshot from it
* as a 2D array of bytes.
*/
private Screenshot retreiveRawScreenshot() throws Exception {
try {
// connect to native application
Socket s = new Socket();
s.connect(new InetSocketAddress("localhost", PORT), TIMEOUT);
// send command to take screenshot
OutputStream os = s.getOutputStream();
os.write("SCREEN".getBytes("ASCII"));
// retrieve response -- first the size and BPP of the screenshot
InputStream is = s.getInputStream();
StringBuilder sb = new StringBuilder();
int c;
while ((c = is.read()) != -1) {
if (c == 0) break;
sb.append((char)c);
}
// parse it
String[] screenData = sb.toString().split(" ");
if (screenData.length >= 3) {
Screenshot ss = new Screenshot();
ss.width = Integer.parseInt(screenData[0]);
ss.height = Integer.parseInt(screenData[1]);
ss.bpp = Integer.parseInt(screenData[2]);
// retreive the screenshot
// (this method - via ByteBuffer - seems to be the fastest)
ByteBuffer bytes = ByteBuffer.allocate (ss.width * ss.height * ss.bpp / 8);
is = new BufferedInputStream(is); // buffering is very important apparently
is.read(bytes.array()); // reading all at once for speed
bytes.position(0); // reset position to the beginning of ByteBuffer
ss.pixels = bytes;
return ss;
}
}
catch (Exception e) {
throw new Exception(e);
}
finally {}
return null;
}
/*
* Saves given array of bytes into image file in the PNG format.
*/
private void writeImageFile(Screenshot ss, String file) {
if (ss == null || !ss.isValid()) throw new IllegalArgumentException();
if (file == null || file.length() == 0) throw new IllegalArgumentException();
// resolve screenshot's BPP to actual bitmap pixel format
Bitmap.Config pf;
switch (ss.bpp) {
case 16: pf = Config.RGB_565; break;
case 32: pf = Config.ARGB_8888; break;
default: pf = Config.ARGB_8888; break;
}
// create appropriate bitmap and fill it wit data
Bitmap bmp = Bitmap.createBitmap(ss.width, ss.height, pf);
bmp.copyPixelsFromBuffer(ss.pixels);
// handle the screen rotation
int rot = getScreenRotation();
if (rot != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(-rot);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
}
// save it in PNG format
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new InvalidParameterException();
}
bmp.compress(CompressFormat.PNG, 100, fos);
}
/*
* Takes screenshot and saves to a file.
*/
private String takeScreenshot() throws IOException {
// make sure the path to save screens exists
File screensPath = new File(SCREENSHOT_FOLDER);
if (!screensPath.mkdirs()) return null;
// construct screenshot file name
StringBuilder sb = new StringBuilder();
sb.append(SCREENSHOT_FOLDER);
sb.append(Integer.toHexString(UUID.randomUUID().hashCode())); // hash code of UUID should be quite random yet short
sb.append(".png");
String file = sb.toString();
// fetch the screen and save it
Screenshot ss = null;
try {
ss = retreiveRawScreenshot();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
writeImageFile(ss, file);
return file;
}
}
|
zzou-screenshot
|
demo/src/pl/polidea/asl/ScreenshotService.java
|
Java
|
bsd
| 8,506
|
// AIDL file specifying interface used by clients to retrieve screenshots
package pl.polidea.asl;
// Interface for fetching screenshots
interface IScreenshotProvider {
// Checks whether the native background application is running
// (and thus whether the screenshots are available)
boolean isAvailable();
// Create a screen snapshot and returns path to file where it is written.
String takeScreenshot();
}
|
zzou-screenshot
|
demo/src/pl/polidea/asl/IScreenshotProvider.aidl
|
AIDL
|
bsd
| 415
|
package pl.polidea.asl.demo;
import pl.polidea.asl.*;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources.NotFoundException;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.graphics.*;
public class ScreenshotDemo extends Activity {
/*
* The ImageView used to display taken screenshots.
*/
private ImageView imgScreen;
private ServiceConnection aslServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
aslProvider = IScreenshotProvider.Stub.asInterface(service);
}
};
private IScreenshotProvider aslProvider = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgScreen = (ImageView)findViewById(R.id.imgScreen);
Button btn = (Button)findViewById(R.id.btnTakeScreenshot);
btn.setOnClickListener(btnTakeScreenshot_onClick);
// connect to ASL service
//Intent intent = new Intent(ScreenshotService.class.getName());
Intent intent = new Intent();
intent.setClass(this, ScreenshotService.class);
//intent.addCategory(Intent.ACTION_DEFAULT);
bindService (intent, aslServiceConn, Context.BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
unbindService(aslServiceConn);
super.onDestroy();
}
private View.OnClickListener btnTakeScreenshot_onClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (aslProvider == null)
Toast.makeText(ScreenshotDemo.this, R.string.n_a, Toast.LENGTH_SHORT).show();
else if (!aslProvider.isAvailable())
Toast.makeText(ScreenshotDemo.this, R.string.native_n_a, Toast.LENGTH_SHORT).show();
else {
String file = aslProvider.takeScreenshot();
if (file == null)
Toast.makeText(ScreenshotDemo.this, R.string.screenshot_error, Toast.LENGTH_SHORT).show();
else {
Toast.makeText(ScreenshotDemo.this, R.string.screenshot_ok, Toast.LENGTH_SHORT).show();
Bitmap screen = BitmapFactory.decodeFile(file);
imgScreen.setImageBitmap(screen);
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// squelch
}
}
};
}
|
zzou-screenshot
|
demo/src/pl/polidea/asl/demo/ScreenshotDemo.java
|
Java
|
bsd
| 2,705
|
# Android Screenshot Library
############################
# Publishing script
# Create directory for package
Remove-Item dist -Recurse -ErrorAction SilentlyContinue
New-Item dist -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
# Copy native application
Copy-Item native/asl-native dist/
# Copy source files
Copy-Item demo/src/pl/polidea/asl/IScreenshotProvider.aidl dist/
Copy-Item demo/src/pl/polidea/asl/ScreenshotService.java dist/
# Copy service launch scripts
Copy-Item desktop/run.* dist/
# Copy demo application
Copy-Item demo dist/demo -Recurse
Remove-Item dist/demo/bin/* -Recurse -ErrorAction SilentlyContinue
Remove-Item dist/demo/gen/* -Recurse -ErrorAction SilentlyContinue
# Copy readme file
Copy-Item readme.html dist/
|
zzou-screenshot
|
publish.ps1
|
PowerShell
|
bsd
| 781
|
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
m4_define([MAJOR_VERSION], 1)
m4_define([MINOR_VERSION], 6)
m4_define([MICRO_VERSION], 1)
AC_PREREQ(2.59)
AC_INIT([klish],
[MAJOR_VERSION.MINOR_VERSION.MICRO_VERSION],
[serj.kalichev at gmail dot com])
AC_CONFIG_AUX_DIR(aux_scripts)
AC_CONFIG_MACRO_DIR([m4])
# Check for system extensions (_POSIX_THREAD_SEMANTICS for Solaris)
AC_USE_SYSTEM_EXTENSIONS
# Checks for programs.
AC_PROG_CC
AC_LIBTOOL_WIN32_DLL
AC_PROG_LIBTOOL
AC_CONFIG_HEADERS([config.h])
AM_INIT_AUTOMAKE(subdir-objects)
AM_PROG_CC_C_O
# needed to handle 64-bit architecture
AC_CHECK_SIZEOF(int)
AC_CHECK_SIZEOF(long)
AC_CHECK_SIZEOF(size_t)
################################
# Deal with debugging options
################################
AC_ARG_ENABLE(debug,
[AS_HELP_STRING([--enable-debug],
[Turn on debugging including asserts [default=no]])],
[],
[enable_debug=no])
AM_CONDITIONAL(DEBUG,test x$enable_debug = xyes)
################################
# Check for the roxml library
################################
AC_ARG_WITH(libroxml,
[AS_HELP_STRING([--with-libroxml=DIR],
[Use roxml as the XML parser implementation [default=no]])],
[use_roxml=$withval],
[use_roxml=no])
AC_ARG_WITH(libexpat,
[AS_HELP_STRING([--with-libexpat=DIR],
[Use expat as the XML parser implementation [default=no]])],
[use_expat=$withval],
[use_expat=no])
AC_ARG_WITH(libxml2,
[AS_HELP_STRING([--with-libxml2=DIR],
[Use libxml2 as the XML parser implementation [default=no]])],
[use_libxml2=$withval],
[use_libxml2=no])
# select the default xml backend
sel_xml_backends=""
xml_backend=""
found_xml_backend=""
count_xml_backends=0
if test "x$use_libxml2" != "xno"; then
sel_xml_backends="$sel_xml_backends libxml2"
xml_backend="libxml2"
count_xml_backends=$((count_xml_backends + 1))
fi
if test "x$use_roxml" != "xno"; then
sel_xml_backends="$sel_xml_backends roxml"
xml_backend="roxml"
count_xml_backends=$((count_xml_backends + 1))
fi
if test "x$use_expat" != "xno"; then
sel_xml_backends="$sel_xml_backends expat"
xml_backend="expat"
count_xml_backends=$((count_xml_backends + 1))
fi
if test $count_xml_backends -gt 1; then
AC_MSG_WARN([Multiple XML backend has been selected ($sel_xml_backends). I choose $xml_backend])
fi
if test "x$xml_backend" = "x"; then
xml_backend="auto"
AC_MSG_WARN([No XML backend has been selected: auto check])
fi
case x$xml_backend in
xroxml)
use_libxml2="no"
use_expat="no"
;;
xlibxml2)
use_roxml="no"
use_expat="no"
;;
xexpat)
use_libxml2="no"
use_roxml="no"
;;
esac
XML_LDFLAGS=""
XML_CFLAGS=""
XML_LIBS=""
if test "$xml_backend" = "expat" -o "$xml_backend" = "auto"; then
if test "$xml_backend" = "auto"; then
# on auto select, we try to detect the library
use_expat="yes"
fi
case x$use_expat in
xyes)
# we choose to NOT rely on pkg-config on this one. Instead, we
# check for the library and the header file - that should be
# enough.
AC_CHECK_HEADER([expat.h],
[expat_h_found=yes],
[expat_h_found=no],
[/* force include check */])
if test "x$expat_h_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find <expat.h> header file])
else
AC_MSG_ERROR([cannot find <expat.h> header file])
fi
fi
XML_CFLAGS=""
AC_CHECK_LIB([expat],
[XML_ParserCreate],
[expat_lib_found=yes],
[expat_lib_found=no],
[])
if test "x$expat_lib_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find expat library])
else
AC_MSG_ERROR([cannot find expat library])
fi
fi
XML_LDFLAGS=""
XML_LIBS="-lexpat"
AC_DEFINE([HAVE_LIB_EXPAT],
[],
[libexpat-based XML backend])
xml_backend="found"
found_xml_backend="expat"
;;
*)
# this is probably broken. We consider that the user supplied path is
# a non-standard path. But we're not going to check anything.
AC_MSG_WARN([--with-expat=DIR is probably broken, just trying])
XML_LDFLAGS="-L${use_expat}/lib"
XML_CFLAGS="-I${use_expat}/include"
XML_LIBS="-lexpat"
AC_MSG_CHECKING([for expat support])
AC_MSG_RESULT([yes])
AC_MSG_NOTICE([headers for expat hopefully in ${use_expat}/include])
AC_MSG_NOTICE([library expat hopefully in ${use_expat}/lib])
AC_DEFINE([HAVE_LIB_EXPAT],
[],
[expat-based XML backend])
xml_backend="found"
found_xml_backend="expat"
;;
esac
else
AC_MSG_CHECKING([for libexpat support])
AC_MSG_RESULT([no])
fi
if test "$xml_backend" = "roxml" -o "$xml_backend" = "auto"; then
if test "$xml_backend" = "auto"; then
# on auto select, we try to detect the library
use_roxml="yes"
fi
case x$use_roxml in
xyes)
# we choose to NOT rely on pkg-config on this one. We may do it as
# libroxml provides a .pc file but some environment (both cross-compile
# or native environment) may lack this support. The good thing is that
# it doesn't add much complexity to the configure.ac file (and we
# may move these tests to another m4 file later).
# the header is installed in the standard path
AC_CHECK_HEADER([roxml.h],
[roxml_h_found=yes],
[roxml_h_found=no],
[/* force include check */])
if test "x$roxml_h_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find <roxml.h> header file])
else
AC_MSG_ERROR([cannot find <roxml.h> header file])
fi
fi
XML_CFLAGS=""
# the library is installed in the standard path
AC_CHECK_LIB([roxml],
[roxml_load_doc],
[roxml_lib_found=yes],
[roxml_lib_found=no],
[])
if test "x$roxml_lib_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find roxml library])
else
AC_MSG_ERROR([cannot find roxml library])
fi
fi
XML_LDFLAGS=""
XML_LIBS="-lroxml"
AC_DEFINE([HAVE_LIB_ROXML],
[],
[libroxml-based XML backend])
xml_backend="found"
found_xml_backend="roxml"
;;
*)
# first, we check if we're not looking for an alternate include
# directory -for example, if the user feeds the script with the
# option --with-roxml=/usr/local
# NOTE: we search for include/roxml.h and inc/roxml.h to defeat
# the caching algorithm of the configure script. If someone knows
# a better way, please do not hesitate
roxml_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS -I${use_roxml}"
AC_CHECK_HEADER([include/roxml.h],
[roxml_h_found=yes],
[roxml_h_found=no],
[/* force include check */])
if test "x$roxml_h_found" = "xno"; then
# the directory might be a source directory, so check
# if the include file is to be found here
AC_CHECK_HEADER([inc/roxml.h],
[roxml_h_found=yes],
[roxml_h_found=no],
[/* force include check */])
if test "x$roxml_h_found" = "xno"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find <roxml.h> header file])
else
AC_MSG_ERROR([cannot find <roxml.h> header file])
fi
fi
XML_CFLAGS="-I${use_roxml}/inc"
AC_MSG_NOTICE([header file <roxml.h> found in ${use_roxml}/inc])
else
XML_CFLAGS="-I${use_roxml}/include"
AC_MSG_NOTICE([header file <roxml.h> found in ${use_roxml}/include])
fi
CFLAGS="$roxml_CFLAGS"
# we're doing both previous checks, but we are trying to find a library
# now, so the check themselves are a bit different
# NOTE: we search for roxml_load_doc and roxml_close to defeat
# the caching algorithm of the configure script. If someone knows
# a better way, please do not hesitate.
roxml_LDFLAGS="$LDFLAGS"
LDFLAGS="$LDFLAGS -L${use_roxml}/lib"
AC_CHECK_LIB([roxml],
[roxml_load_doc],
[roxml_lib_found=yes],
[roxml_lib_found=no],
[])
LDFLAGS=$roxml_LDFLAGS
if test "x$roxml_lib_found" = "xno"; then
LDFLAGS="$LDFLAGS -L${use_roxml}"
AC_CHECK_LIB([roxml],
[roxml_close],
[roxml_lib_found=yes],
[roxml_lib_found=no],
[])
LDFLAGS=$roxml_LDFLAGS
if test "x$roxml_lib_found" = "xno"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find roxml library])
else
AC_MSG_ERROR([cannot find roxml library])
fi
fi
XML_LDFLAGS="-L${use_roxml}"
XML_LIBS="-lroxml"
AC_MSG_NOTICE([library libroxml found in ${use_roxml}])
else
XML_LDFLAGS="-L${use_roxml}/lib"
XML_LIBS="-lroxml"
AC_MSG_NOTICE([library libroxml found in ${use_roxml}/lib])
fi
AC_DEFINE([HAVE_LIB_ROXML],
[],
[libroxml-based XML backend])
xml_backend="found"
found_xml_backend="roxml"
;;
esac
else
AC_MSG_CHECKING([for libroxml support])
AC_MSG_RESULT([no])
fi
if test "$xml_backend" = "libxml2" -o "$xml_backend" = "auto"; then
if test "$xml_backend" = "auto"; then
# on auto select, we try to detect the library
use_libxml2="yes"
fi
case x$use_libxml2 in
xyes)
# I would love to avoid using pkg-config (which may not be available on
# some compilation environment) but doing so really add a lot of
# complexity to the system, as the headers don't lie in a standard
# directory (they lie in a subdirectory of a standard include directory;
# not the same thing for configure scripts).
XML_CFLAGS="`pkg-config libxml-2.0 --cflags`"
XML_LDFLAGS="`pkg-config libxml-2.0 --libs-only-L`"
XML_LIBS="`pkg-config libxml-2.0 --libs-only-l`"
AC_CHECK_LIB([xml2],
[xmlNewDoc],
[libxml2_lib_found=yes],
[libxml2_lib_found=no],
[-lz])
if test "x$libxml2_lib_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find libxml2 library])
else
AC_MSG_ERROR([cannot find libxml2 library])
fi
fi
# the header file is installed in a subdirectory of one of the standard
# include directory. This might prove to be a problem if the cross-
# compile environment is not complete enough (i.e. if it misses
# pkg-config, or if pkg-config returns wrong values). In most cases, the
# environment is likely to be OK so we will never hit any issue.
xml2_CFLAGS="$CFLAGS"
CFLAGS="$CFLAGS $XML_CFLAGS"
AC_CHECK_HEADER([libxml/tree.h],
[libxml2_h_found=yes],
[libxml2_h_found=no],
[/* force include check */])
CFLAGS="$xml2_CFLAGS"
if test "x$libxml2_h_found" != "xyes"; then
if test "$xml_backend" = "auto"; then
AC_MSG_WARN([cannot find libxml2 headers])
else
AC_MSG_ERROR([cannot find libxml2 headers])
fi
fi
AC_DEFINE([HAVE_LIB_LIBXML2],
[],
[libxml2-based XML backend])
xml_backend="found"
found_xml_backend="libxml2"
;;
*)
# this is probably broken. We consider that the user supplied path is
# a non-standard path. But we're not going to check anything.
AC_MSG_WARN([--with-libxml2=DIR is probably broken, just trying])
XML_LDFLAGS="-L${use_libxml2}/lib"
XML_CFLAGS="-I${use_libxml2}/include/libxml2"
XML_LIBS="-lxml2"
AC_MSG_CHECKING([for libxml2 support])
AC_MSG_RESULT([yes])
AC_MSG_NOTICE([headers for libxml2 hopefully in ${use_libxml2}/include/libxml2])
AC_MSG_NOTICE([library libxml2 hopefully in ${use_libxml2}/lib])
AC_DEFINE([HAVE_LIB_LIBXML2],
[],
[libxml2-based XML backend])
xml_backend="found"
found_xml_backend="libxml2"
;;
esac
else
# not selected? We print a small message
AC_MSG_CHECKING([for libxml2 support])
AC_MSG_RESULT([no])
fi
if test "$xml_backend" != "found"; then
AC_MSG_ERROR([Failed to find a suitable XML backend])
fi
if test $count_xml_backends -eq 0; then
AC_MSG_NOTICE([I found a suitable XML backend: $found_xml_backend])
fi
AC_SUBST(XML_LIBS)
AC_SUBST(XML_LDFLAGS)
AC_SUBST(XML_CFLAGS)
################################
# Search for network functions (like connect())
################################
AC_SEARCH_LIBS([socket], [socket])
################################
# Check for regex.h
################################
AC_CHECK_HEADERS(regex.h, [],
AC_MSG_ERROR([regex.h not found: regular expressions are not supported]))
################################
# Check for getopt_long()
################################
AC_CHECK_HEADERS(getopt.h, [],
AC_MSG_WARN([getopt.h not found: only short parameters can be used on command line]))
################################
# Check for locale.h
################################
AC_CHECK_HEADERS(locale.h, [],
AC_MSG_WARN([locale.h not found: the locales is not supported]))
################################
# Check for CODESET within nl_langinfo
################################
AM_LANGINFO_CODESET
################################
# Check for pwd.h and grp.h
################################
AC_CHECK_HEADERS(pwd.h, [],
AC_MSG_WARN([pwd.h not found: the pwd operations is not supported]))
AC_CHECK_HEADERS(grp.h, [],
AC_MSG_WARN([grp.h not found: the grp operations is not supported]))
################################
# Check for chroot
################################
AC_CHECK_FUNCS(chroot, [],
AC_MSG_WARN([chroot() not found: the choot is not supported]))
AC_CONFIG_FILES(Makefile)
AC_OUTPUT
|
zzysjtu-klish
|
configure.ac
|
M4Sugar
|
bsd
| 15,589
|
/*
* conf.h
*/
/**
\ingroup clish
\defgroup clish_conf config
@{
\brief This class is a config in memory container.
Use it to implement config in memory.
*/
#ifndef _konf_tree_h
#define _konf_tree_h
#include <stdio.h>
#include "lub/types.h"
#include "lub/list.h"
typedef struct konf_tree_s konf_tree_t;
#define KONF_ENTRY_OK 0xffff
#define KONF_ENTRY_DIRTY 0xfffe
#define KONF_ENTRY_NEW 0xfffd
/*=====================================
* CONF INTERFACE
*===================================== */
/*-----------------
* meta functions
*----------------- */
konf_tree_t *konf_tree_new(const char *line, unsigned short priority);
/*-----------------
* methods
*----------------- */
void konf_tree_delete(konf_tree_t * instance);
void konf_tree_fprintf(konf_tree_t * instance, FILE * stream,
const char *pattern, int top_depth, int depth,
bool_t seq, unsigned char prev_pri_hi);
konf_tree_t *konf_tree_new_conf(konf_tree_t * instance,
const char *line, unsigned short priority,
bool_t seq, unsigned short seq_num);
konf_tree_t *konf_tree_find_conf(konf_tree_t * instance,
const char *line, unsigned short priority, unsigned short sequence);
int konf_tree_del_pattern(konf_tree_t * instance,
const char *line, bool_t unique,
const char *pattern, unsigned short priority,
bool_t seq, unsigned short seq_num);
/*-----------------
* attributes
*----------------- */
unsigned short konf_tree__get_priority(const konf_tree_t * instance);
unsigned char konf_tree__get_priority_hi(const konf_tree_t * instance);
unsigned char konf_tree__get_priority_lo(const konf_tree_t * instance);
bool_t konf_tree__get_splitter(const konf_tree_t * instance);
void konf_tree__set_splitter(konf_tree_t *instance, bool_t splitter);
unsigned short konf_tree__get_seq_num(const konf_tree_t * instance);
void konf_tree__set_seq_num(konf_tree_t * instance, unsigned short seq_num);
unsigned short konf_tree__get_sub_num(const konf_tree_t * instance);
void konf_tree__set_sub_num(konf_tree_t * instance, unsigned short sub_num);
const char * konf_tree__get_line(const konf_tree_t * instance);
void konf_tree__set_depth(konf_tree_t * instance, int depth);
int konf_tree__get_depth(const konf_tree_t * instance);
#endif /* _konf_tree_h */
/** @} clish_conf */
|
zzysjtu-klish
|
konf/tree.h
|
C
|
bsd
| 2,254
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#include "lub/types.h"
#include "lub/argv.h"
#include "lub/string.h"
#include "private.h"
/*-------------------------------------------------------- */
konf_query_t *konf_query_new(void)
{
konf_query_t *this;
if (!(this = malloc(sizeof(*this))))
return NULL;
this->op = KONF_QUERY_OP_NONE;
this->pattern = NULL;
this->priority = 0;
this->seq = BOOL_FALSE;
this->seq_num = 0;
this->pwdc = 0;
this->pwd = NULL;
this->line = NULL;
this->path = NULL;
this->splitter = BOOL_TRUE;
this->unique = BOOL_TRUE;
this->depth = -1;
return this;
}
/*-------------------------------------------------------- */
void konf_query_add_pwd(konf_query_t *this, char *str)
{
size_t new_size;
char **tmp;
if (!this)
return;
new_size = ((this->pwdc + 1) * sizeof(char *));
/* resize the pwd vector */
tmp = realloc(this->pwd, new_size);
assert(tmp);
this->pwd = tmp;
/* insert reference to the pwd component */
this->pwd[this->pwdc++] = strdup(str);
}
/*-------------------------------------------------------- */
void konf_query_free(konf_query_t *this)
{
unsigned i;
free(this->pattern);
free(this->line);
free(this->path);
if (this->pwdc > 0) {
for (i = 0; i < this->pwdc; i++)
free(this->pwd[i]);
free(this->pwd);
}
free(this);
}
/*-------------------------------------------------------- */
/* Parse query */
int konf_query_parse(konf_query_t *this, int argc, char **argv)
{
unsigned i = 0;
int pwdc = 0;
static const char *shortopts = "suoedtp:q:r:l:f:inh:";
#ifdef HAVE_GETOPT_H
static const struct option longopts[] = {
{"set", 0, NULL, 's'},
{"unset", 0, NULL, 'u'},
{"ok", 0, NULL, 'o'},
{"error", 0, NULL, 'e'},
{"dump", 0, NULL, 'd'},
{"stream", 0, NULL, 't'},
{"priority", 1, NULL, 'p'},
{"seq", 1, NULL, 'q'},
{"pattern", 1, NULL, 'r'},
{"line", 1, NULL, 'l'},
{"file", 1, NULL, 'f'},
{"splitter", 0, NULL, 'i'},
{"non-unique", 0, NULL, 'n'},
{"depth", 1, NULL, 'h'},
{NULL, 0, NULL, 0}
};
#endif
optind = 0; /* It must be 1 for QNX6. This system has no getopt.h */
while(1) {
int opt;
#ifdef HAVE_GETOPT_H
opt = getopt_long(argc, argv, shortopts, longopts, NULL);
#else
opt = getopt(argc, argv, shortopts);
#endif
if (-1 == opt)
break;
switch (opt) {
case 'o':
this->op = KONF_QUERY_OP_OK;
break;
case 'e':
this->op = KONF_QUERY_OP_ERROR;
break;
case 's':
this->op = KONF_QUERY_OP_SET;
break;
case 'u':
this->op = KONF_QUERY_OP_UNSET;
break;
case 'd':
this->op = KONF_QUERY_OP_DUMP;
break;
case 't':
this->op = KONF_QUERY_OP_STREAM;
break;
case 'p':
{
long val = 0;
char *endptr;
val = strtol(optarg, &endptr, 0);
if (endptr == optarg)
break;
if ((val > 0xffff) || (val < 0))
break;
this->priority = (unsigned short)val;
break;
}
case 'q':
{
long val = 0;
char *endptr;
this->seq = BOOL_TRUE;
val = strtol(optarg, &endptr, 0);
if (endptr == optarg)
break;
if ((val > 0xffff) || (val < 0))
break;
this->seq_num = (unsigned short)val;
break;
}
case 'r':
this->pattern = strdup(optarg);
break;
case 'l':
this->line = strdup(optarg);
break;
case 'f':
this->path = strdup(optarg);
break;
case 'i':
this->splitter = BOOL_FALSE;
break;
case 'n':
this->unique = BOOL_FALSE;
break;
case 'h':
{
long val = 0;
char *endptr;
val = strtol(optarg, &endptr, 0);
if (endptr == optarg)
break;
if ((val > 0xffff) || (val < 0))
break;
this->depth = (unsigned short)val;
break;
}
default:
break;
}
}
/* Check options */
if (KONF_QUERY_OP_NONE == this->op)
return -1;
if (KONF_QUERY_OP_SET == this->op) {
if (!this->pattern)
return -1;
if (!this->line)
return -1;
}
if ((pwdc = argc - optind) < 0)
return -1;
for (i = 0; i < pwdc; i++)
konf_query_add_pwd(this, argv[optind + i]);
return 0;
}
/*-------------------------------------------------------- */
/* Parse query string */
int konf_query_parse_str(konf_query_t *this, char *str)
{
int res;
lub_argv_t *lub_argv;
char **str_argv;
int str_argc;
/* Make args from string */
lub_argv = lub_argv_new(str, 0);
str_argv = lub_argv__get_argv(lub_argv, "");
str_argc = lub_argv__get_count(lub_argv) + 1;
/* Parse query */
res = konf_query_parse(this, str_argc, str_argv);
lub_argv__free_argv(str_argv);
lub_argv_delete(lub_argv);
return res;
}
/*-------------------------------------------------------- */
char * konf_query__get_pwd(konf_query_t *this, unsigned index)
{
if (!this)
return NULL;
if (index >= this->pwdc)
return NULL;
return this->pwd[index];
}
/*-------------------------------------------------------- */
int konf_query__get_pwdc(konf_query_t *this)
{
return this->pwdc;
}
/*-------------------------------------------------------- */
konf_query_op_t konf_query__get_op(konf_query_t *this)
{
return this->op;
}
/*-------------------------------------------------------- */
char * konf_query__get_path(konf_query_t *this)
{
return this->path;
}
/*-------------------------------------------------------- */
const char * konf_query__get_pattern(konf_query_t *this)
{
return this->pattern;
}
/*-------------------------------------------------------- */
const char * konf_query__get_line(konf_query_t *this)
{
return this->line;
}
/*-------------------------------------------------------- */
unsigned short konf_query__get_priority(konf_query_t *this)
{
return this->priority;
}
/*-------------------------------------------------------- */
bool_t konf_query__get_splitter(konf_query_t *this)
{
return this->splitter;
}
/*-------------------------------------------------------- */
bool_t konf_query__get_seq(konf_query_t *this)
{
return this->seq;
}
/*-------------------------------------------------------- */
unsigned short konf_query__get_seq_num(konf_query_t *this)
{
return this->seq_num;
}
/*-------------------------------------------------------- */
bool_t konf_query__get_unique(konf_query_t *this)
{
return this->unique;
}
/*-------------------------------------------------------- */
int konf_query__get_depth(konf_query_t *this)
{
return this->depth;
}
|
zzysjtu-klish
|
konf/query/query.c
|
C
|
bsd
| 6,479
|
#include "private.h"
#include "lub/dump.h"
/*-------------------------------------------------------- */
void konf_query_dump(konf_query_t *this)
{
const char *op;
lub_dump_printf("query(%p)\n", this);
lub_dump_indent();
switch (this->op) {
case KONF_QUERY_OP_SET:
op = "SET";
break;
case KONF_QUERY_OP_UNSET:
op = "UNSET";
break;
case KONF_QUERY_OP_DUMP:
op = "DUMP";
break;
case KONF_QUERY_OP_OK:
op = "OK";
break;
case KONF_QUERY_OP_ERROR:
op = "ERROR";
break;
case KONF_QUERY_OP_STREAM:
op = "STREAM";
break;
default:
op = "UNKNOWN";
break;
}
lub_dump_printf("operation : %s\n", op);
lub_dump_printf("pattern : %s\n", this->pattern);
lub_dump_printf("priority : 0x%x\n", this->priority);
lub_dump_printf("sequence : %u\n", this->seq ? "true" : "false");
lub_dump_printf("seq_num : %u\n", this->seq_num);
lub_dump_printf("line : %s\n", this->line);
lub_dump_printf("path : %s\n", this->path);
lub_dump_printf("pwdc : %u\n", this->pwdc);
lub_dump_printf("splitter : %s\n", this->splitter ? "true" : "false");
lub_dump_printf("unique : %s\n", this->unique ? "true" : "false");
lub_dump_printf("depth : %d\n", this->depth);
lub_dump_undent();
}
|
zzysjtu-klish
|
konf/query/query_dump.c
|
C
|
bsd
| 1,230
|
#ifndef _konf_query_private_h
#define _konf_query_private_h
#include "konf/query.h"
#include "lub/types.h"
struct konf_query_s {
konf_query_op_t op;
char *pattern;
unsigned short priority;
bool_t seq; /* sequence aka auto priority */
unsigned short seq_num; /* sequence number */
unsigned int pwdc;
char **pwd;
char *line;
char *path;
bool_t splitter;
bool_t unique;
int depth;
};
#endif
|
zzysjtu-klish
|
konf/query/private.h
|
C
|
bsd
| 403
|
/*
* buf.c
*
* This file provides the implementation of a buf class
*/
#include "private.h"
#include "lub/argv.h"
#include "lub/string.h"
#include "lub/ctype.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#define KONF_BUF_CHUNK 1024
/*---------------------------------------------------------
* PRIVATE META FUNCTIONS
*--------------------------------------------------------- */
int konf_buf_bt_compare(const void *clientnode, const void *clientkey)
{
const konf_buf_t *this = clientnode;
int keyfd;
memcpy(&keyfd, clientkey, sizeof(keyfd));
return (this->fd - keyfd);
}
/*-------------------------------------------------------- */
static void konf_buf_key(lub_bintree_key_t * key,
int fd)
{
memcpy(key, &fd, sizeof(fd));
}
/*-------------------------------------------------------- */
void konf_buf_bt_getkey(const void *clientnode, lub_bintree_key_t * key)
{
const konf_buf_t *this = clientnode;
konf_buf_key(key, this->fd);
}
/*---------------------------------------------------------
* PRIVATE METHODS
*--------------------------------------------------------- */
static void
konf_buf_init(konf_buf_t * this, int fd)
{
this->fd = fd;
this->buf = malloc(KONF_BUF_CHUNK);
this->size = KONF_BUF_CHUNK;
this->pos = 0;
this->rpos = 0;
/* Be a good binary tree citizen */
lub_bintree_node_init(&this->bt_node);
}
/*--------------------------------------------------------- */
static void konf_buf_fini(konf_buf_t * this)
{
free(this->buf);
}
/*---------------------------------------------------------
* PUBLIC META FUNCTIONS
*--------------------------------------------------------- */
size_t konf_buf_bt_offset(void)
{
return offsetof(konf_buf_t, bt_node);
}
/*--------------------------------------------------------- */
konf_buf_t *konf_buf_new(int fd)
{
konf_buf_t *this = malloc(sizeof(konf_buf_t));
if (this)
konf_buf_init(this, fd);
return this;
}
/*---------------------------------------------------------
* PUBLIC METHODS
*--------------------------------------------------------- */
void konf_buf_delete(konf_buf_t * this)
{
konf_buf_fini(this);
free(this);
}
/*--------------------------------------------------------- */
static int konf_buf_realloc(konf_buf_t *this, int addsize)
{
int chunk = KONF_BUF_CHUNK;
char *tmpbuf;
if (addsize > chunk)
chunk = addsize;
if ((this->size - this->pos) < chunk) {
tmpbuf = realloc(this->buf, this->size + chunk);
this->buf = tmpbuf;
this->size += chunk;
}
return this->size;
}
/*--------------------------------------------------------- */
int konf_buf_add(konf_buf_t *this, void *str, size_t len)
{
char *buffer;
konf_buf_realloc(this, len);
buffer = this->buf + this->pos;
memcpy(buffer, str, len);
this->pos += len;
return len;
}
/*--------------------------------------------------------- */
int konf_buf_read(konf_buf_t *this)
{
char *buffer;
int buffer_size;
int nbytes;
konf_buf_realloc(this, 0);
buffer_size = this->size - this->pos;
buffer = this->buf + this->pos;
nbytes = read(this->fd, buffer, buffer_size);
if (nbytes > 0)
this->pos += nbytes;
return nbytes;
}
/*--------------------------------------------------------- */
char * konf_buf_string(char *buf, int len)
{
unsigned i;
char *str;
for (i = 0; i < len; i++) {
if (('\0' == buf[i]) ||
('\n' == buf[i]))
break;
}
if (i >= len)
return NULL;
str = malloc(i + 1);
memcpy(str, buf, i + 1);
str[i] = '\0';
return str;
}
/*--------------------------------------------------------- */
char * konf_buf_parse(konf_buf_t *this)
{
char * str = NULL;
/* Search the buffer for the string */
str = konf_buf_string(this->buf, this->pos);
/* Remove parsed string from the buffer */
if (str) {
int len = strlen(str) + 1;
memmove(this->buf, &this->buf[len], this->pos - len);
this->pos -= len;
if (this->rpos >= len)
this->rpos -= len;
else
this->rpos = 0;
}
/* Make buffer shorter */
if ((this->size - this->pos) > (2 * KONF_BUF_CHUNK)) {
char *tmpbuf;
tmpbuf = realloc(this->buf, this->size - KONF_BUF_CHUNK);
this->buf = tmpbuf;
this->size -= KONF_BUF_CHUNK;
}
return str;
}
/*--------------------------------------------------------- */
char * konf_buf_preparse(konf_buf_t *this)
{
char * str = NULL;
str = konf_buf_string(this->buf + this->rpos, this->pos - this->rpos);
if (str)
this->rpos += (strlen(str) + 1);
return str;
}
/*--------------------------------------------------------- */
int konf_buf_lseek(konf_buf_t *this, int newpos)
{
if (newpos > this->pos)
return -1;
this->rpos = newpos;
return newpos;
}
/*--------------------------------------------------------- */
int konf_buf__get_fd(const konf_buf_t * this)
{
return this->fd;
}
/*--------------------------------------------------------- */
int konf_buf__get_len(const konf_buf_t *this)
{
return this->pos;
}
/*--------------------------------------------------------- */
char * konf_buf__dup_line(const konf_buf_t *this)
{
char *str;
str = malloc(this->pos + 1);
memcpy(str, this->buf, this->pos);
str[this->pos] = '\0';
return str;
}
/*---------------------------------------------------------
* buftree functions
*--------------------------------------------------------- */
/*--------------------------------------------------------- */
konf_buf_t *konf_buftree_find(lub_bintree_t * this,
int fd)
{
lub_bintree_key_t key;
konf_buf_key(&key, fd);
return lub_bintree_find(this, &key);
}
/*--------------------------------------------------------- */
void konf_buftree_remove(lub_bintree_t * this,
int fd)
{
konf_buf_t *tbuf;
if ((tbuf = konf_buftree_find(this, fd)) == NULL)
return;
lub_bintree_remove(this, tbuf);
konf_buf_delete(tbuf);
}
/*--------------------------------------------------------- */
int konf_buftree_read(lub_bintree_t * this, int fd)
{
konf_buf_t *buf;
buf = konf_buftree_find(this, fd);
if (!buf)
return -1;
return konf_buf_read(buf);
}
/*--------------------------------------------------------- */
char * konf_buftree_parse(lub_bintree_t * this,
int fd)
{
konf_buf_t *buf;
buf = konf_buftree_find(this, fd);
if (!buf)
return NULL;
return konf_buf_parse(buf);
}
|
zzysjtu-klish
|
konf/buf/buf.c
|
C
|
bsd
| 6,242
|
/*
* conf.h
*/
#ifndef _konf_buf_private_h
#define _konf_buf_private_h
#include "konf/buf.h"
#include "lub/bintree.h"
/*---------------------------------------------------------
* PRIVATE TYPES
*--------------------------------------------------------- */
struct konf_buf_s {
lub_bintree_node_t bt_node;
int fd;
int size;
char *buf;
int pos;
int rpos;
};
#endif
|
zzysjtu-klish
|
konf/buf/private.h
|
C
|
bsd
| 375
|