code
stringlengths 3
1.18M
| language
stringclasses 1
value |
|---|---|
public class HundredIntegers {
public static void main (String[] args) {
for (int i = 1; i<=100; i++) {
System.out.println(i);
}
}
}
|
Java
|
public class HundredIntegers {
public static void main (String[] args) {
for (int i = 1; i<=100; i++) {
System.out.println(i);
}
}
}
|
Java
|
package Entity;
public interface IOperatoerDTO {
int getoprId();
void setoprId(int Id);
String getoprNavn();
void setoprNavn(String Navn);
String getini();
void setini(String In);
String getcpr();
void setcpr(String cp);
String getpassword();
void setpassword(String passwd);
}
|
Java
|
package Entity;
public class OperatoerDTO implements IOperatoerDTO
{
int oprId;
String oprNavn;
String ini;
String cpr;
String password;
public OperatoerDTO() //Default Constructor
{
this.oprId = 0;
this.oprNavn = "";
this.ini = "";
this.cpr = "";
this.password = "";
}
public OperatoerDTO (int oId, String oNavn, String i, String cr, String pwd) //created constructor
{
this.oprId = oId;
this.oprNavn = oNavn;
this.ini = i;
this.cpr = cr;
this.password = pwd;
}
public int getoprId(){
return oprId;} //return must be oprId not 0;
public void setoprId(int Id){
oprId = Id;
}
public String getoprNavn(){
return oprNavn;
}
public void setoprNavn(String Navn){
oprNavn = Navn;
}
public String getini(){
return ini;
}
public void setini(String In){
ini = In;
}
public String getcpr(){
return cpr;
}
public void setcpr(String cp){
cpr = cp;
}
public String getpassword(){
return password;
}
public void setpassword(String passwd){
password = passwd;
}
}//corrected setters and getters
|
Java
|
package Controller;
import Entity.OperatoerDTO;
/*
public class ChangePassword implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public String passwordGenerator(String passwd){
return passwd;
}
public String opChangePasswd(int Id)
{
return null;
}
*/
|
Java
|
package Controller;
import java.util.ArrayList;
import Entity.OperatoerDTO;
public class OperatoerDAO implements IOperatoerDAO{
OperatoerDTO opr = new OperatoerDTO();
private ArrayList<OperatoerDTO> oDTO = new ArrayList<OperatoerDTO>();; //added an arraylist of type OperatoerDTO
public OperatoerDAO()
{
}
public OperatoerDTO getOperatoer(int oprId) throws DALException{
return opr;
}
public ArrayList<OperatoerDTO> getOperatoerList() throws DALException
{
return oDTO;
}
public void createOperatoer(OperatoerDTO opr) throws DALException{
oDTO.add(opr);
}
public void updateOperatoer(OperatoerDTO opr) throws DALException{}
}
|
Java
|
package Controller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/*
* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
*/
public boolean validate(String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
|
Java
|
package Controller;
import Entity.OperatoerDTO;
/*
public class LoginTjeck implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public int loginUser(String passwd, int id)
{
return 0;
}
}*/
|
Java
|
package Controller;
import Entity.OperatoerDTO;
/*
public class Afvejning implements IOperatoerDAO {
OperatoerDTO opr = new OperatoerDTO();
public double beregningNetto(double Tara, double Brutto)
{
return 0.0;
}
}*/
|
Java
|
package Controller;
import Entity.OperatoerDTO;
import java.util.ArrayList;
public interface IOperatoerDAO
{
//int loginUser(String passwd, int id);
OperatoerDTO getOperatoer(int oprId) throws DALException;
ArrayList<OperatoerDTO> getOperatoerList() throws DALException;
void createOperatoer(OperatoerDTO opr) throws DALException;
void updateOperatoer(OperatoerDTO opr) throws DALException;
// String passwordGenerator(String passwd);
// String opchangepasswd(int Id);
//double beregningNetto(double Tara, double Brutto);
public class DALException extends Exception //added exception class
{
public DALException()
{
super( " findes ikke.");
}
}
}
|
Java
|
package Boundary;
import Entity.OperatoerDTO;
import Controller.IOperatoerDAO.DALException;
import Controller.OperatoerDAO;
import Controller.PasswordValidator;
import java.util.Scanner;
public class Graenseflade {
OperatoerDTO opr = new OperatoerDTO();
OperatoerDAO dao = new OperatoerDAO();
PasswordValidator pv = new PasswordValidator();
boolean go = true;
public Graenseflade() //added user options
{
while(go){
System.out.println("1. Login");
System.out.println("2. Change Password");
System.out.println("3. Exit");
System.out.println("Enter your choice");
Scanner sc = new Scanner(System.in); //user input
String choice = sc.next();
switch(choice) //checking admin login
{
case "1":
Scanner user = new Scanner(System.in);
System.out.println("Enter ID:");
String uname = user.next();
System.out.println("Enter password:");
String pwd = user.next();
if((uname.equals("BOB")) && (pwd.equals("DGMNZ123")))
{
System.out.println("Login Successful");
System.out.println();
System.out.println("Select you choice");
System.out.println("1. Create Operator");
System.out.println("2. Udpate Operator");
System.out.println("3. Delete Operator");
}
//Scanner s = new Scanner(System.in); //user input
String ch = sc.next();
switch(ch) //Admin entering operator data
{
case "1":
Scanner admin = new Scanner(System.in);
System.out.println("Enter ID");
int ID = admin.nextInt();
opr.setoprId(ID);
System.out.println("Enter Name");
String name = admin.next();
opr.setoprNavn(name);
System.out.println("Enter CPR");
String cpr = admin.next();
opr.setcpr(cpr);
System.out.println("Enter Password");
/*
must contains one digit from 0-9
must contains one lowercase characters
must contains one uppercase characters
must contains one special symbols in the list "@#$%"
match anything with previous condition checking
length at least 6 characters and maximum of 20
*/
String pass = admin.next();
while((pv.validate(pass)) == false)
{
System.out.println("Enter a new Password");
pass = admin.next();
}
opr.setpassword(pass);
try { //try catch for createOperatoer
dao.createOperatoer(opr);
} catch (DALException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case "3":
System.exit(0);;
}
System.out.println("Id: " + opr.getoprId() + "\nName: " + opr.getoprNavn()
+ "\nCPR: " + opr.getcpr() + "\nPassword: " + opr.getpassword());
System.out.println();
}
}
//Login interface
/* if(Id == 10 && passwd == "02304it")
{
int Id = sysadminInt();
}
*/
//Operatorinterface
//Sysadmininterface
/* private int sysadminInt()
{
return 0;
}
*/
//vægtdetaljerinterface
}
|
Java
|
import Boundary.Graenseflade;
public class Main {
public static void main(String[] args) {
Graenseflade g = new Graenseflade();
}
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.tesseract.android;
import android.graphics.Bitmap;
import android.graphics.Rect;
import com.googlecode.leptonica.android.Pix;
import com.googlecode.leptonica.android.ReadFile;
import java.io.File;
/**
* Java interface for the Tesseract OCR engine. Does not implement all available
* JNI methods, but does implement enough to be useful. Comments are adapted
* from original Tesseract source.
*
* @author alanv@google.com (Alan Viverette)
*/
public class TessBaseAPI {
/**
* Used by the native implementation of the class.
*/
private int mNativeData;
static {
System.loadLibrary("lept");
System.loadLibrary("tess");
nativeClassInit();
}
/** Fully automatic page segmentation. */
public static final int PSM_AUTO = 0;
/** Assume a single column of text of variable sizes. */
public static final int PSM_SINGLE_COLUMN = 1;
/** Assume a single uniform block of text. (Default) */
public static final int PSM_SINGLE_BLOCK = 2;
/** Treat the image as a single text line. */
public static final int PSM_SINGLE_LINE = 3;
/** Treat the image as a single word. */
public static final int PSM_SINGLE_WORD = 4;
/** Treat the image as a single character. */
public static final int PSM_SINGLE_CHAR = 5;
/** Default accuracy versus speed mode. */
public static final int AVS_FASTEST = 0;
/** Slowest and most accurate mode. */
public static final int AVS_MOST_ACCURATE = 100;
/** Whitelist of characters to recognize. */
public static final String VAR_CHAR_WHITELIST = "tessedit_char_whitelist";
/** Blacklist of characters to not recognize. */
public static final String VAR_CHAR_BLACKLIST = "tessedit_char_blacklist";
/** Accuracy versus speed setting. */
public static final String VAR_ACCURACYVSPEED = "tessedit_accuracyvspeed";
/**
* Constructs an instance of TessBaseAPI.
*/
public TessBaseAPI() {
nativeConstruct();
}
/**
* Called by the GC to clean up the native data that we set up when we
* construct the object.
*/
@Override
protected void finalize() throws Throwable {
try {
nativeFinalize();
} finally {
super.finalize();
}
}
/**
* Initializes the Tesseract engine with a specified language model. Returns
* <code>true</code> on success.
* <p>
* Instances are now mostly thread-safe and totally independent, but some
* global parameters remain. Basically it is safe to use multiple
* TessBaseAPIs in different threads in parallel, UNLESS you use SetVariable
* on some of the Params in classify and textord. If you do, then the effect
* will be to change it for all your instances.
* <p>
* The datapath must be the name of the parent directory of tessdata and
* must end in / . Any name after the last / will be stripped. The language
* is (usually) an ISO 639-3 string or <code>null</code> will default to eng.
* It is entirely safe (and eventually will be efficient too) to call Init
* multiple times on the same instance to change language, or just to reset
* the classifier.
* <p>
* <b>WARNING:</b> On changing languages, all Tesseract parameters are reset
* back to their default values. (Which may vary between languages.)
* <p>
* If you have a rare need to set a Variable that controls initialization
* for a second call to Init you should explicitly call End() and then use
* SetVariable before Init. This is only a very rare use case, since there
* are very few uses that require any parameters to be set before Init.
*
* @param datapath the parent directory of tessdata ending in a forward
* slash
* @param language (optional) an ISO 639-3 string representing the language
* @return <code>true</code> on success
*/
public boolean init(String datapath, String language) {
if (datapath == null)
throw new IllegalArgumentException("Data path must not be null!");
if (!datapath.endsWith(File.separator))
datapath += File.separator;
File tessdata = new File(datapath + "tessdata");
if (!tessdata.exists() || !tessdata.isDirectory())
throw new IllegalArgumentException("Data path must contain subfolder tessdata!");
return nativeInit(datapath, language);
}
/**
* Frees up recognition results and any stored image data, without actually
* freeing any recognition data that would be time-consuming to reload.
* Afterwards, you must call SetImage or SetRectangle before doing any
* Recognize or Get* operation.
*/
public void clear() {
nativeClear();
}
/**
* Closes down tesseract and free up all memory. End() is equivalent to
* destructing and reconstructing your TessBaseAPI.
* <p>
* Once End() has been used, none of the other API functions may be used
* other than Init and anything declared above it in the class definition.
*/
public void end() {
nativeEnd();
}
/**
* Set the value of an internal "variable" (of either old or new types).
* Supply the name of the variable and the value as a string, just as you
* would in a config file.
* <p>
* Example: <code>setVariable(VAR_TESSEDIT_CHAR_BLACKLIST, "xyz"); to ignore x, y and z. * setVariable(VAR_BLN_NUMERICMODE, "1"); to set numeric-only mode. * </code>
* <p>
* setVariable() may be used before open(), but settings will revert to
* defaults on close().
*
* @param var name of the variable
* @param value value to set
* @return false if the name lookup failed
*/
public boolean setVariable(String var, String value) {
return nativeSetVariable(var, value);
}
/**
* Sets the page segmentation mode. This controls how much processing the
* OCR engine will perform before recognizing text.
*
* @param mode the page segmentation mode to set
*/
public void setPageSegMode(int mode) {
nativeSetPageSegMode(mode);
}
/**
* Sets debug mode. This controls how much information is displayed in the
* log during recognition.
*
* @param enabled <code>true</code> to enable debugging mode
*/
public void setDebug(boolean enabled) {
nativeSetDebug(enabled);
}
/**
* Restricts recognition to a sub-rectangle of the image. Call after
* SetImage. Each SetRectangle clears the recogntion results so multiple
* rectangles can be recognized with the same image.
*
* @param rect the bounding rectangle
*/
public void setRectangle(Rect rect) {
setRectangle(rect.left, rect.top, rect.width(), rect.height());
}
/**
* Restricts recognition to a sub-rectangle of the image. Call after
* SetImage. Each SetRectangle clears the recogntion results so multiple
* rectangles can be recognized with the same image.
*
* @param left the left bound
* @param top the right bound
* @param width the width of the bounding box
* @param height the height of the bounding box
*/
public void setRectangle(int left, int top, int width, int height) {
nativeSetRectangle(left, top, width, height);
}
/**
* Provides an image for Tesseract to recognize.
*
* @param file absolute path to the image file
*/
public void setImage(File file) {
Pix image = ReadFile.readFile(file);
if (image == null) {
throw new RuntimeException("Failed to read image file");
}
nativeSetImagePix(image.getNativePix());
}
/**
* Provides an image for Tesseract to recognize. Does not copy the image
* buffer. The source image must persist until after Recognize or
* GetUTF8Chars is called.
*
* @param bmp bitmap representation of the image
*/
public void setImage(Bitmap bmp) {
Pix image = ReadFile.readBitmap(bmp);
if (image == null) {
throw new RuntimeException("Failed to read bitmap");
}
nativeSetImagePix(image.getNativePix());
}
/**
* Provides a Leptonica pix format image for Tesseract to recognize. Clones
* the pix object. The source image may be destroyed immediately after
* SetImage is called, but its contents may not be modified.
*
* @param image Leptonica pix representation of the image
*/
public void setImage(Pix image) {
nativeSetImagePix(image.getNativePix());
}
/**
* Provides an image for Tesseract to recognize. Copies the image buffer.
* The source image may be destroyed immediately after SetImage is called.
* SetImage clears all recognition results, and sets the rectangle to the
* full image, so it may be followed immediately by a GetUTF8Text, and it
* will automatically perform recognition.
*
* @param imagedata byte representation of the image
* @param width image width
* @param height image height
* @param bpp bytes per pixel
* @param bpl bytes per line
*/
public void setImage(byte[] imagedata, int width, int height, int bpp, int bpl) {
nativeSetImageBytes(imagedata, width, height, bpp, bpl);
}
/**
* The recognized text is returned as a String which is coded as UTF8.
*
* @return the recognized text
*/
public String getUTF8Text() {
// Trim because the text will have extra line breaks at the end
String text = nativeGetUTF8Text();
return text.trim();
}
/**
* Returns the mean confidence of text recognition.
*
* @return the mean confidence
*/
public int meanConfidence() {
return nativeMeanConfidence();
}
/**
* Returns all word confidences (between 0 and 100) in an array. The number
* of confidences should correspond to the number of space-delimited words
* in GetUTF8Text().
*
* @return an array of word confidences (between 0 and 100) for each
* space-delimited word returned by GetUTF8Text()
*/
public int[] wordConfidences() {
int[] conf = nativeWordConfidences();
// We shouldn't return null confidences
if (conf == null)
conf = new int[0];
return conf;
}
// ******************
// * Native methods *
// ******************
/**
* Initializes static native data. Must be called on object load.
*/
private static native void nativeClassInit();
/**
* Initializes native data. Must be called on object construction.
*/
private native void nativeConstruct();
/**
* Finalizes native data. Must be called on object destruction.
*/
private native void nativeFinalize();
private native boolean nativeInit(String datapath, String language);
private native void nativeClear();
private native void nativeEnd();
private native void nativeSetImageBytes(
byte[] imagedata, int width, int height, int bpp, int bpl);
private native void nativeSetImagePix(int nativePix);
private native void nativeSetRectangle(int left, int top, int width, int height);
private native String nativeGetUTF8Text();
private native int nativeMeanConfidence();
private native int[] nativeWordConfidences();
private native boolean nativeSetVariable(String var, String value);
private native void nativeSetDebug(boolean debug);
private native void nativeSetPageSegMode(int mode);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
import android.graphics.Rect;
/**
* Java representation of a native Leptonica PIX object.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Pix {
static {
System.loadLibrary("lept");
}
/** Index of the image width within the dimensions array. */
public static final int INDEX_W = 0;
/** Index of the image height within the dimensions array. */
public static final int INDEX_H = 1;
/** Index of the image bit-depth within the dimensions array. */
public static final int INDEX_D = 2;
/** Package-accessible pointer to native pix */
final int mNativePix;
private boolean mRecycled;
/**
* Creates a new Pix wrapper for the specified native PIX object. Never call
* this twice on the same native pointer, because finalize() will attempt to
* free native memory twice.
*
* @param nativePix A pointer to the native PIX object.
*/
public Pix(int nativePix) {
mNativePix = nativePix;
mRecycled = false;
}
public Pix(int width, int height, int depth) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Pix width and height must be > 0");
} else if (depth != 1 && depth != 2 && depth != 4 && depth != 8 && depth != 16
&& depth != 24 && depth != 32) {
throw new IllegalArgumentException("Depth must be one of 1, 2, 4, 8, 16, or 32");
}
mNativePix = nativeCreatePix(width, height, depth);
mRecycled = false;
}
/**
* Returns a pointer to the native Pix object. This is used by native code
* and is only valid within the same process in which the Pix was created.
*
* @return a native pointer to the Pix object
*/
public int getNativePix() {
return mNativePix;
}
/**
* Return the raw bytes of the native PIX object. You can reconstruct the
* Pix from this data using createFromPix().
*
* @return a copy of this PIX object's raw data
*/
public byte[] getData() {
int size = nativeGetDataSize(mNativePix);
byte[] buffer = new byte[size];
if (!nativeGetData(mNativePix, buffer)) {
throw new RuntimeException("native getData failed");
}
return buffer;
}
/**
* Returns an array of this image's dimensions. See Pix.INDEX_* for indices.
*
* @return an array of this image's dimensions or <code>null</code> on
* failure
*/
public int[] getDimensions() {
int[] dimensions = new int[4];
if (getDimensions(dimensions)) {
return dimensions;
}
return null;
}
/**
* Fills an array with this image's dimensions. The array must be at least 3
* elements long.
*
* @param dimensions An integer array with at least three elements.
* @return <code>true</code> on success
*/
public boolean getDimensions(int[] dimensions) {
return nativeGetDimensions(mNativePix, dimensions);
}
/**
* Returns a clone of this Pix. This does NOT create a separate copy, just a
* new pointer that can be recycled without affecting other clones.
*
* @return a clone (shallow copy) of the Pix
*/
@Override
public Pix clone() {
int nativePix = nativeClone(mNativePix);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Returns a deep copy of this Pix that can be modified without affecting
* the original Pix.
*
* @return a copy of the Pix
*/
public Pix copy() {
int nativePix = nativeCopy(mNativePix);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Inverts this Pix in-place.
*
* @return <code>true</code> on success
*/
public boolean invert() {
return nativeInvert(mNativePix);
}
/**
* Releases resources and frees any memory associated with this Pix. You may
* not modify or access the pix after calling this method.
*/
public void recycle() {
if (!mRecycled) {
nativeDestroy(mNativePix);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
/**
* Creates a new Pix from raw Pix data obtained from getData().
*
* @param pixData Raw pix data obtained from getData().
* @param width The width of the original Pix.
* @param height The height of the original Pix.
* @param depth The bit-depth of the original Pix.
* @return a new Pix or <code>null</code> on error
*/
public static Pix createFromPix(byte[] pixData, int width, int height, int depth) {
int nativePix = nativeCreateFromData(pixData, width, height, depth);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
/**
* Returns a Rect with the width and height of this Pix.
*
* @return a Rect with the width and height of this Pix
*/
public Rect getRect() {
int w = getWidth();
int h = getHeight();
return new Rect(0, 0, w, h);
}
/**
* Returns the width of this Pix.
*
* @return the width of this Pix
*/
public int getWidth() {
return nativeGetWidth(mNativePix);
}
/**
* Returns the height of this Pix.
*
* @return the height of this Pix
*/
public int getHeight() {
return nativeGetHeight(mNativePix);
}
/**
* Returns the depth of this Pix.
*
* @return the depth of this Pix
*/
public int getDepth() {
return nativeGetDepth(mNativePix);
}
/**
* Returns the {@link android.graphics.Color} at the specified location.
*
* @param x The x coordinate (0...width-1) of the pixel to return.
* @param y The y coordinate (0...height-1) of the pixel to return.
* @return The argb {@link android.graphics.Color} at the specified
* coordinate.
* @throws IllegalArgumentException If x, y exceeds the image bounds.
*/
public int getPixel(int x, int y) {
if (x < 0 || x >= getWidth()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
} else if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
}
return nativeGetPixel(mNativePix, x, y);
}
/**
* Sets the {@link android.graphics.Color} at the specified location.
*
* @param x The x coordinate (0...width-1) of the pixel to set.
* @param y The y coordinate (0...height-1) of the pixel to set.
* @param color The argb {@link android.graphics.Color} to set at the
* specified coordinate.
* @throws IllegalArgumentException If x, y exceeds the image bounds.
*/
public void setPixel(int x, int y, int color) {
if (x < 0 || x >= getWidth()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
} else if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Supplied x coordinate exceeds image bounds");
}
nativeSetPixel(mNativePix, x, y, color);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreatePix(int w, int h, int d);
private static native int nativeCreateFromData(byte[] data, int w, int h, int d);
private static native boolean nativeGetData(int nativePix, byte[] data);
private static native int nativeGetDataSize(int nativePix);
private static native int nativeClone(int nativePix);
private static native int nativeCopy(int nativePix);
private static native boolean nativeInvert(int nativePix);
private static native void nativeDestroy(int nativePix);
private static native boolean nativeGetDimensions(int nativePix, int[] dimensions);
private static native int nativeGetWidth(int nativePix);
private static native int nativeGetHeight(int nativePix);
private static native int nativeGetDepth(int nativePix);
private static native int nativeGetPixel(int nativePix, int x, int y);
private static native void nativeSetPixel(int nativePix, int x, int y, int color);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
/**
* Image input and output methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class ReadFile {
static {
System.loadLibrary("lept");
}
/**
* Creates a 32bpp Pix object from encoded data. Supported formats are BMP
* and JPEG.
*
* @param encodedData JPEG or BMP encoded byte data.
* @return a 32bpp Pix object
*/
public static Pix readMem(byte[] encodedData) {
if (encodedData == null)
throw new IllegalArgumentException("Image data byte array must be non-null");
final BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
final Bitmap bmp = BitmapFactory.decodeByteArray(encodedData, 0, encodedData.length,
opts);
final Pix pix = readBitmap(bmp);
bmp.recycle();
return pix;
}
/**
* Creates an 8bpp Pix object from raw 8bpp grayscale pixels.
*
* @param pixelData 8bpp grayscale pixel data.
* @param width The width of the input image.
* @param height The height of the input image.
* @return an 8bpp Pix object
*/
public static Pix readBytes8(byte[] pixelData, int width, int height) {
if (pixelData == null)
throw new IllegalArgumentException("Byte array must be non-null");
if (width <= 0)
throw new IllegalArgumentException("Image width must be greater than 0");
if (height <= 0)
throw new IllegalArgumentException("Image height must be greater than 0");
if (pixelData.length < width * height)
throw new IllegalArgumentException("Array length does not match dimensions");
int nativePix = nativeReadBytes8(pixelData, width, height);
if (nativePix == 0)
throw new RuntimeException("Failed to read pix from memory");
return new Pix(nativePix);
}
/**
* Replaces the bytes in an 8bpp Pix object with raw grayscale 8bpp pixels.
* Width and height be identical to the input Pix.
*
* @param pixs The Pix whose bytes will be replaced.
* @param pixelData 8bpp grayscale pixel data.
* @param width The width of the input image.
* @param height The height of the input image.
* @return an 8bpp Pix object
*/
public static boolean replaceBytes8(Pix pixs, byte[] pixelData, int width, int height) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (pixelData == null)
throw new IllegalArgumentException("Byte array must be non-null");
if (width <= 0)
throw new IllegalArgumentException("Image width must be greater than 0");
if (height <= 0)
throw new IllegalArgumentException("Image height must be greater than 0");
if (pixelData.length < width * height)
throw new IllegalArgumentException("Array length does not match dimensions");
if (pixs.getWidth() != width)
throw new IllegalArgumentException("Source pix width does not match image width");
if (pixs.getHeight() != height)
throw new IllegalArgumentException("Source pix width does not match image width");
return nativeReplaceBytes8(pixs.mNativePix, pixelData, width, height);
}
/**
* Creates a Pixa object from encoded files in a directory. Supported
* formats are BMP and JPEG.
*
* @param dir The directory containing the files.
* @param prefix The prefix of the files to load into a Pixa.
* @return a Pixa object containing one Pix for each file
*/
public static Pixa readFiles(File dir, String prefix) {
if (dir == null)
throw new IllegalArgumentException("Directory must be non-null");
if (!dir.exists())
throw new IllegalArgumentException("Directory does not exist");
if (!dir.canRead())
throw new IllegalArgumentException("Cannot read directory");
// TODO: Remove or fix this.
throw new RuntimeException("readFiles() is not current supported");
}
/**
* Creates a Pix object from encoded file data. Supported formats are BMP
* and JPEG.
*
* @param file The JPEG or BMP-encoded file to read in as a Pix.
* @return a Pix object
*/
public static Pix readFile(File file) {
if (file == null)
throw new IllegalArgumentException("File must be non-null");
if (!file.exists())
throw new IllegalArgumentException("File does not exist");
if (!file.canRead())
throw new IllegalArgumentException("Cannot read file");
final BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
final Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
final Pix pix = readBitmap(bmp);
bmp.recycle();
return pix;
}
/**
* Creates a Pix object from Bitmap data. Currently supports only
* ARGB_8888-formatted bitmaps.
*
* @param bmp The Bitmap object to convert to a Pix.
* @return a Pix object
*/
public static Pix readBitmap(Bitmap bmp) {
if (bmp == null)
throw new IllegalArgumentException("Bitmap must be non-null");
if (bmp.getConfig() != Bitmap.Config.ARGB_8888)
throw new IllegalArgumentException("Bitmap config must be ARGB_8888");
int nativePix = nativeReadBitmap(bmp);
if (nativePix == 0)
throw new RuntimeException("Failed to read pix from bitmap");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeReadMem(byte[] data, int size);
private static native int nativeReadBytes8(byte[] data, int w, int h);
private static native boolean nativeReplaceBytes8(int nativePix, byte[] data, int w, int h);
private static native int nativeReadFiles(String dirname, String prefix);
private static native int nativeReadFile(String filename);
private static native int nativeReadBitmap(Bitmap bitmap);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Wrapper for Leptonica's native BOX.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Box {
static {
System.loadLibrary("lept");
}
/** The index of the X coordinate within the geometry array. */
public static final int INDEX_X = 0;
/** The index of the Y coordinate within the geometry array. */
public static final int INDEX_Y = 1;
/** The index of the width within the geometry array. */
public static final int INDEX_W = 2;
/** The index of the height within the geometry array. */
public static final int INDEX_H = 3;
/**
* A pointer to the native Box object. This is used internally by native
* code.
*/
final int mNativeBox;
private boolean mRecycled = false;
/**
* Creates a new Box wrapper for the specified native BOX.
*
* @param nativeBox A pointer to the native BOX.
*/
Box(int nativeBox) {
mNativeBox = nativeBox;
mRecycled = false;
}
/**
* Creates a box with the specified geometry. All dimensions should be
* non-negative and specified in pixels.
*
* @param x X-coordinate of the top-left corner of the box.
* @param y Y-coordinate of the top-left corner of the box.
* @param w Width of the box.
* @param h Height of the box.
*/
public Box(int x, int y, int w, int h) {
if (x < 0 || y < 0 || w < 0 || h < 0) {
throw new IllegalArgumentException("All box dimensions must be non-negative");
}
int nativeBox = nativeCreate(x, y, w, h);
if (nativeBox == 0) {
throw new OutOfMemoryError();
}
mNativeBox = nativeBox;
mRecycled = false;
}
/**
* Returns the box's x-coordinate in pixels.
*
* @return The box's x-coordinate in pixels.
*/
public int getX() {
return nativeGetX(mNativeBox);
}
/**
* Returns the box's y-coordinate in pixels.
*
* @return The box's y-coordinate in pixels.
*/
public int getY() {
return nativeGetY(mNativeBox);
}
/**
* Returns the box's width in pixels.
*
* @return The box's width in pixels.
*/
public int getWidth() {
return nativeGetWidth(mNativeBox);
}
/**
* Returns the box's height in pixels.
*
* @return The box's height in pixels.
*/
public int getHeight() {
return nativeGetHeight(mNativeBox);
}
/**
* Returns an array containing the coordinates of this box. See INDEX_*
* constants for indices.
*
* @return an array of box oordinates
*/
public int[] getGeometry() {
int[] geometry = new int[4];
if (getGeometry(geometry)) {
return geometry;
}
return null;
}
/**
* Fills an array containing the coordinates of this box. See INDEX_*
* constants for indices.
*
* @param geometry A 4+ element integer array to fill with coordinates.
* @return <code>true</code> on success
*/
public boolean getGeometry(int[] geometry) {
if (geometry.length < 4) {
throw new IllegalArgumentException("Geometry array must be at least 4 elements long");
}
return nativeGetGeometry(mNativeBox, geometry);
}
/**
* Releases resources and frees any memory associated with this Box.
*/
public void recycle() {
if (!mRecycled) {
nativeDestroy(mNativeBox);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreate(int x, int y, int w, int h);
private static native int nativeGetX(int nativeBox);
private static native int nativeGetY(int nativeBox);
private static native int nativeGetWidth(int nativeBox);
private static native int nativeGetHeight(int nativeBox);
private static native void nativeDestroy(int nativeBox);
private static native boolean nativeGetGeometry(int nativeBox, int[] geometry);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image bit-depth conversion methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Convert {
static {
System.loadLibrary("lept");
}
/**
* Converts an image of any bit depth to 8-bit grayscale.
*
* @param pixs Source pix of any bit-depth.
* @return a new Pix image or <code>null</code> on error
*/
public static Pix convertTo8(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeConvertTo8(pixs.mNativePix);
if (nativePix == 0)
throw new RuntimeException("Failed to natively convert pix");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeConvertTo8(int nativePix);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
import android.graphics.Rect;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Java representation of a native PIXA object. This object contains multiple
* PIX objects and their associated bounding BOX objects.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Pixa implements Iterable<Pix> {
static {
System.loadLibrary("lept");
}
/** A pointer to the native PIXA object. This is used internally by native code. */
final int mNativePixa;
/** The specified width of this Pixa. */
final int mWidth;
/** The specified height of this Pixa. */
final int mHeight;
private boolean mRecycled;
/**
* Creates a new Pixa with the specified minimum capacity. The Pixa will
* expand automatically as new Pix are added.
*
* @param size The minimum capacity of this Pixa.
* @return a new Pixa or <code>null</code> on error
*/
public static Pixa createPixa(int size) {
return createPixa(size, 0, 0);
}
/**
* Creates a new Pixa with the specified minimum capacity. The Pixa will
* expand automatically as new Pix are added.
* <p>
* If non-zero, the specified width and height will be used to specify the
* bounds of output images. *
*
* @param size The minimum capacity of this Pixa.
* @param width (Optional) The width of this Pixa, use 0 for default.
* @param height (Optional) The height of this Pixa, use 0 for default.
* @return a new Pixa or <code>null</code> on error
*/
public static Pixa createPixa(int size, int width, int height) {
int nativePixa = nativeCreate(size);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, width, height);
}
/**
* Creates a wrapper for the specified native Pixa pointer.
*
* @param nativePixa Native pointer to a PIXA object.
* @param width The width of the PIXA.
* @param height The height of the PIXA.
*/
public Pixa(int nativePixa, int width, int height) {
mNativePixa = nativePixa;
mWidth = width;
mHeight = height;
mRecycled = false;
}
/**
* Returns a pointer to the native PIXA object. This is used by native code.
*
* @return a pointer to the native PIXA object
*/
public int getNativePixa() {
return mNativePixa;
}
/**
* Creates a shallow copy of this Pixa. Contained Pix are cloned, and the
* resulting Pixa may be recycled separately from the original.
*
* @return a shallow copy of this Pixa
*/
public Pixa copy() {
int nativePixa = nativeCopy(mNativePixa);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, mWidth, mHeight);
}
/**
* Sorts this Pixa using the specified field and order. See
* Constants.L_SORT_BY_* and Constants.L_SORT_INCREASING or
* Constants.L_SORT_DECREASING.
*
* @param field The field to sort by. See Constants.L_SORT_BY_*.
* @param order The order in which to sort. Must be either
* Constants.L_SORT_INCREASING or Constants.L_SORT_DECREASING.
* @return a sorted copy of this Pixa
*/
public Pixa sort(int field, int order) {
int nativePixa = nativeSort(mNativePixa, field, order);
if (nativePixa == 0) {
throw new OutOfMemoryError();
}
return new Pixa(nativePixa, mWidth, mHeight);
}
/**
* Returns the number of elements in this Pixa.
*
* @return the number of elements in this Pixa
*/
public int size() {
return nativeGetCount(mNativePixa);
}
/**
* Recycles this Pixa and frees natively allocated memory. You may not
* access or modify the Pixa after calling this method.
* <p>
* Any Pix obtained from this Pixa or copies of this Pixa will still be
* accessible until they are explicitly recycled or finalized by the garbage
* collector.
*/
public synchronized void recycle() {
if (!mRecycled) {
nativeDestroy(mNativePixa);
mRecycled = true;
}
}
@Override
protected void finalize() throws Throwable {
recycle();
super.finalize();
}
/**
* Merges the contents of another Pixa into this one.
*
* @param otherPixa
* @return <code>true</code> on success
*/
public boolean join(Pixa otherPixa) {
return nativeJoin(mNativePixa, otherPixa.mNativePixa);
}
/**
* Adds a Pix to this Pixa.
*
* @param pix The Pix to add.
* @param mode The mode in which to add this Pix, typically
* Constants.L_CLONE.
*/
public void addPix(Pix pix, int mode) {
nativeAddPix(mNativePixa, pix.mNativePix, mode);
}
/**
* Adds a Box to this Pixa.
*
* @param box The Box to add.
* @param mode The mode in which to add this Box, typically
* Constants.L_CLONE.
*/
public void addBox(Box box, int mode) {
nativeAddBox(mNativePixa, box.mNativeBox, mode);
}
/**
* Adds a Pix and associated Box to this Pixa.
*
* @param pix The Pix to add.
* @param box The Box to add.
* @param mode The mode in which to add this Pix and Box, typically
* Constants.L_CLONE.
*/
public void add(Pix pix, Box box, int mode) {
nativeAdd(mNativePixa, pix.mNativePix, box.mNativeBox, mode);
}
/**
* Returns the Box at the specified index, or <code>null</code> on error.
*
* @param index The index of the Box to return.
* @return the Box at the specified index, or <code>null</code> on error
*/
public Box getBox(int index) {
int nativeBox = nativeGetBox(mNativePixa, index);
if (nativeBox == 0) {
return null;
}
return new Box(nativeBox);
}
/**
* Returns the Pix at the specified index, or <code>null</code> on error.
*
* @param index The index of the Pix to return.
* @return the Pix at the specified index, or <code>null</code> on error
*/
public Pix getPix(int index) {
int nativePix = nativeGetPix(mNativePixa, index);
if (nativePix == 0) {
return null;
}
return new Pix(nativePix);
}
/**
* Returns the width of this Pixa, or 0 if one was not set when it was
* created.
*
* @return the width of this Pixa, or 0 if one was not set when it was
* created
*/
public int getWidth() {
return mWidth;
}
/**
* Returns the height of this Pixa, or 0 if one was not set when it was
* created.
*
* @return the height of this Pixa, or 0 if one was not set when it was
* created
*/
public int getHeight() {
return mHeight;
}
/**
* Returns a bounding Rect for this Pixa, which may be (0,0,0,0) if width
* and height were not specified on creation.
*
* @return a bounding Rect for this Pixa
*/
public Rect getRect() {
return new Rect(0, 0, mWidth, mHeight);
}
/**
* Returns a bounding Rect for the Box at the specified index.
*
* @param index The index of the Box to get the bounding Rect of.
* @return a bounding Rect for the Box at the specified index
*/
public Rect getBoxRect(int index) {
int[] dimensions = getBoxGeometry(index);
if (dimensions == null) {
return null;
}
int x = dimensions[Box.INDEX_X];
int y = dimensions[Box.INDEX_Y];
int w = dimensions[Box.INDEX_W];
int h = dimensions[Box.INDEX_H];
Rect bound = new Rect(x, y, x + w, y + h);
return bound;
}
/**
* Returns a geometry array for the Box at the specified index. See
* Box.INDEX_* for indices.
*
* @param index The index of the Box to get the geometry of.
* @return a bounding Rect for the Box at the specified index
*/
public int[] getBoxGeometry(int index) {
int[] dimensions = new int[4];
if (getBoxGeometry(index, dimensions)) {
return dimensions;
}
return null;
}
/**
* Fills an array with the geometry of the Box at the specified index. See
* Box.INDEX_* for indices.
*
* @param index The index of the Box to get the geometry of.
* @param dimensions The array to fill with Box geometry. Must be at least 4
* elements.
* @return <code>true</code> on success
*/
public boolean getBoxGeometry(int index, int[] dimensions) {
return nativeGetBoxGeometry(mNativePixa, index, dimensions);
}
/**
* Returns an ArrayList of Box bounding Rects.
*
* @return an ArrayList of Box bounding Rects
*/
public ArrayList<Rect> getBoxRects() {
final int pixaCount = nativeGetCount(mNativePixa);
final int[] buffer = new int[4];
final ArrayList<Rect> rects = new ArrayList<Rect>(pixaCount);
for (int i = 0; i < pixaCount; i++) {
getBoxGeometry(i, buffer);
final int x = buffer[Box.INDEX_X];
final int y = buffer[Box.INDEX_Y];
final Rect bound = new Rect(x, y, x + buffer[Box.INDEX_W], y + buffer[Box.INDEX_H]);
rects.add(bound);
}
return rects;
}
/**
* Replaces the Pix and Box at the specified index with the specified Pix
* and Box, both of which may be recycled after calling this method.
*
* @param index The index of the Pix to replace.
* @param pix The Pix to replace the existing Pix.
* @param box The Box to replace the existing Box.
*/
public void replacePix(int index, Pix pix, Box box) {
nativeReplacePix(mNativePixa, index, pix.mNativePix, box.mNativeBox);
}
/**
* Merges the Pix at the specified indices and removes the Pix at the second
* index.
*
* @param indexA The index of the first Pix.
* @param indexB The index of the second Pix, which will be removed after
* merging.
*/
public void mergeAndReplacePix(int indexA, int indexB) {
nativeMergeAndReplacePix(mNativePixa, indexA, indexB);
}
/**
* Writes the components of this Pix to a bitmap-formatted file using a
* random color map.
*
* @param file The file to write to.
* @return <code>true</code> on success
*/
public boolean writeToFileRandomCmap(File file) {
return nativeWriteToFileRandomCmap(mNativePixa, file.getAbsolutePath(), mWidth, mHeight);
}
@Override
public Iterator<Pix> iterator() {
return new PixIterator();
}
private class PixIterator implements Iterator<Pix> {
private int mIndex;
private PixIterator() {
mIndex = 0;
}
@Override
public boolean hasNext() {
final int size = size();
return (size > 0 && mIndex < size);
}
@Override
public Pix next() {
return getPix(mIndex++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeCreate(int size);
private static native int nativeCopy(int nativePixa);
private static native int nativeSort(int nativePixa, int field, int order);
private static native boolean nativeJoin(int nativePixa, int otherPixa);
private static native int nativeGetCount(int nativePixa);
private static native void nativeDestroy(int nativePixa);
private static native void nativeAddPix(int nativePixa, int nativePix, int mode);
private static native void nativeAddBox(int nativePixa, int nativeBox, int mode);
private static native void nativeAdd(int nativePixa, int nativePix, int nativeBox, int mode);
private static native boolean nativeWriteToFileRandomCmap(
int nativePixa, String fileName, int width, int height);
private static native void nativeReplacePix(
int nativePixa, int index, int nativePix, int nativeBox);
private static native void nativeMergeAndReplacePix(int nativePixa, int indexA, int indexB);
private static native int nativeGetBox(int nativePix, int index);
private static native int nativeGetPix(int nativePix, int index);
private static native boolean nativeGetBoxGeometry(int nativePixa, int index, int[] dimensions);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
import android.graphics.Bitmap;
import java.io.File;
/**
* @author alanv@google.com (Alan Viverette)
*/
public class WriteFile {
static {
System.loadLibrary("lept");
}
/* Default JPEG quality */
public static final int DEFAULT_QUALITY = 85;
/* Default JPEG progressive encoding */
public static final boolean DEFAULT_PROGRESSIVE = true;
/**
* Write an 8bpp Pix to a flat byte array.
*
* @param pixs The 8bpp source image.
* @return a byte array where each byte represents a single 8-bit pixel
*/
public static byte[] writeBytes8(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int size = pixs.getWidth() * pixs.getHeight();
if (pixs.getDepth() != 8) {
Pix pix8 = Convert.convertTo8(pixs);
pixs.recycle();
pixs = pix8;
}
byte[] data = new byte[size];
writeBytes8(pixs, data);
return data;
}
/**
* Write an 8bpp Pix to a flat byte array.
*
* @param pixs The 8bpp source image.
* @param data A byte array large enough to hold the pixels of pixs.
* @return the number of bytes written to data
*/
public static int writeBytes8(Pix pixs, byte[] data) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int size = pixs.getWidth() * pixs.getHeight();
if (data.length < size)
throw new IllegalArgumentException("Data array must be large enough to hold image bytes");
int bytesWritten = nativeWriteBytes8(pixs.mNativePix, data);
return bytesWritten;
}
/**
* Writes all the images in a Pixa array to individual files using the
* specified format. The output file extension will be determined by the
* format.
* <p>
* Output file names will take the format <path>/<prefix><index>.<extension>
*
* @param pixas The source Pixa image array.
* @param path The output directory.
* @param prefix The prefix to give output files.
* @param format The format to use for output files.
* @return <code>true</code> on success
*/
public static boolean writeFiles(Pixa pixas, File path, String prefix, int format) {
if (pixas == null)
throw new IllegalArgumentException("Source pixa must be non-null");
if (path == null)
throw new IllegalArgumentException("Destination path non-null");
if (prefix == null)
throw new IllegalArgumentException("Filename prefix must be non-null");
String rootname = new File(path, prefix).getAbsolutePath();
throw new RuntimeException("writeFiles() is not currently supported");
}
/**
* Write a Pix to a byte array using the specified encoding from
* Constants.IFF_*.
*
* @param pixs The source image.
* @param format A format from Constants.IFF_*.
* @return a byte array containing encoded bytes
*/
public static byte[] writeMem(Pix pixs, int format) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
return nativeWriteMem(pixs.mNativePix, format);
}
/**
* Writes a Pix to file using the file extension as the output format;
* supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap.
* <p>
* Uses default quality and progressive encoding settings.
*
* @param pixs Source image.
* @param file The file to write.
* @return <code>true</code> on success
*/
public static boolean writeImpliedFormat(Pix pixs, File file) {
return writeImpliedFormat(pixs, file, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE);
}
/**
* Writes a Pix to file using the file extension as the output format;
* supported formats are .jpg or .jpeg for JPEG and .bmp for bitmap.
* <p>
* Notes:
* <ol>
* <li>This determines the output format from the filename extension.
* <li>The last two args are ignored except for requests for jpeg files.
* <li>The jpeg default quality is 75.
* </ol>
*
* @param pixs Source image.
* @param file The file to write.
* @param quality (Only for lossy formats) Quality between 1 - 100, 0 for
* default.
* @param progressive (Only for JPEG) Whether to encode as progressive.
* @return <code>true</code> on success
*/
public static boolean writeImpliedFormat(
Pix pixs, File file, int quality, boolean progressive) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (file == null)
throw new IllegalArgumentException("File must be non-null");
return nativeWriteImpliedFormat(
pixs.mNativePix, file.getAbsolutePath(), quality, progressive);
}
/**
* Writes a Pix to an Android Bitmap object. The output Bitmap will always
* be in ARGB_8888 format, but the input Pixs may be any bit-depth.
*
* @param pixs The source image.
* @return a Bitmap containing a copy of the source image, or <code>null
* </code> on failure
*/
public static Bitmap writeBitmap(Pix pixs) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
final int[] dimensions = pixs.getDimensions();
final int width = dimensions[Pix.INDEX_W];
final int height = dimensions[Pix.INDEX_H];
//final int depth = dimensions[Pix.INDEX_D];
final Bitmap.Config config = Bitmap.Config.ARGB_8888;
final Bitmap bitmap = Bitmap.createBitmap(width, height, config);
if (nativeWriteBitmap(pixs.mNativePix, bitmap)) {
return bitmap;
}
bitmap.recycle();
return null;
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeWriteBytes8(int nativePix, byte[] data);
private static native boolean nativeWriteFiles(int nativePix, String rootname, int format);
private static native byte[] nativeWriteMem(int nativePix, int format);
private static native boolean nativeWriteImpliedFormat(
int nativePix, String fileName, int quality, boolean progressive);
private static native boolean nativeWriteBitmap(int nativePix, Bitmap bitmap);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image binarization methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Binarize {
static {
System.loadLibrary("lept");
}
// Otsu thresholding constants
/** Desired tile X dimension; actual size may vary */
public final static int OTSU_SIZE_X = 32;
/** Desired tile Y dimension; actual size may vary */
public final static int OTSU_SIZE_Y = 32;
/** Desired X smoothing value */
public final static int OTSU_SMOOTH_X = 2;
/** Desired Y smoothing value */
public final static int OTSU_SMOOTH_Y = 2;
/** Fraction of the max Otsu score, typically 0.1 */
public final static float OTSU_SCORE_FRACTION = 0.1f;
/**
* Performs locally-adaptive Otsu threshold binarization with default
* parameters.
*
* @param pixs An 8 bpp PIX source image.
* @return A 1 bpp thresholded PIX image.
*/
public static Pix otsuAdaptiveThreshold(Pix pixs) {
return otsuAdaptiveThreshold(
pixs, OTSU_SIZE_X, OTSU_SIZE_Y, OTSU_SMOOTH_X, OTSU_SMOOTH_Y, OTSU_SCORE_FRACTION);
}
/**
* Performs locally-adaptive Otsu threshold binarization.
* <p>
* Notes:
* <ol>
* <li>The Otsu method finds a single global threshold for an image. This
* function allows a locally adapted threshold to be found for each tile
* into which the image is broken up.
* <li>The array of threshold values, one for each tile, constitutes a
* highly downscaled image. This array is optionally smoothed using a
* convolution. The full width and height of the convolution kernel are (2 *
* smoothX + 1) and (2 * smoothY + 1).
* <li>The minimum tile dimension allowed is 16. If such small tiles are
* used, it is recommended to use smoothing, because without smoothing, each
* small tile determines the splitting threshold independently. A tile that
* is entirely in the image bg will then hallucinate fg, resulting in a very
* noisy binarization. The smoothing should be large enough that no tile is
* only influenced by one type (fg or bg) of pixels, because it will force a
* split of its pixels.
* <li>To get a single global threshold for the entire image, use input
* values of sizeX and sizeY that are larger than the image. For this
* situation, the smoothing parameters are ignored.
* <li>The threshold values partition the image pixels into two classes: one
* whose values are less than the threshold and another whose values are
* greater than or equal to the threshold. This is the same use of
* 'threshold' as in pixThresholdToBinary().
* <li>The scorefract is the fraction of the maximum Otsu score, which is
* used to determine the range over which the histogram minimum is searched.
* See numaSplitDistribution() for details on the underlying method of
* choosing a threshold.
* <li>This uses enables a modified version of the Otsu criterion for
* splitting the distribution of pixels in each tile into a fg and bg part.
* The modification consists of searching for a minimum in the histogram
* over a range of pixel values where the Otsu score is within a defined
* fraction, scoreFraction, of the max score. To get the original Otsu
* algorithm, set scoreFraction == 0.
* </ol>
*
* @param pixs An 8 bpp PIX source image.
* @param sizeX Desired tile X dimension; actual size may vary.
* @param sizeY Desired tile Y dimension; actual size may vary.
* @param smoothX Half-width of convolution kernel applied to threshold
* array: use 0 for no smoothing.
* @param smoothY Half-height of convolution kernel applied to threshold
* array: use 0 for no smoothing.
* @param scoreFraction Fraction of the max Otsu score; typ. 0.1 (use 0.0
* for standard Otsu).
* @return A 1 bpp thresholded PIX image.
*/
public static Pix otsuAdaptiveThreshold(
Pix pixs, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFraction) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (pixs.getDepth() != 8)
throw new IllegalArgumentException("Source pix depth must be 8bpp");
int nativePix = nativeOtsuAdaptiveThreshold(
pixs.mNativePix, sizeX, sizeY, smoothX, smoothY, scoreFraction);
if (nativePix == 0)
throw new RuntimeException("Failed to perform Otsu adaptive threshold on image");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeOtsuAdaptiveThreshold(
int nativePix, int sizeX, int sizeY, int smoothX, int smoothY, float scoreFract);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* @author alanv@google.com (Alan Viverette)
*/
public class Rotate {
static {
System.loadLibrary("lept");
}
// Rotation default
/** Default rotation quality is high. */
public static final boolean ROTATE_QUALITY = true;
/**
* Performs rotation using the default parameters.
*
* @param pixs The source pix.
* @param degrees The number of degrees to rotate; clockwise is positive.
* @return the rotated source image
*/
public static Pix rotate(Pix pixs, float degrees) {
return rotate(pixs, degrees, false);
}
/**
* Performs basic image rotation about the center.
* <p>
* Notes:
* <ol>
* <li>Rotation is about the center of the image.
* <li>For very small rotations, just return a clone.
* <li>Rotation brings either white or black pixels in from outside the
* image.
* <li>Above 20 degrees, if rotation by shear is requested, we rotate by
* sampling.
* <li>Colormaps are removed for rotation by area map and shear.
* <li>The dest can be expanded so that no image pixels are lost. To invoke
* expansion, input the original width and height. For repeated rotation,
* use of the original width and height allows the expansion to stop at the
* maximum required size, which is a square with side = sqrt(w*w + h*h).
* </ol>
*
* @param pixs The source pix.
* @param degrees The number of degrees to rotate; clockwise is positive.
* @param quality Whether to use high-quality rotation.
* @return the rotated source image
*/
public static Pix rotate(Pix pixs, float degrees, boolean quality) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeRotate(pixs.mNativePix, degrees, quality);
if (nativePix == 0)
return null;
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeRotate(int nativePix, float degrees, boolean quality);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image rotation and skew detection methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Skew {
static {
System.loadLibrary("lept");
}
// Text alignment defaults
/** Default range for sweep, will detect rotation of + or - 30 degrees. */
public final static float SWEEP_RANGE = 30.0f;
/** Default sweep delta, reasonably accurate within 0.05 degrees. */
public final static float SWEEP_DELTA = 5.0f;
/** Default sweep reduction, one-eighth the size of the original image. */
public final static int SWEEP_REDUCTION = 8;
/** Default sweep reduction, one-fourth the size of the original image. */
public final static int SEARCH_REDUCTION = 4;
/** Default search minimum delta, reasonably accurate within 0.05 degrees. */
public final static float SEARCH_MIN_DELTA = 0.01f;
/**
* Finds and returns the skew angle using default parameters.
*
* @param pixs Input pix (1 bpp).
* @return the detected skew angle, or 0.0 on failure
*/
public static float findSkew(Pix pixs) {
return findSkew(pixs, SWEEP_RANGE, SWEEP_DELTA, SWEEP_REDUCTION, SEARCH_REDUCTION,
SEARCH_MIN_DELTA);
}
/**
* Finds and returns the skew angle, doing first a sweep through a set of
* equal angles, and then doing a binary search until convergence.
* <p>
* Notes:
* <ol>
* <li>In computing the differential line sum variance score, we sum the
* result over scanlines, but we always skip:
* <ul>
* <li>at least one scanline
* <li>not more than 10% of the image height
* <li>not more than 5% of the image width
* </ul>
* </ol>
*
* @param pixs Input pix (1 bpp).
* @param sweepRange Half the full search range, assumed about 0; in
* degrees.
* @param sweepDelta Angle increment of sweep; in degrees.
* @param sweepReduction Sweep reduction factor = 1, 2, 4 or 8.
* @param searchReduction Binary search reduction factor = 1, 2, 4 or 8; and
* must not exceed redsweep.
* @param searchMinDelta Minimum binary search increment angle; in degrees.
* @return the detected skew angle, or 0.0 on failure
*/
public static float findSkew(Pix pixs, float sweepRange, float sweepDelta, int sweepReduction,
int searchReduction, float searchMinDelta) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
return nativeFindSkew(pixs.mNativePix, sweepRange, sweepDelta, sweepReduction,
searchReduction, searchMinDelta);
}
// ***************
// * NATIVE CODE *
// ***************
private static native float nativeFindSkew(int nativePix, float sweepRange, float sweepDelta,
int sweepReduction, int searchReduction, float searchMinDelta);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image adaptive mapping methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class AdaptiveMap {
static {
System.loadLibrary("lept");
}
// Background normalization constants
/** Image reduction value; possible values are 1, 2, 4, 8 */
private final static int NORM_REDUCTION = 16;
/** Desired tile size; actual size may vary */
private final static int NORM_SIZE = 3;
/** Background brightness value; values over 200 may result in clipping */
private final static int NORM_BG_VALUE = 200;
/**
* Normalizes an image's background using default parameters.
*
* @param pixs A source pix image.
* @return the source pix image with a normalized background
*/
public static Pix backgroundNormMorph(Pix pixs) {
return backgroundNormMorph(pixs, NORM_REDUCTION, NORM_SIZE, NORM_BG_VALUE);
}
/**
* Normalizes an image's background to a specified value.
* <p>
* Notes:
* <ol>
* <li>This is a top-level interface for normalizing the image intensity by
* mapping the image so that the background is near the input value 'bgval'.
* <li>The input image is either grayscale or rgb.
* <li>For each component in the input image, the background value is
* estimated using a grayscale closing; hence the 'Morph' in the function
* name.
* <li>An optional binary mask can be specified, with the foreground pixels
* typically over image regions. The resulting background map values will be
* determined by surrounding pixels that are not under the mask foreground.
* The origin (0,0) of this mask is assumed to be aligned with the origin of
* the input image. This binary mask must not fully cover pixs, because then
* there will be no pixels in the input image available to compute the
* background.
* <li>The map is computed at reduced size (given by 'reduction') from the
* input pixs and optional pixim. At this scale, pixs is closed to remove
* the background, using a square Sel of odd dimension. The product of
* reduction * size should be large enough to remove most of the text
* foreground.
* <li>No convolutional smoothing needs to be done on the map before
* inverting it.
* <li>A 'bgval' target background value for the normalized image. This
* should be at least 128. If set too close to 255, some clipping will occur
* in the result.
* </ol>
*
* @param pixs A source pix image.
* @param normReduction Reduction at which morphological closings are done.
* @param normSize Size of square Sel for the closing.
* @param normBgValue Target background value.
* @return the source pix image with a normalized background
*/
public static Pix backgroundNormMorph(
Pix pixs, int normReduction, int normSize, int normBgValue) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeBackgroundNormMorph(
pixs.mNativePix, normReduction, normSize, normBgValue);
if (nativePix == 0)
throw new RuntimeException("Failed to normalize image background");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeBackgroundNormMorph(
int nativePix, int reduction, int size, int bgval);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image sharpening methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Enhance {
static {
System.loadLibrary("lept");
}
/**
* Performs unsharp masking (edge enhancement).
* <p>
* Notes:
* <ul>
* <li>We use symmetric smoothing filters of odd dimension, typically use
* sizes of 3, 5, 7, etc. The <code>halfwidth</code> parameter for these is
* (size - 1)/2; i.e., 1, 2, 3, etc.</li>
* <li>The <code>fract</code> parameter is typically taken in the range: 0.2
* < <code>fract</code> < 0.7</li>
* </ul>
*
* @param halfwidth The half-width of the smoothing filter.
* @param fraction The fraction of edge to be added back into the source
* image.
* @return an edge-enhanced Pix image or copy if no enhancement requested
*/
public static Pix unsharpMasking(Pix pixs, int halfwidth, float fraction) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int nativePix = nativeUnsharpMasking(pixs.mNativePix, halfwidth, fraction);
if (nativePix == 0) {
throw new OutOfMemoryError();
}
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeUnsharpMasking(int nativePix, int halfwidth, float fract);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* JPEG input and output methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class JpegIO {
static {
System.loadLibrary("lept");
}
/** Default quality is 85%, which is reasonably good. */
public static final int DEFAULT_QUALITY = 85;
/** Progressive encoding is disabled by default to increase compatibility. */
public static final boolean DEFAULT_PROGRESSIVE = false;
/**
* Returns a compressed JPEG byte representation of this Pix using default
* parameters.
*
* @param pixs
* @return a compressed JPEG byte array representation of the Pix
*/
public static byte[] compressToJpeg(Pix pixs) {
return compressToJpeg(pixs, DEFAULT_QUALITY, DEFAULT_PROGRESSIVE);
}
/**
* Returns a compressed JPEG byte representation of this Pix.
*
* @param pixs A source pix image.
* @param quality The quality of the compressed image. Valid range is 0-100.
* @param progressive Whether to use progressive compression.
* @return a compressed JPEG byte array representation of the Pix
*/
public static byte[] compressToJpeg(Pix pixs, int quality, boolean progressive) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (quality < 0 || quality > 100)
throw new IllegalArgumentException("Quality must be between 0 and 100 (inclusive)");
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
final Bitmap bmp = WriteFile.writeBitmap(pixs);
bmp.compress(CompressFormat.JPEG, quality, byteStream);
bmp.recycle();
final byte[] encodedData = byteStream.toByteArray();
try {
byteStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return encodedData;
}
// ***************
// * NATIVE CODE *
// ***************
private static native byte[] nativeCompressToJpeg(
int nativePix, int quality, boolean progressive);
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Leptonica constants.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Constants {
/*-------------------------------------------------------------------------*
* Access and storage flags *
*-------------------------------------------------------------------------*/
/*
* For Pix, Box, Pta and Numa, there are 3 standard methods for handling the
* retrieval or insertion of a struct: (1) direct insertion (Don't do this
* if there is another handle somewhere to this same struct!) (2) copy
* (Always safe, sets up a refcount of 1 on the new object. Can be
* undesirable if very large, such as an image or an array of images.) (3)
* clone (Makes another handle to the same struct, and bumps the refcount up
* by 1. Safe to do unless you're changing data through one of the handles
* but don't want those changes to be seen by the other handle.) For Pixa
* and Boxa, which are structs that hold an array of clonable structs, there
* is an additional method: (4) copy-clone (Makes a new higher-level struct
* with a refcount of 1, but clones all the structs in the array.) Unlike
* the other structs, when retrieving a string from an Sarray, you are
* allowed to get a handle without a copy or clone (i.e., that you don't
* own!). You must not free or insert such a string! Specifically, for an
* Sarray, the copyflag for retrieval is either: TRUE (or 1 or L_COPY) or
* FALSE (or 0 or L_NOCOPY) For insertion, the copyflag is either: TRUE (or
* 1 or L_COPY) or FALSE (or 0 or L_INSERT) Note that L_COPY is always 1,
* and L_INSERT and L_NOCOPY are always 0.
*/
/* Stuff it in; no copy, clone or copy-clone */
public static final int L_INSERT = 0;
/* Make/use a copy of the object */
public static final int L_COPY = 1;
/* Make/use clone (ref count) of the object */
public static final int L_CLONE = 2;
/*
* Make a new object and fill with with clones of each object in the
* array(s)
*/
public static final int L_COPY_CLONE = 3;
/*--------------------------------------------------------------------------*
* Sort flags *
*--------------------------------------------------------------------------*/
/* Sort in increasing order */
public static final int L_SORT_INCREASING = 1;
/* Sort in decreasing order */
public static final int L_SORT_DECREASING = 2;
/* Sort box or c.c. by horiz location */
public static final int L_SORT_BY_X = 3;
/* Sort box or c.c. by vert location */
public static final int L_SORT_BY_Y = 4;
/* Sort box or c.c. by width */
public static final int L_SORT_BY_WIDTH = 5;
/* Sort box or c.c. by height */
public static final int L_SORT_BY_HEIGHT = 6;
/* Sort box or c.c. by min dimension */
public static final int L_SORT_BY_MIN_DIMENSION = 7;
/* Sort box or c.c. by max dimension */
public static final int L_SORT_BY_MAX_DIMENSION = 8;
/* Sort box or c.c. by perimeter */
public static final int L_SORT_BY_PERIMETER = 9;
/* Sort box or c.c. by area */
public static final int L_SORT_BY_AREA = 10;
/* Sort box or c.c. by width/height ratio */
public static final int L_SORT_BY_ASPECT_RATIO = 11;
/* ------------------ Image file format types -------------- */
/*
* The IFF_DEFAULT flag is used to write the file out in the same (input)
* file format that the pix was read from. If the pix was not read from
* file, the input format field will be IFF_UNKNOWN and the output file
* format will be chosen to be compressed and lossless; namely, IFF_TIFF_G4
* for d = 1 and IFF_PNG for everything else. IFF_JP2 is for jpeg2000, which
* is not supported in leptonica.
*/
public static final int IFF_UNKNOWN = 0;
public static final int IFF_BMP = 1;
public static final int IFF_JFIF_JPEG = 2;
public static final int IFF_PNG = 3;
public static final int IFF_TIFF = 4;
public static final int IFF_TIFF_PACKBITS = 5;
public static final int IFF_TIFF_RLE = 6;
public static final int IFF_TIFF_G3 = 7;
public static final int IFF_TIFF_G4 = 8;
public static final int IFF_TIFF_LZW = 9;
public static final int IFF_TIFF_ZIP = 10;
public static final int IFF_PNM = 11;
public static final int IFF_PS = 12;
public static final int IFF_GIF = 13;
public static final int IFF_JP2 = 14;
public static final int IFF_DEFAULT = 15;
public static final int IFF_SPIX = 16;
}
|
Java
|
/*
* Copyright (C) 2011 Google Inc.
*
* 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.googlecode.leptonica.android;
/**
* Image scaling methods.
*
* @author alanv@google.com (Alan Viverette)
*/
public class Scale {
static {
System.loadLibrary("lept");
}
public enum ScaleType {
/* Scale in X and Y independently, so that src matches dst exactly. */
FILL,
/*
* Compute a scale that will maintain the original src aspect ratio, but
* will also ensure that src fits entirely inside dst. May shrink or
* expand src to fit dst.
*/
FIT,
/*
* Compute a scale that will maintain the original src aspect ratio, but
* will also ensure that src fits entirely inside dst. May shrink src to
* fit dst, but will not expand it.
*/
FIT_SHRINK,
}
/**
* Scales the Pix to a specified width and height using a specified scaling
* type (fill, stretch, etc.). Returns a scaled image or a clone of the Pix
* if no scaling is required.
*
* @param pixs
* @param width
* @param height
* @param type
* @return a scaled image or a clone of the Pix if no scaling is required
*/
public static Pix scaleToSize(Pix pixs, int width, int height, ScaleType type) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
int pixWidth = pixs.getWidth();
int pixHeight = pixs.getHeight();
float scaleX = width / (float) pixWidth;
float scaleY = height / (float) pixHeight;
switch (type) {
case FILL:
// Retains default scaleX and scaleY values
break;
case FIT:
scaleX = Math.min(scaleX, scaleY);
scaleY = scaleX;
break;
case FIT_SHRINK:
scaleX = Math.min(1.0f, Math.min(scaleX, scaleY));
scaleY = scaleX;
break;
}
return scale(pixs, scaleX, scaleY);
}
/**
* Scales the Pix to specified scale. If no scaling is required, returns a
* clone of the source Pix.
*
* @param pixs the source Pix
* @param scale dimension scaling factor
* @return a Pix scaled according to the supplied factors
*/
public static Pix scale(Pix pixs, float scale) {
return scale(pixs, scale, scale);
}
/**
* Scales the Pix to specified x and y scale. If no scaling is required,
* returns a clone of the source Pix.
*
* @param pixs the source Pix
* @param scaleX x-dimension (width) scaling factor
* @param scaleY y-dimension (height) scaling factor
* @return a Pix scaled according to the supplied factors
*/
public static Pix scale(Pix pixs, float scaleX, float scaleY) {
if (pixs == null)
throw new IllegalArgumentException("Source pix must be non-null");
if (scaleX <= 0.0f)
throw new IllegalArgumentException("X scaling factor must be positive");
if (scaleY <= 0.0f)
throw new IllegalArgumentException("Y scaling factor must be positive");
int nativePix = nativeScale(pixs.mNativePix, scaleX, scaleY);
if (nativePix == 0)
throw new RuntimeException("Failed to natively scale pix");
return new Pix(nativePix);
}
// ***************
// * NATIVE CODE *
// ***************
private static native int nativeScale(int nativePix, float scaleX, float scaleY);
}
|
Java
|
// vim: fileencoding=utf-8 tabstop=4 shiftwidth=4
// Copyright (c) 2010 , NetEase.com,Inc. All rights reserved.
//
// Author: Yang Bo (pop.atry@gmail.com)
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protocGenAs3;
import static google.protobuf.compiler.Plugin.*;
import static com.google.protobuf.DescriptorProtos.*;
import com.google.protobuf.*;
import java.io.*;
import java.util.*;
import java.math.*;
public final class Main {
private static final String[] ACTIONSCRIPT_KEYWORDS = {
"as", "break", "case", "catch", "class", "const", "continue", "default",
"delete", "do", "else", "extends", "false", "finally", "for",
"function", "if", "implements", "import", "in", "instanceof",
"interface", "internal", "is", "native", "new", "null", "package",
"private", "protected", "public", "return", "super", "switch", "this",
"throw", "to", "true", "try", "typeof", "use", "var", "void", "while",
"with"
};
private static final class Scope<Proto> {
// 如果 proto instanceOf Scope ,则这个 Scope 是对另一 Scope 的引用
public final String fullName;
public final Scope<?> parent;
public final Proto proto;
public final boolean export;
public final HashMap<String, Scope<?>> children =
new HashMap<String, Scope<?>>();
private Scope<?> find(String[] pathElements, int i) {
Scope<?> result = this;
for (; i < pathElements.length; i++) {
String name = pathElements[i];
if (result.children.containsKey(name)) {
result = result.children.get(name);
} else {
return null;
}
}
while (result.proto instanceof Scope) {
result = (Scope<?>)result.proto;
}
return result;
}
public boolean isRoot() {
return parent == null;
}
private Scope<?> getRoot() {
Scope<?> scope = this;
while (!scope.isRoot()) {
scope = scope.parent;
}
return scope;
}
public Scope<?> find(String path) {
String[] pathElements = path.split("\\.");
if (pathElements[0].equals("")) {
return getRoot().find(pathElements, 1);
} else {
for (Scope<?> scope = this; scope != null; scope = scope.parent) {
Scope<?> result = scope.find(pathElements, 0);
if (result != null) {
return result;
}
}
return null;
}
}
private Scope<?> findOrCreate(String[] pathElements, int i) {
Scope<?> scope = this;
for (; i < pathElements.length; i++) {
String name = pathElements[i];
if (scope.children.containsKey(name)) {
scope = scope.children.get(name);
} else {
Scope<Object> child =
new Scope<Object>(scope, null, false, name);
scope.children.put(name, child);
scope = child;
}
}
return scope;
}
public Scope<?> findOrCreate(String path) {
String[] pathElements = path.split("\\.");
if (pathElements[0].equals("")) {
return getRoot().findOrCreate(pathElements, 1);
} else {
return findOrCreate(pathElements, 0);
}
}
private Scope(Scope<?> parent, Proto proto, boolean export,
String name) {
this.parent = parent;
this.proto = proto;
this.export = export;
if (isRoot() || parent.isRoot()) {
fullName = name;
} else {
fullName = parent.fullName + '.' + name;
}
}
public <ChildProto> Scope<ChildProto> addChild(
String name, ChildProto proto, boolean export) {
assert(name != null);
assert(!name.equals(""));
Scope<ChildProto> child =
new Scope<ChildProto>(this, proto, export, name);
if(children.containsKey(child)) {
throw new IllegalArgumentException();
}
children.put(name, child);
return child;
}
public static Scope<Object> newRoot() {
return new Scope<Object>(null, null, false, "");
}
}
private static void addServiceToScope(Scope<?> scope,
ServiceDescriptorProto sdp, boolean export) {
scope.addChild(sdp.getName(), sdp, export);
}
private static void addExtensionToScope(Scope<?> scope,
FieldDescriptorProto efdp, boolean export) {
scope.addChild(efdp.getName().toUpperCase(), efdp, export);
}
private static void addEnumToScope(Scope<?> scope, EnumDescriptorProto edp,
boolean export) {
assert(edp.hasName());
Scope<EnumDescriptorProto> enumScope =
scope.addChild(edp.getName(), edp, export);
for (EnumValueDescriptorProto evdp : edp.getValueList()) {
Scope<EnumValueDescriptorProto> enumValueScope =
enumScope.addChild(evdp.getName(), evdp, false);
scope.addChild(evdp.getName(), enumValueScope, false);
}
}
private static void addMessageToScope(Scope<?> scope, DescriptorProto dp,
boolean export) {
Scope<DescriptorProto> messageScope =
scope.addChild(dp.getName(), dp, export);
for (EnumDescriptorProto edp : dp.getEnumTypeList()) {
addEnumToScope(messageScope, edp, export);
}
for (DescriptorProto nested: dp.getNestedTypeList()) {
addMessageToScope(messageScope, nested, export);
}
}
private static Scope<Object> buildScopeTree(CodeGeneratorRequest request) {
Scope<Object> root = Scope.newRoot();
List<String> filesToGenerate = request.getFileToGenerateList();
for (FileDescriptorProto fdp : request.getProtoFileList()) {
Scope<?> packageScope = fdp.hasPackage() ?
root.findOrCreate(fdp.getPackage()) : root;
boolean export = filesToGenerate.contains(fdp.getName());
for (ServiceDescriptorProto sdp : fdp.getServiceList()) {
addServiceToScope(packageScope, sdp, export);
}
for (FieldDescriptorProto efdp : fdp.getExtensionList()) {
addExtensionToScope(packageScope, efdp, export);
}
for (EnumDescriptorProto edp : fdp.getEnumTypeList()) {
addEnumToScope(packageScope, edp, export);
}
for (DescriptorProto dp : fdp.getMessageTypeList()) {
addMessageToScope(packageScope, dp, export);
}
}
return root;
}
private static String getImportType(Scope<?> scope,
FieldDescriptorProto fdp) {
switch (fdp.getType()) {
case TYPE_ENUM:
case TYPE_MESSAGE:
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
return typeScope.fullName;
case TYPE_BYTES:
return "flash.utils.ByteArray";
default:
return null;
}
}
private static boolean isValueType(FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_BOOL:
case TYPE_UINT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_ENUM:
return true;
default:
return false;
}
}
static final int VARINT = 0;
static final int FIXED_64_BIT = 1;
static final int LENGTH_DELIMITED = 2;
static final int FIXED_32_BIT = 5;
private static int getWireType(
FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FIXED64:
case TYPE_SFIXED64:
return FIXED_64_BIT;
case TYPE_FLOAT:
case TYPE_FIXED32:
case TYPE_SFIXED32:
return FIXED_32_BIT;
case TYPE_INT32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_SINT64:
case TYPE_ENUM:
return VARINT;
case TYPE_STRING:
case TYPE_MESSAGE:
case TYPE_BYTES:
return LENGTH_DELIMITED;
default:
throw new IllegalArgumentException();
}
}
private static String getActionScript3WireType(
FieldDescriptorProto.Type type) {
switch (type) {
case TYPE_DOUBLE:
case TYPE_FIXED64:
case TYPE_SFIXED64:
return "FIXED_64_BIT";
case TYPE_FLOAT:
case TYPE_FIXED32:
case TYPE_SFIXED32:
return "FIXED_32_BIT";
case TYPE_INT32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_SINT64:
case TYPE_ENUM:
return "VARINT";
case TYPE_STRING:
case TYPE_MESSAGE:
case TYPE_BYTES:
return "LENGTH_DELIMITED";
default:
throw new IllegalArgumentException();
}
}
private static String getActionScript3LogicType(Scope<?> scope,
FieldDescriptorProto fdp) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_ENUM) {
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
if (typeScope == scope) {
// workaround for mxmlc's bug.
return typeScope.fullName.substring(
typeScope.fullName.lastIndexOf('.') + 1);
}
return typeScope.fullName;
} else {
return getActionScript3Type(scope, fdp);
}
}
private static String getActionScript3Type(Scope<?> scope,
FieldDescriptorProto fdp) {
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
return "Number";
case TYPE_INT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_ENUM:
return "int";
case TYPE_UINT32:
case TYPE_FIXED32:
return "uint";
case TYPE_BOOL:
return "Boolean";
case TYPE_INT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
return "Int64";
case TYPE_UINT64:
case TYPE_FIXED64:
return "UInt64";
case TYPE_STRING:
return "String";
case TYPE_MESSAGE:
Scope<?> typeScope = scope.find(fdp.getTypeName());
if (typeScope == null) {
throw new IllegalArgumentException(
fdp.getTypeName() + " not found.");
}
if (typeScope == scope) {
// workaround for mxmlc's bug.
return typeScope.fullName.substring(
typeScope.fullName.lastIndexOf('.') + 1);
}
return typeScope.fullName;
case TYPE_BYTES:
return "flash.utils.ByteArray";
default:
throw new IllegalArgumentException();
}
}
private static void appendQuotedString(StringBuilder sb, String value) {
sb.append('\"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '\"':
case '\\':
sb.append('\\');
sb.append(c);
break;
default:
if (c >= 128 || Character.isISOControl(c)) {
sb.append("\\u");
sb.append(String.format("%04X", new Integer(c)));
} else {
sb.append(c);
}
}
}
sb.append('\"');
}
private static void appendDefaultValue(StringBuilder sb, Scope<?> scope,
FieldDescriptorProto fdp) {
String value = fdp.getDefaultValue();
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
if (value.equals("nan")) {
sb.append("NaN");
} else if (value.equals("inf")) {
sb.append("Infinity");
} else if (value.equals("-inf")) {
sb.append("-Infinity");
} else {
sb.append(value);
}
break;
case TYPE_UINT64:
case TYPE_FIXED64:
{
long v = new BigInteger(value).longValue();
sb.append("new UInt64(");
sb.append(Long.toString(v & 0xFFFFFFFFL));
sb.append(", ");
sb.append(Long.toString((v >>> 32) & 0xFFFFFFFFL));
sb.append(")");
}
break;
case TYPE_INT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
{
long v = Long.parseLong(value);
sb.append("new Int64(");
sb.append(Long.toString(v & 0xFFFFFFFFL));
sb.append(", ");
sb.append(Integer.toString((int)v >>> 32));
sb.append(")");
}
break;
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_UINT32:
case TYPE_BOOL:
sb.append(value);
break;
case TYPE_STRING:
appendQuotedString(sb, value);
break;
case TYPE_ENUM:
sb.append(scope.find(fdp.getTypeName()).
children.get(value).fullName);
break;
case TYPE_BYTES:
sb.append("stringToByteArray(");
sb.append("\"");
sb.append(value);
sb.append("\")");
break;
default:
throw new IllegalArgumentException();
}
}
private static void appendLowerCamelCase(StringBuilder sb, String s) {
if (Arrays.binarySearch(ACTIONSCRIPT_KEYWORDS, s) >= 0) {
sb.append("__");
}
sb.append(Character.toLowerCase(s.charAt(0)));
boolean upper = false;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (upper) {
if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
upper = false;
continue;
} else {
sb.append('_');
}
}
upper = c == '_';
if (!upper) {
sb.append(c);
}
}
}
private static void appendUpperCamelCase(StringBuilder sb, String s) {
sb.append(Character.toUpperCase(s.charAt(0)));
boolean upper = false;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (upper) {
if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
upper = false;
continue;
} else {
sb.append('_');
}
}
upper = c == '_';
if (!upper) {
sb.append(c);
}
}
}
private static void writeMessage(Scope<DescriptorProto> scope,
StringBuilder content, StringBuilder initializerContent) {
content.append("\timport com.netease.protobuf.*;\n");
content.append("\tuse namespace com.netease.protobuf.used_by_generated_code;\n");
content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n");
content.append("\timport flash.utils.Endian;\n");
content.append("\timport flash.utils.IDataInput;\n");
content.append("\timport flash.utils.IDataOutput;\n");
content.append("\timport flash.utils.IExternalizable;\n");
content.append("\timport flash.errors.IOError;\n");
HashSet<String> importTypes = new HashSet<String>();
for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) {
importTypes.add(scope.find(efdp.getExtendee()).fullName);
if (efdp.getType().equals(FieldDescriptorProto.Type.TYPE_MESSAGE)) {
importTypes.add(scope.find(efdp.getTypeName()).fullName);
}
String importType = getImportType(scope, efdp);
if (importType != null) {
importTypes.add(importType);
}
}
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
String importType = getImportType(scope, fdp);
if (importType != null) {
importTypes.add(importType);
}
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\t// @@protoc_insertion_point(imports)\n\n");
String remoteClassAlias;
if (scope.proto.hasOptions()) {
if (scope.proto.getOptions().hasExtension(Options.as3AmfAlias)) {
remoteClassAlias = scope.proto.getOptions().getExtension(Options.as3AmfAlias);
} else if (scope.proto.getOptions().getExtension(Options.as3AmfAutoAlias)) {
remoteClassAlias = scope.fullName;
} else {
remoteClassAlias = null;
}
if (remoteClassAlias != null) {
content.append("\t[RemoteClass(alias=");
appendQuotedString(content, remoteClassAlias);
content.append(")]\n");
}
if (scope.proto.getOptions().getExtension(Options.as3Bindable)) {
content.append("\t[Bindable]\n");
}
} else {
remoteClassAlias = null;
}
content.append("\t// @@protoc_insertion_point(class_metadata)\n");
content.append("\tpublic dynamic final class ");
content.append(scope.proto.getName());
content.append(" extends com.netease.protobuf.Message");
if (remoteClassAlias != null) {
content.append(" implements flash.utils.IExternalizable {\n");
content.append("\t\tpublic final function writeExternal(output:flash.utils.IDataOutput):void {\n");
content.append("\t\t\twriteDelimitedTo(output);\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic final function readExternal(input:flash.utils.IDataInput):void {\n");
content.append("\t\t\tmergeDelimitedFrom(input);\n");
content.append("\t\t}\n\n");
} else {
content.append(" {\n");
}
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t[ArrayElementType(\"Function\")]\n");
content.append("\t\tpublic static const extensionReadFunctions:Array = [];\n\n");
}
if (scope.proto.getExtensionCount() > 0) {
initializerContent.append("import ");
initializerContent.append(scope.fullName);
initializerContent.append(";\n");
initializerContent.append("if(!");
initializerContent.append(scope.fullName);
initializerContent.append(") throw new Error();\n");
}
for (FieldDescriptorProto efdp : scope.proto.getExtensionList()) {
if (efdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
String extendee = scope.find(efdp.getExtendee()).fullName;
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\tpublic static const ");
content.append(efdp.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, efdp);
content.append(" = ");
appendFieldDescriptor(content, scope, efdp);
content.append(";\n\n");
if (efdp.hasDefaultValue()) {
content.append("\t\t");
content.append(extendee);
content.append(".prototype[");
content.append(efdp.getName().toUpperCase());
content.append("] = ");
appendDefaultValue(content, scope, efdp);
content.append(";\n\n");
}
appendExtensionReadFunction(content, "\t\t", scope, efdp);
}
int valueTypeCount = 0;
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\tpublic static const ");
content.append(fdp.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, fdp);
content.append(" = ");
appendFieldDescriptor(content, scope, fdp);
content.append(";\n\n");
assert(fdp.hasLabel());
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
content.append("\t\tprivate var ");
content.append(fdp.getName());
content.append("$field:");
content.append(getActionScript3Type(scope, fdp));
content.append(";\n\n");
if (isValueType(fdp.getType())) {
final int valueTypeId = valueTypeCount++;
final int valueTypeField = valueTypeId / 32;
final int valueTypeBit = valueTypeId % 32;
if (valueTypeBit == 0) {
content.append("\t\tprivate var hasField$");
content.append(valueTypeField);
content.append(":uint = 0;\n\n");
}
content.append("\t\tpublic function clear");
appendUpperCamelCase(content, fdp.getName());
content.append("():void {\n");
content.append("\t\t\thasField$");
content.append(valueTypeField);
content.append(" &= 0x");
content.append(Integer.toHexString(~(1 << valueTypeBit)));
content.append(";\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = new ");
content.append(getActionScript3Type(scope, fdp));
content.append("();\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function get has");
appendUpperCamelCase(content, fdp.getName());
content.append("():Boolean {\n");
content.append("\t\t\treturn (hasField$");
content.append(valueTypeField);
content.append(" & 0x");
content.append(Integer.toHexString(1 << valueTypeBit));
content.append(") != 0;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function set ");
appendLowerCamelCase(content, fdp.getName());
content.append("(value:");
content.append(getActionScript3Type(scope, fdp));
content.append("):void {\n");
content.append("\t\t\thasField$");
content.append(valueTypeField);
content.append(" |= 0x");
content.append(Integer.toHexString(1 << valueTypeBit));
content.append(";\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = value;\n");
content.append("\t\t}\n\n");
} else {
content.append("\t\tpublic function clear");
appendUpperCamelCase(content, fdp.getName());
content.append("():void {\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = null;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function get has");
appendUpperCamelCase(content, fdp.getName());
content.append("():Boolean {\n");
content.append("\t\t\treturn ");
content.append(fdp.getName());
content.append("$field != null;\n");
content.append("\t\t}\n\n");
content.append("\t\tpublic function set ");
appendLowerCamelCase(content, fdp.getName());
content.append("(value:");
content.append(getActionScript3Type(scope, fdp));
content.append("):void {\n");
content.append("\t\t\t");
content.append(fdp.getName());
content.append("$field = value;\n");
content.append("\t\t}\n\n");
}
content.append("\t\tpublic function get ");
appendLowerCamelCase(content, fdp.getName());
content.append("():");
content.append(getActionScript3Type(scope, fdp));
content.append(" {\n");
if (fdp.hasDefaultValue()) {
content.append("\t\t\tif(!has");
appendUpperCamelCase(content, fdp.getName());
content.append(") {\n");
content.append("\t\t\t\treturn ");
appendDefaultValue(content, scope, fdp);
content.append(";\n");
content.append("\t\t\t}\n");
}
content.append("\t\t\treturn ");
content.append(fdp.getName());
content.append("$field;\n");
content.append("\t\t}\n\n");
break;
case LABEL_REQUIRED:
content.append("\t\tpublic var ");
appendLowerCamelCase(content, fdp.getName());
content.append(":");
content.append(getActionScript3Type(scope, fdp));
if (fdp.hasDefaultValue()) {
content.append(" = ");
appendDefaultValue(content, scope, fdp);
}
content.append(";\n\n");
break;
case LABEL_REPEATED:
content.append("\t\t[ArrayElementType(\"");
content.append(getActionScript3Type(scope, fdp));
content.append("\")]\n");
content.append("\t\tpublic var ");
appendLowerCamelCase(content, fdp.getName());
content.append(":Array = [];\n\n");
break;
default:
throw new IllegalArgumentException();
}
}
content.append("\t\t/**\n\t\t * @private\n\t\t */\n\t\toverride com.netease.protobuf.used_by_generated_code final function writeToBuffer(output:com.netease.protobuf.WritingBuffer):void {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
content.append("\t\t\tif (");
content.append("has");
appendUpperCamelCase(content, fdp.getName());
content.append(") {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, ");
content.append(fdp.getName());
content.append("$field);\n");
content.append("\t\t\t}\n");
break;
case LABEL_REQUIRED:
content.append("\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
break;
case LABEL_REPEATED:
if (fdp.hasOptions() && fdp.getOptions().getPacked()) {
content.append("\t\t\tif (this.");
appendLowerCamelCase(content, fdp.getName());
content.append(" != null && this.");
appendLowerCamelCase(content, fdp.getName());
content.append(".length > 0) {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.LENGTH_DELIMITED, ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writePackedRepeated(output, com.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append(", this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
content.append("\t\t\t}\n");
} else {
content.append("\t\t\tfor (var ");
appendLowerCamelCase(content, fdp.getName());
content.append("$index:uint = 0; ");
appendLowerCamelCase(content, fdp.getName());
content.append("$index < this.");
appendLowerCamelCase(content, fdp.getName());
content.append(".length; ++");
appendLowerCamelCase(content, fdp.getName());
content.append("$index) {\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.writeTag(output, com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append(", ");
content.append(Integer.toString(fdp.getNumber()));
content.append(");\n");
content.append("\t\t\t\tcom.netease.protobuf.WriteUtils.write$");
content.append(fdp.getType().name());
content.append("(output, this.");
appendLowerCamelCase(content, fdp.getName());
content.append("[");
appendLowerCamelCase(content, fdp.getName());
content.append("$index]);\n");
content.append("\t\t\t}\n");
}
break;
}
}
content.append("\t\t\tfor (var fieldKey:* in this) {\n");
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t\t\tsuper.writeExtensionOrUnknown(output, fieldKey);\n");
} else {
content.append("\t\t\t\tsuper.writeUnknown(output, fieldKey);\n");
}
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
content.append("\t\t/**\n\t\t * @private\n\t\t */\n");
content.append("\t\toverride com.netease.protobuf.used_by_generated_code final function readFromSlice(input:flash.utils.IDataInput, bytesAfterSlice:uint):void {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
case LABEL_REQUIRED:
content.append("\t\t\tvar ");
content.append(fdp.getName());
content.append("$count:uint = 0;\n");
break;
}
}
content.append("\t\t\twhile (input.bytesAvailable > bytesAfterSlice) {\n");
content.append("\t\t\t\tvar tag:uint = com.netease.protobuf.ReadUtils.read$TYPE_UINT32(input);\n");
content.append("\t\t\t\tswitch (tag >> 3) {\n");
for (FieldDescriptorProto fdp : scope.proto.getFieldList()) {
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
continue;
}
content.append("\t\t\t\tcase ");
content.append(Integer.toString(fdp.getNumber()));
content.append(":\n");
switch (fdp.getLabel()) {
case LABEL_OPTIONAL:
case LABEL_REQUIRED:
content.append("\t\t\t\t\tif (");
content.append(fdp.getName());
content.append("$count != 0) {\n");
content.append("\t\t\t\t\t\tthrow new flash.errors.IOError('Bad data format: ");
content.append(scope.proto.getName());
content.append('.');
appendLowerCamelCase(content, fdp.getName());
content.append(" cannot be set twice.');\n");
content.append("\t\t\t\t\t}\n");
content.append("\t\t\t\t\t++");
content.append(fdp.getName());
content.append("$count;\n");
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(" = new ");
content.append(getActionScript3Type(scope, fdp));
content.append("();\n");
content.append("\t\t\t\t\tcom.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
} else {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(" = com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append("(input);\n");
}
break;
case LABEL_REPEATED:
switch (fdp.getType()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_BOOL:
case TYPE_INT32:
case TYPE_FIXED32:
case TYPE_UINT32:
case TYPE_SFIXED32:
case TYPE_SINT32:
case TYPE_INT64:
case TYPE_FIXED64:
case TYPE_UINT64:
case TYPE_SFIXED64:
case TYPE_SINT64:
case TYPE_ENUM:
content.append("\t\t\t\t\tif ((tag & 7) == com.netease.protobuf.WireType.LENGTH_DELIMITED) {\n");
content.append("\t\t\t\t\t\tcom.netease.protobuf.ReadUtils.readPackedRepeated(input, com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append(", this.");
appendLowerCamelCase(content, fdp.getName());
content.append(");\n");
content.append("\t\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t\t}\n");
}
if (fdp.getType() == FieldDescriptorProto.Type.TYPE_MESSAGE) {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(".push(");
content.append("com.netease.protobuf.ReadUtils.read$TYPE_MESSAGE(input, ");
content.append("new ");
content.append(getActionScript3Type(scope, fdp));
content.append("()));\n");
} else {
content.append("\t\t\t\t\tthis.");
appendLowerCamelCase(content, fdp.getName());
content.append(".push(com.netease.protobuf.ReadUtils.read$");
content.append(fdp.getType().name());
content.append("(input));\n");
}
break;
}
content.append("\t\t\t\t\tbreak;\n");
}
content.append("\t\t\t\tdefault:\n");
if (scope.proto.getExtensionRangeCount() > 0) {
content.append("\t\t\t\t\tsuper.readExtensionOrUnknown(extensionReadFunctions, input, tag);\n");
} else {
content.append("\t\t\t\t\tsuper.readUnknown(input, tag);\n");
}
content.append("\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t}\n");
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
content.append("\t}\n");
}
private static void appendFieldDescriptorClass(StringBuilder content,
FieldDescriptorProto fdp) {
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
break;
case LABEL_REPEATED:
content.append("Repeated");
break;
default:
throw new IllegalArgumentException();
}
content.append("FieldDescriptor$");
content.append(fdp.getType().name());
}
private static void appendFieldDescriptor(StringBuilder content,
Scope<?> scope,
FieldDescriptorProto fdp) {
content.append("new ");
appendFieldDescriptorClass(content, fdp);
content.append("(");
if (scope.parent == null) {
appendQuotedString(content, fdp.getName());
} else {
appendQuotedString(content, scope.fullName + '.' + fdp.getName());
}
content.append(", ");
if (fdp.hasExtendee()) {
if (scope.proto instanceof DescriptorProto) {
appendQuotedString(content, scope.fullName + '/' + fdp.getName().toUpperCase());
} else {
if (scope.parent == null) {
appendQuotedString(content, fdp.getName().toUpperCase());
} else {
appendQuotedString(content, scope.fullName + '.' + fdp.getName().toUpperCase());
}
}
} else {
StringBuilder fieldName = new StringBuilder();
appendLowerCamelCase(fieldName, fdp.getName());
appendQuotedString(content, fieldName.toString());
}
content.append(", (");
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
break;
case LABEL_REPEATED:
if (fdp.hasOptions() && fdp.getOptions().getPacked()) {
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED");
} else {
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
}
break;
}
switch (fdp.getType()) {
case TYPE_MESSAGE:
if (scope.proto instanceof DescriptorProto) {
content.append(", function():Class { return ");
content.append(getActionScript3LogicType(scope, fdp));
content.append("; }");
} else {
content.append(", ");
content.append(getActionScript3LogicType(scope, fdp));
}
break;
case TYPE_ENUM:
content.append(", ");
content.append(getActionScript3LogicType(scope, fdp));
break;
}
content.append(")");
}
private static void appendExtensionReadFunction(StringBuilder content,
String tabs,
Scope<?> scope,
FieldDescriptorProto fdp) {
String extendee = scope.find(fdp.getExtendee()).fullName;
switch (fdp.getLabel()) {
case LABEL_REQUIRED:
case LABEL_OPTIONAL:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append("] = ");
content.append(fdp.getName().toUpperCase());
content.append(".read;\n\n");
break;
case LABEL_REPEATED:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.");
content.append(getActionScript3WireType(fdp.getType()));
content.append("] = ");
content.append(fdp.getName().toUpperCase());
content.append(".readNonPacked;\n\n");
switch (fdp.getType()) {
case TYPE_MESSAGE:
case TYPE_BYTES:
case TYPE_STRING:
break;
default:
content.append(tabs);
content.append(extendee);
content.append(".extensionReadFunctions[(");
content.append(Integer.toString(fdp.getNumber()));
content.append(" << 3) | com.netease.protobuf.WireType.LENGTH_DELIMITED] = ");
content.append(fdp.getName().toUpperCase());
content.append(".readPacked;\n\n");
break;
}
break;
}
}
private static void writeExtension(Scope<FieldDescriptorProto> scope,
StringBuilder content, StringBuilder initializerContent) {
initializerContent.append("import ");
initializerContent.append(scope.fullName);
initializerContent.append(";\n");
initializerContent.append("if(!");
initializerContent.append(scope.fullName);
initializerContent.append(") throw new Error;\n");
content.append("\timport com.netease.protobuf.*;\n");
content.append("\timport com.netease.protobuf.fieldDescriptors.*;\n");
String importType = getImportType(scope.parent, scope.proto);
if (importType != null) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
String extendee = scope.parent.find(scope.proto.getExtendee()).fullName;
content.append("\timport ");
content.append(extendee);
content.append(";\n");
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\t// @@protoc_insertion_point(constant_metadata)\n");
content.append("\t/**\n\t * @private\n\t */\n");
content.append("\tpublic const ");
content.append(scope.proto.getName().toUpperCase());
content.append(":");
appendFieldDescriptorClass(content, scope.proto);
content.append(" = ");
appendFieldDescriptor(content, scope.parent, scope.proto);
content.append(";\n\n");
if (scope.proto.hasDefaultValue()) {
content.append("\t");
content.append(extendee);
content.append(".prototype[");
content.append(scope.proto.getName().toUpperCase());
content.append("] = ");
appendDefaultValue(content, scope.parent, scope.proto);
content.append(";\n\n");
}
appendExtensionReadFunction(content, "\t", scope.parent, scope.proto);
}
private static void writeEnum(Scope<EnumDescriptorProto> scope,
StringBuilder content) {
content.append("\tpublic final class ");
content.append(scope.proto.getName());
content.append(" {\n");
for (EnumValueDescriptorProto evdp : scope.proto.getValueList()) {
content.append("\t\tpublic static const ");
content.append(evdp.getName());
content.append(":int = ");
content.append(evdp.getNumber());
content.append(";\n");
}
content.append("\t}\n");
}
@SuppressWarnings("unchecked")
private static void writeFile(Scope<?> scope, StringBuilder content,
StringBuilder initializerContent) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
if (scope.proto instanceof DescriptorProto) {
writeMessage((Scope<DescriptorProto>)scope, content,
initializerContent);
} else if (scope.proto instanceof EnumDescriptorProto) {
writeEnum((Scope<EnumDescriptorProto>)scope, content);
} else if (scope.proto instanceof FieldDescriptorProto) {
Scope<FieldDescriptorProto> fdpScope =
(Scope<FieldDescriptorProto>)scope;
if (fdpScope.proto.getType() ==
FieldDescriptorProto.Type.TYPE_GROUP) {
System.err.println("Warning: Group is not supported.");
} else {
writeExtension(fdpScope, content, initializerContent);
}
} else {
throw new IllegalArgumentException();
}
content.append("}\n");
}
@SuppressWarnings("unchecked")
private static void writeFiles(Scope<?> root,
CodeGeneratorResponse.Builder responseBuilder,
StringBuilder initializerContent) {
for (Map.Entry<String, Scope<?>> entry : root.children.entrySet()) {
Scope<?> scope = entry.getValue();
if (scope.export) {
if (scope.proto instanceof ServiceDescriptorProto) {
ServiceDescriptorProto serviceProto = (ServiceDescriptorProto)scope.proto;
if (serviceProto.getOptions().getExtension(Options.as3ClientSideService) ||
serviceProto.getOptions().getExtension(Options.as3ServerSideService)) {
StringBuilder classContent = new StringBuilder();
writeServiceClass((Scope<ServiceDescriptorProto>)scope, classContent);
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(scope.fullName.replace('.', '/') + ".as").
setContent(classContent.toString()).
build()
);
StringBuilder interfaceContent = new StringBuilder();
writeServiceInterface((Scope<ServiceDescriptorProto>)scope, interfaceContent);
String[] servicePath = scope.fullName.split("\\.");
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < servicePath.length - 1; i++) {
sb.append(servicePath[i]);
sb.append('/');
}
sb.append('I');
sb.append(servicePath[i]);
sb.append(".as");
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(sb.toString()).
setContent(interfaceContent.toString()).
build()
);
}
}
else
{
StringBuilder content = new StringBuilder();
writeFile(scope, content, initializerContent);
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName(scope.fullName.replace('.', '/') + ".as").
setContent(content.toString()).
build()
);
}
}
writeFiles(scope, responseBuilder, initializerContent);
}
}
private static void writeFiles(Scope<?> root,
CodeGeneratorResponse.Builder responseBuilder) {
StringBuilder initializerContent = new StringBuilder();
initializerContent.append("{\n");
writeFiles(root, responseBuilder, initializerContent);
initializerContent.append("}\n");
responseBuilder.addFile(
CodeGeneratorResponse.File.newBuilder().
setName("initializer.as.inc").
setContent(initializerContent.toString()).
build()
);
}
private static void writeServiceClass(Scope<ServiceDescriptorProto> scope,
StringBuilder content) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
HashSet<String> importTypes = new HashSet<String>();
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
importTypes.add(scope.find(mdp.getInputType()).fullName);
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
importTypes.add(scope.find(mdp.getOutputType()).fullName);
}
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\timport google.protobuf.*;\n");
content.append("\timport flash.utils.*;\n");
content.append("\timport com.netease.protobuf.*;\n");
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\tpublic final class ");
content.append(scope.proto.getName());
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
content.append(" implements ");
if (scope.parent.isRoot()) {
content.append("I");
} else {
content.append(scope.parent.fullName);
content.append(".I");
}
content.append(scope.proto.getName());
}
content.append(" {\n");
if (scope.proto.hasOptions()) {
content.append("\t\tpublic static const OPTIONS_BYTES:flash.utils.ByteArray = com.netease.protobuf.stringToByteArray(\"");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
scope.proto.getOptions().writeTo(buffer);
} catch (IOException e) {
throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e);
}
for (byte b : buffer.toByteArray()) {
content.append("\\x");
content.append(Character.forDigit((b & 0xF0) >>> 4, 16));
content.append(Character.forDigit(b & 0x0F, 16));
}
content.append("\");\n\n");
content.append("\t\tpublic static function getOptions():google.protobuf.ServiceOptions\n");
content.append("\t\t{\n");
content.append("\t\t\tOPTIONS_BYTES.position = 0;\n");
content.append("\t\t\tconst options:google.protobuf.ServiceOptions = new google.protobuf.ServiceOptions();\n");
content.append("\t\t\toptions.mergeFrom(OPTIONS_BYTES);\n\n");
content.append("\t\t\treturn options;\n");
content.append("\t\t}\n\n");
}
boolean hasMethodOptions = false;
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
if (mdp.hasOptions()) {
if (!hasMethodOptions) {
hasMethodOptions = true;
content.append("\t\tpublic static const OPTIONS_BYTES_BY_METHOD_NAME:Object =\n");
content.append("\t\t{\n");
} else {
content.append(",\n");
}
content.append("\t\t\t\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\" : stringToByteArray(\"");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
mdp.getOptions().writeTo(buffer);
} catch (IOException e) {
throw new IllegalStateException("ByteArrayOutputStream should not throw IOException!", e);
}
for (byte b : buffer.toByteArray()) {
content.append("\\x");
content.append(Character.forDigit((b & 0xF0) >>> 4, 16));
content.append(Character.forDigit(b & 0x0F, 16));
}
content.append("\")");
}
}
if (hasMethodOptions) {
content.append("\n\t\t};\n\n");
}
if (scope.proto.getOptions().getExtension(Options.as3ServerSideService)) {
content.append("\t\tpublic static const REQUEST_CLASSES_BY_METHOD_NAME:Object =\n");
content.append("\t\t{\n");
boolean comma = false;
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
if (comma) {
content.append(",\n");
} else {
comma = true;
}
content.append("\t\t\t\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\" : ");
content.append(scope.find(mdp.getInputType()).fullName);
}
content.append("\n\t\t};\n\n");
content.append("\t\tpublic static function callMethod(service:");
if (scope.parent.isRoot()) {
content.append("I");
} else {
content.append(scope.parent.fullName);
content.append(".I");
}
content.append(scope.proto.getName());
content.append(", methodName:String, request:com.netease.protobuf.Message, responseHandler:Function):void {\n");
content.append("\t\t\tswitch (methodName) {\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\t\t\tcase \"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\":\n");
content.append("\t\t\t\t{\n");
content.append("\t\t\t\t\tservice.");
appendLowerCamelCase(content, mdp.getName());
content.append("(");
content.append(scope.find(mdp.getInputType()).fullName);
content.append("(request), responseHandler);\n");
content.append("\t\t\t\t\tbreak;\n");
content.append("\t\t\t\t}\n");
}
content.append("\t\t\t}\n");
content.append("\t\t}\n\n");
}
if (scope.proto.getOptions().getExtension(Options.as3ClientSideService)) {
content.append("\t\tpublic var sendFunction:Function;\n\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\tpublic function ");
appendLowerCamelCase(content, mdp.getName());
content.append("(request:");
content.append(scope.find(mdp.getInputType()).fullName);
content.append(", responseHandler:Function):void {\n");
content.append("\t\t\tsendFunction(\"");
content.append(scope.fullName);
content.append(".");
content.append(mdp.getName());
content.append("\", request, responseHandler, ");
content.append(scope.find(mdp.getOutputType()).fullName);
content.append(");\n");
content.append("\t\t}\n\n");
}
}
content.append("\t}\n");
content.append("}\n");
}
private static void writeServiceInterface(
Scope<ServiceDescriptorProto> scope,
StringBuilder content) {
content.append("package ");
content.append(scope.parent.fullName);
content.append(" {\n");
HashSet<String> importTypes = new HashSet<String>();
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
importTypes.add(scope.find(mdp.getInputType()).fullName);
}
for (String importType : importTypes) {
content.append("\timport ");
content.append(importType);
content.append(";\n");
}
content.append("\t// @@protoc_insertion_point(imports)\n\n");
content.append("\tpublic interface I");
content.append(scope.proto.getName());
content.append(" {\n\n");
for (MethodDescriptorProto mdp : scope.proto.getMethodList()) {
content.append("\t\tfunction ");
appendLowerCamelCase(content, mdp.getName());
content.append("(input:");
content.append(scope.find(mdp.getInputType()).fullName);
content.append(", done:Function):void;\n\n");
}
content.append("\t}\n");
content.append("}\n");
}
public static void main(String[] args) throws IOException {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
Options.registerAllExtensions(registry);
CodeGeneratorRequest request = CodeGeneratorRequest.
parseFrom(System.in, registry);
CodeGeneratorResponse response;
try {
Scope<Object> root = buildScopeTree(request);
CodeGeneratorResponse.Builder responseBuilder =
CodeGeneratorResponse.newBuilder();
writeFiles(root, responseBuilder);
response = responseBuilder.build();
} catch (Exception e) {
// 出错,报告给 protoc ,然后退出
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
CodeGeneratorResponse.newBuilder().setError(sw.toString()).
build().writeTo(System.out);
System.out.flush();
return;
}
response.writeTo(System.out);
System.out.flush();
}
}
|
Java
|
public class TestSVNCode {
//nhom google code nhom 8
public static void main(String[] args)
{
System.out.println("hello world");
System.out.println("hello world");
System.out.println("nhom 8");
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.service;
import java.util.List;
import com.google.gwt.sample.stockwatcher.client.shared.StockBuy;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(List<String> symbols);
StockBuy buyStock(StockBuy stockBuy);
List<StockBuy> getStockBuyingHistory();
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.service;
import java.util.List;
import com.google.gwt.sample.stockwatcher.client.shared.StockBuy;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface StockPriceServiceAsync {
void getPrices(List<String> symbol, AsyncCallback<StockPrice[]> callback);
void buyStock(StockBuy stockBuy, AsyncCallback<StockBuy> callback);
void getStockBuyingHistory(AsyncCallback<List<StockBuy>> callback);
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
public interface BuyStockPresenter extends Presenter<BuyStockPresenter.Display> {
public interface Display extends
com.google.gwt.sample.stockwatcher.client.view.Display {
void displaySymbol(String symbol);
void displayPrice(String price);
void setPresenter(BuyStockPresenter presenter);
}
void onSaveButtonClicked(Long amount);
void onCancelButtonClicked();
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.sample.stockwatcher.client.view.Display;
/**
*
*/
public abstract class BasePresenter<D extends Display> implements Presenter<D> {
protected final HandlerManager eventBus;
protected final D display;
public BasePresenter(HandlerManager eventBus, D display) {
this.eventBus = eventBus;
this.display = display;
}
@Override
public void bind() {
onBind();
postBind();
}
/**
* Do actually event binding.
*/
protected abstract void onBind();
/**
* Override in case data init after bind.
*/
protected void postBind() {
}
public D getDisplay() {
return this.display;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.sample.stockwatcher.client.event.BuyStockEvent;
import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync;
import com.google.gwt.sample.stockwatcher.client.shared.StockBuy;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class StockWatcherPresenterImpl extends
BasePresenter<StockWatcherPresenter.Display> implements
StockWatcherPresenter {
private List<String> symbolList = new ArrayList<String>();
private StockPriceServiceAsync rpcService;
public StockWatcherPresenterImpl(StockPriceServiceAsync rpcService,
HandlerManager eventBus, Display view) {
super(eventBus, view);
this.rpcService = rpcService;
}
@Override
protected void onBind() {
}
private void addStock(final String symbol) {
if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
return;
}
if (symbolList.contains(symbol)) {
Window.alert("Unique constraint of symbol.");
return;
}
symbolList.add(symbol);
display.addNewRow(symbol);
refreshWatchList();
display.getRemoveButton(symbol).addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
display.removeRow(symbol);
symbolList.remove(symbol);
}
});
display.getBuyButton(symbol).addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final double price = Double.parseDouble(display
.getPrice(symbol));
StockPrice stockPrice = new StockPrice(symbol, price);
eventBus.fireEvent(new BuyStockEvent(stockPrice));
}
});
}
private void refreshWatchList() {
this.rpcService.getPrices(this.symbolList,
new AsyncCallback<StockPrice[]>() {
@Override
public void onFailure(Throwable caught) {
Window.alert("refreshWatchList error");
}
@Override
public void onSuccess(StockPrice[] result) {
for (int i = 0; i < result.length; i++) {
int row = i + 1;
display.updatePrice(row, result[i].getPrice());
display.updateChangePercent(row, result[i]
.getChange(), result[i].getChangePercent());
}
}
});
}
/**
* TODO: duplicated row.
*/
private void refreshBuyingHistory() {
this.rpcService
.getStockBuyingHistory(new AsyncCallback<List<StockBuy>>() {
@Override
public void onFailure(Throwable caught) {
Window.alert("refreshBuyingHistory error"
+ caught.getMessage());
}
@Override
public void onSuccess(List<StockBuy> result) {
for (StockBuy stockBuy : result) {
display.addNewBuyingHistory(stockBuy.getSymbol(),
String.valueOf(stockBuy.getPrice()), String
.valueOf(stockBuy.getCount()));
}
}
});
}
@Override
protected void postBind() {
refreshWatchList();
refreshBuyingHistory();
}
@Override
public void onAddButtonClicked(String value) {
addStock(value);
}
@Override
public void onInputBoxEnterKeyPressed(String value) {
addStock(value);
}
// private void scheduleTimeRefresh() {
// // Setup timer to refresh list automatically.
// Timer refreshTimer = new Timer() {
// @Override
// public void run() {
// refreshWatchList();
// }
// };
// refreshTimer.scheduleRepeating(REFRESH_INTERVAL);
// }
// private static final int REFRESH_INTERVAL = 2000;
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
import com.google.gwt.event.dom.client.HasClickHandlers;
public interface StockWatcherPresenter extends
Presenter<StockWatcherPresenter.Display> {
public interface Display extends
com.google.gwt.sample.stockwatcher.client.view.Display {
/**
* Get the Remove button for <code>symbol<code>.
*/
HasClickHandlers getRemoveButton(String symbol);
HasClickHandlers getBuyButton(String symbol);
/**
* Add new Row that has the <code>symbol<code> into Table
*/
void addNewRow(String symbol);
/**
* Remove the Row that has the <code>symbol<code> in the Table
*/
void removeRow(String symbol);
/**
* Get price of current row.
*/
String getPrice(String symbol);
/**
* TODO: Add a single API to update Price and ChangePercentage.
*/
void updateChangePercent(int row, double change, double changePercent);
void updatePrice(int row, double value);
void addNewBuyingHistory(String symbol, String price, String count);
void setPresenter(StockWatcherPresenter presenter);
}
// void refreshWatchList();
// void refreshBuyingHistory();
void onAddButtonClicked(String value);
void onInputBoxEnterKeyPressed(String value);
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
import com.google.gwt.sample.stockwatcher.client.view.Display;
/**
* Presenter Interface.
*/
public interface Presenter<D extends Display> {
void bind();
D getDisplay();
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.presenter;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEvent;
import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync;
import com.google.gwt.sample.stockwatcher.client.shared.StockBuy;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class BuyStockPresenterImpl extends
BasePresenter<BuyStockPresenter.Display> implements BuyStockPresenter {
private StockPriceServiceAsync rpcService;
private StockPrice stockPrice;
public BuyStockPresenterImpl(StockPriceServiceAsync rpcService,
HandlerManager eventBus, Display view, StockPrice stockPrice) {
super(eventBus, view);
this.rpcService = rpcService;
this.stockPrice = stockPrice;
displayValue(stockPrice);
}
private void displayValue(StockPrice stockPrice) {
display.displaySymbol(stockPrice.getSymbol());
display.displayPrice(String.valueOf(stockPrice.getPrice()));
}
@Override
public void onCancelButtonClicked() {
eventBus.fireEvent(new ShowStockWaterEvent());
}
@Override
public void onSaveButtonClicked(Long amount) {
StockBuy stockBuy = new StockBuy(this.stockPrice.getSymbol(),
this.stockPrice.getPrice(), amount);
rpcService.buyStock(stockBuy, new AsyncCallback<StockBuy>() {
@Override
public void onSuccess(StockBuy result) {
eventBus.fireEvent(new ShowStockWaterEvent());
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
});
}
@Override
protected void onBind() {
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.view;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenter;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
/**
*
*/
public class StockWatcherView extends Composite implements
StockWatcherPresenter.Display {
/**
* FlexTable is used when you have content added/removed dynamically - which
* means you won't be adding stuff via UiBinder templates (that doesn't even
* makes sense).
*/
@UiField
FlexTable stocksFlexTable = new FlexTable();
@UiField
FlexTable buyingHistory = new FlexTable();
@UiField
TextBox newSymbolTextBox;
@UiField
Button addButton;
private StockWatcherPresenter presenter;
@UiTemplate("StockWatcherView.ui.xml")
interface StockWatcherViewUiBinder extends
UiBinder<Widget, StockWatcherView> {
}
private static StockWatcherViewUiBinder uiBinder = GWT
.create(StockWatcherViewUiBinder.class);
public StockWatcherView() {
initWidget(uiBinder.createAndBindUi(this));
buildStocksTable();
buildBuyingHistoryTable();
// this.newSymbolTextBox.setFocus(true);
}
private void buildBuyingHistoryTable() {
buyingHistory.setText(0, 0, "Symbol");
buyingHistory.setText(0, 1, "Price");
buyingHistory.setText(0, 2, "Count");
// stocksFlexTable.setCellPadding(6);
buyingHistory.getRowFormatter().addStyleName(0, "watchListHeader");
buyingHistory.addStyleName("watchList");
buyingHistory.getCellFormatter().addStyleName(0, 1,
"watchListNumericColumn");
buyingHistory.getCellFormatter().addStyleName(0, 2,
"watchListNumericColumn");
}
private void buildStocksTable() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Symbol");
stocksFlexTable.setText(0, 1, "Price");
stocksFlexTable.setText(0, 2, "Change");
stocksFlexTable.setText(0, 3, "Remove");
stocksFlexTable.setText(0, 4, "Buy");
// Add styles to elements in the stock list table.
stocksFlexTable.setCellPadding(6);
stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
stocksFlexTable.addStyleName("watchList");
stocksFlexTable.getCellFormatter().addStyleName(0, 1,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(0, 2,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(0, 3,
"watchListButtonColumn");
stocksFlexTable.getCellFormatter().addStyleName(0, 4,
"watchListButtonColumn");
}
@UiHandler("addButton")
void onAddButtonClicked(ClickEvent event) {
if (presenter != null) {
presenter.onAddButtonClicked(newSymbolTextBox.getValue());
}
}
@UiHandler("newSymbolTextBox")
void onInputBoxEnterKeyPressed(KeyPressEvent event) {
if (presenter != null && event.getCharCode() == KeyCodes.KEY_ENTER) {
presenter.onInputBoxEnterKeyPressed(newSymbolTextBox.getValue());
}
}
// ==============================================
// ========================= Override
// ==============================================
@Override
public void setPresenter(StockWatcherPresenter presenter) {
this.presenter = presenter;
}
@Override
public Widget asWidget() {
return this;
}
@Override
public HasClickHandlers getRemoveButton(String symbol) {
return (HasClickHandlers) stocksFlexTable.getWidget(
findRowNumberOfSymbol(symbol), 3);
}
@Override
public HasClickHandlers getBuyButton(String symbol) {
return (HasClickHandlers) stocksFlexTable.getWidget(
findRowNumberOfSymbol(symbol), 4);
}
@Override
public void updatePrice(int row, double value) {
String priceText = NumberFormat.getFormat("#,##0.00").format(value);
stocksFlexTable.setText(row, 1, priceText);
}
@Override
public String getPrice(String symbol) {
return stocksFlexTable.getText(findRowNumberOfSymbol(symbol), 1);
}
@Override
public void updateChangePercent(int row, double change, double changePercent) {
NumberFormat changeFormat = NumberFormat
.getFormat("+#,##0.00;-#,##0.00");
String changeText = changeFormat.format(change);
String changePercentText = changeFormat.format(changePercent);
Label changeWidget = (Label) stocksFlexTable.getWidget(row, 2);
changeWidget.setText(changeText + " (" + changePercentText + "%)");
String changeStyleName = "noChange";
if (changePercent < -0.1f) {
changeStyleName = "negativeChange";
} else if (changePercent > 0.1f) {
changeStyleName = "positiveChange";
}
changeWidget.setStyleName(changeStyleName);
}
@Override
public void addNewRow(String symbol) {
int row = stocksFlexTable.getRowCount();
stocksFlexTable.setText(row, 0, symbol);
stocksFlexTable.setWidget(row, 2, new Label());
stocksFlexTable.getCellFormatter().addStyleName(row, 1,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(row, 2,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(row, 3,
"watchListRemoveColumn");
Button removeStockButton = new Button("x");
removeStockButton.addStyleDependentName("remove");
stocksFlexTable.setWidget(row, 3, removeStockButton);
Button buyButton = new Button("$");
buyButton.addStyleDependentName("Buy");
stocksFlexTable.setWidget(row, 4, buyButton);
this.newSymbolTextBox.setText("");
}
@Override
public void addNewBuyingHistory(String symbol, String price, String count) {
buyingHistory.clear();
int row = buyingHistory.getRowCount();
buyingHistory.setText(row, 0, symbol);
buyingHistory.setText(row, 1, price);
buyingHistory.setText(row, 2, count);
}
@Override
public void removeRow(String symbol) {
stocksFlexTable.removeRow(findRowNumberOfSymbol(symbol));
}
private int findRowNumberOfSymbol(String symbol) {
for (int row = 1; row < stocksFlexTable.getRowCount(); row++) {
if (this.stocksFlexTable.getText(row, 0).equals(symbol)) {
return row;
}
}
return 0;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.view;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenter;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
public class BuyStockView extends Composite implements
BuyStockPresenter.Display {
@UiTemplate("BuyStockView.ui.xml")
interface BuyStockViewUiBinder extends
UiBinder<DecoratorPanel, BuyStockView> {
}
private static BuyStockViewUiBinder uiBinder = GWT
.create(BuyStockViewUiBinder.class);
@UiField
TextBox symbol;
@UiField
TextBox price;
@UiField
TextBox amount;
@UiField
Button saveButton;
@UiField
Button cancelButton;
private BuyStockPresenter presenter;
public BuyStockView() {
initWidget(uiBinder.createAndBindUi(this));
}
@UiHandler("saveButton")
void onSaveButtonClicked(ClickEvent event) {
if (presenter != null) {
presenter.onSaveButtonClicked(Long.valueOf(amount.getValue()));
}
}
@UiHandler("cancelButton")
void onCancelButtonClicked(ClickEvent event) {
if (presenter != null) {
presenter.onCancelButtonClicked();
}
}
@Override
public void setPresenter(BuyStockPresenter presenter) {
this.presenter = presenter;
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void displaySymbol(String value) {
symbol.setText(value);
}
@Override
public void displayPrice(String price) {
this.price.setText(price);
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.view;
import com.google.gwt.user.client.ui.Widget;
public interface Display {
Widget asWidget();
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.shared;
import java.io.Serializable;
public class StockPrice implements Serializable {
/** */
private static final long serialVersionUID = 8040259246828316386L;
private String symbol;
private double price;
private double change;
public StockPrice() {
}
public StockPrice(String symbol, double price, double change) {
this.symbol = symbol;
this.price = price;
this.change = change;
}
public StockPrice(String symbol, double price) {
this.symbol = symbol;
this.price = price;
}
public String getSymbol() {
return this.symbol;
}
public double getPrice() {
return this.price;
}
public double getChange() {
return this.change;
}
public double getChangePercent() {
return 100.0 * this.change / this.price;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public void setPrice(double price) {
this.price = price;
}
public void setChange(double change) {
this.change = change;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.shared;
import java.io.Serializable;
public class StockBuy implements Serializable {
/** */
private static final long serialVersionUID = -5423954446375892903L;
private String symbol;
private Double price;
private Long count;
public StockBuy() {
}
public StockBuy(String symbol, Double price, Long count) {
this.symbol = symbol;
this.price = price;
this.count = count;
}
public String getSymbol() {
return this.symbol;
}
public double getPrice() {
return this.price;
}
public long getCount() {
return count;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.sample.stockwatcher.client.event.BuyStockEvent;
import com.google.gwt.sample.stockwatcher.client.event.BuyStockEventHandler;
import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEvent;
import com.google.gwt.sample.stockwatcher.client.event.ShowStockWaterEventHandler;
import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenter;
import com.google.gwt.sample.stockwatcher.client.presenter.BuyStockPresenterImpl;
import com.google.gwt.sample.stockwatcher.client.presenter.Presenter;
import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenter;
import com.google.gwt.sample.stockwatcher.client.presenter.StockWatcherPresenterImpl;
import com.google.gwt.sample.stockwatcher.client.service.StockPriceService;
import com.google.gwt.sample.stockwatcher.client.service.StockPriceServiceAsync;
import com.google.gwt.sample.stockwatcher.client.view.BuyStockView;
import com.google.gwt.sample.stockwatcher.client.view.Display;
import com.google.gwt.sample.stockwatcher.client.view.StockWatcherView;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.RootPanel;
public class StockWatcherMVP implements EntryPoint {
private StockPriceServiceAsync stockPriceSvc = GWT
.create(StockPriceService.class);
private static HandlerManager eventBus = new HandlerManager(null);
/**
* Entry point method.
*/
public void onModuleLoad() {
bind();
openStockWater();
}
private void openStockWater() {
StockWatcherView view = new StockWatcherView();
StockWatcherPresenter presenter = new StockWatcherPresenterImpl(stockPriceSvc, eventBus, view);
presenter.bind();
view.setPresenter(presenter);
displayView(presenter, RootPanel.get("stockList"));
}
private void displayView(Presenter<? extends Display> presenter, HasWidgets container) {
container.clear();
container.add(presenter.getDisplay().asWidget());
}
private void bind() {
eventBus.addHandler(BuyStockEvent.TYPE, new BuyStockEventHandler() {
@Override
public void onBuyStock(BuyStockEvent event) {
BuyStockView view = new BuyStockView();
BuyStockPresenter presenter = new BuyStockPresenterImpl(
stockPriceSvc, eventBus, view, event.getStockPrice());
presenter.bind();
view.setPresenter(presenter);
displayView(presenter, RootPanel.get("stockList"));
}
});
eventBus.addHandler(ShowStockWaterEvent.TYPE,
new ShowStockWaterEventHandler() {
@Override
public void onShowStockWater(ShowStockWaterEvent event) {
openStockWater();
}
});
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.event;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
public class BuyStockEvent extends GwtEvent<BuyStockEventHandler> {
private StockPrice stockPrice;
public BuyStockEvent(StockPrice stockPrice) {
super();
this.stockPrice = stockPrice;
}
public static Type<BuyStockEventHandler> TYPE = new Type<BuyStockEventHandler>();
@Override
protected void dispatch(BuyStockEventHandler handler) {
handler.onBuyStock(this);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<BuyStockEventHandler> getAssociatedType() {
// TODO Auto-generated method stub
return TYPE;
}
public StockPrice getStockPrice() {
return stockPrice;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface BuyStockEventHandler extends EventHandler {
void onBuyStock(BuyStockEvent event);
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.event;
import com.google.gwt.event.shared.GwtEvent;
public class ShowStockWaterEvent extends GwtEvent<ShowStockWaterEventHandler> {
public ShowStockWaterEvent() {
super();
}
public static Type<ShowStockWaterEventHandler> TYPE = new Type<ShowStockWaterEventHandler>();
@Override
protected void dispatch(ShowStockWaterEventHandler handler) {
handler.onShowStockWater(this);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<ShowStockWaterEventHandler> getAssociatedType() {
// TODO Auto-generated method stub
return TYPE;
}
}
|
Java
|
package com.google.gwt.sample.stockwatcher.client.event;
import com.google.gwt.event.shared.EventHandler;
public interface ShowStockWaterEventHandler extends EventHandler {
void onShowStockWater(ShowStockWaterEvent event);
}
|
Java
|
package com.google.gwt.sample.stockwatcher.server;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import com.google.gwt.sample.stockwatcher.client.service.StockPriceService;
import com.google.gwt.sample.stockwatcher.client.shared.StockBuy;
import com.google.gwt.sample.stockwatcher.client.shared.StockPrice;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class StockPriceServiceImpl extends RemoteServiceServlet implements
StockPriceService {
/** */
private static final long serialVersionUID = 155669477848585224L;
private static final double MAX_PRICE = 100.0; // $100.00
private static final double MAX_PRICE_CHANGE = 0.02; // +/- 2%
private static List<StockBuy> buyingHistory = new LinkedList<StockBuy>();
@Override
public StockPrice[] getPrices(List<String> symbols) {
Random rnd = new Random();
StockPrice[] prices = new StockPrice[symbols.size()];
for (int i = 0; i < symbols.size(); i++) {
double price = rnd.nextDouble() * MAX_PRICE;
double change = price * MAX_PRICE_CHANGE
* (rnd.nextDouble() * 2f - 1f);
prices[i] = new StockPrice(symbols.get(i), price, change);
}
return prices;
}
// =====================================================
@Override
public StockBuy buyStock(StockBuy stockBuy) {
buyingHistory.add(stockBuy);
return stockBuy;
}
@Override
public List<StockBuy> getStockBuyingHistory() {
return buyingHistory;
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
/**
* A dialog-like floating activity
* @author Kevin Yuan
*
*/
public class Floating extends Activity {
private static final int[] BUTTONS = {R.id.button1, R.id.button2, R.id.button3};
private View mView;
private ViewGroup mContentViewContainer;
private Content mContent;
@Override
public void onCreate(Bundle savedInstanceState) {
// It will not work if we setTheme here.
// Please add android:theme="@android:style/Theme.Dialog" to any descendant class in AndroidManifest.xml!
// See http://code.google.com/p/android/issues/detail?id=4394
// setTheme(android.R.style.Theme_Dialog);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
mView = View.inflate(this, R.layout.floating, null);
final DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
mView.setMinimumWidth(Math.min(dm.widthPixels, dm.heightPixels) - 20);
setContentView(mView);
mContentViewContainer = (ViewGroup) mView.findViewById(R.id.content);
}
private void setDialogContentView(final View contentView) {
mContentViewContainer.removeAllViews();
mContentViewContainer.addView(contentView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
public void setContent(Content content) {
mContent = content;
refreshContent();
}
public void refreshContent() {
setDialogContentView(mContent.getView());
((TextView)findViewById(R.id.title)).setText(mContent.getTitle());
final int btnCount = mContent.getButtonCount();
if(btnCount > BUTTONS.length) {
throw new RuntimeException(String.format("%d exceeds maximum button count: %d!", btnCount, BUTTONS.length));
}
findViewById(R.id.buttons_view).setVisibility(btnCount > 0 ? View.VISIBLE : View.GONE);
for(int buttonId:BUTTONS) {
final Button btn = (Button) findViewById(buttonId);
btn.setOnClickListener(null);
btn.setVisibility(View.GONE);
}
for(int btnIndex = 0; btnIndex < btnCount; btnIndex++){
final Button btn = (Button)findViewById(BUTTONS[btnIndex]);
btn.setText(mContent.getButtonText(btnIndex));
btn.setVisibility(View.VISIBLE);
btn.setOnClickListener(mContent.getButtonOnClickListener(btnIndex));
}
}
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(mContent != null) {
mContent.onCreateContextMenu(menu, v, menuInfo);
}
}
public boolean onContextItemSelected (MenuItem item) {
if(mContent != null) {
return mContent.onContextItemSelected(item);
}
return false;
}
public interface Content {
CharSequence getTitle();
View getView();
int getButtonCount();
CharSequence getButtonText(int index);
OnClickListener getButtonOnClickListener(int index);
void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo);
boolean onContextItemSelected (MenuItem item);
}
}
|
Java
|
package com.farproc.wifi.connecter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.PairwiseCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.text.TextUtils;
import android.util.Log;
public class ConfigurationSecuritiesOld extends ConfigurationSecurities {
// Constants used for different security types
public static final String WPA2 = "WPA2";
public static final String WPA = "WPA";
public static final String WEP = "WEP";
public static final String OPEN = "Open";
// For EAP Enterprise fields
public static final String WPA_EAP = "WPA-EAP";
public static final String IEEE8021X = "IEEE8021X";
public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" };
public static final int WEP_PASSWORD_AUTO = 0;
public static final int WEP_PASSWORD_ASCII = 1;
public static final int WEP_PASSWORD_HEX = 2;
static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X };
private static final String TAG = "ConfigurationSecuritiesOld";
@Override
public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {
if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) {
// If we never set group ciphers, wpa_supplicant puts all of them.
// For open, we don't set group ciphers.
// For WEP, we specifically only set WEP40 and WEP104, so CCMP
// and TKIP should not be there.
if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP)
&&
(wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40)
|| wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) {
return WEP;
} else {
return OPEN;
}
} else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) {
return WPA2;
} else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
return WPA_EAP;
} else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return IEEE8021X;
} else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) {
return WPA;
} else {
Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open.");
return OPEN;
}
}
@Override
public String getScanResultSecurity(ScanResult scanResult) {
final String cap = scanResult.capabilities;
for (int i = SECURITY_MODES.length - 1; i >= 0; i--) {
if (cap.contains(SECURITY_MODES[i])) {
return SECURITY_MODES[i];
}
}
return OPEN;
}
@Override
public String getDisplaySecirityString(final ScanResult scanResult) {
return getScanResultSecurity(scanResult);
}
private static boolean isHexWepKey(String wepKey) {
final int len = wepKey.length();
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len != 10 && len != 26 && len != 58) {
return false;
}
return isHex(wepKey);
}
private static boolean isHex(String key) {
for (int i = key.length() - 1; i >= 0; i--) {
final char c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
return false;
}
}
return true;
}
@Override
public void setupSecurity(WifiConfiguration config, String security, final String password) {
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
if (TextUtils.isEmpty(security)) {
security = OPEN;
Log.w(TAG, "Empty security, assuming open");
}
if (security.equals(WEP)) {
int wepPasswordType = WEP_PASSWORD_AUTO;
// If password is empty, it should be left untouched
if (!TextUtils.isEmpty(password)) {
if (wepPasswordType == WEP_PASSWORD_AUTO) {
if (isHexWepKey(password)) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = Wifi.convertToQuotedString(password);
}
} else {
config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII
? Wifi.convertToQuotedString(password)
: password;
}
}
config.wepTxKeyIndex = 0;
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedGroupCiphers.set(GroupCipher.WEP40);
config.allowedGroupCiphers.set(GroupCipher.WEP104);
} else if (security.equals(WPA) || security.equals(WPA2)){
config.allowedGroupCiphers.set(GroupCipher.TKIP);
config.allowedGroupCiphers.set(GroupCipher.CCMP);
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);
config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA);
// If password is empty, it should be left untouched
if (!TextUtils.isEmpty(password)) {
if (password.length() == 64 && isHex(password)) {
// Goes unquoted as hex
config.preSharedKey = password;
} else {
// Goes quoted as ASCII
config.preSharedKey = Wifi.convertToQuotedString(password);
}
}
} else if (security.equals(OPEN)) {
config.allowedKeyManagement.set(KeyMgmt.NONE);
} else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) {
config.allowedGroupCiphers.set(GroupCipher.TKIP);
config.allowedGroupCiphers.set(GroupCipher.CCMP);
if (security.equals(WPA_EAP)) {
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
} else {
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
}
if (!TextUtils.isEmpty(password)) {
config.preSharedKey = Wifi.convertToQuotedString(password);
}
}
}
@Override
public boolean isOpenNetwork(String security) {
return OPEN.equals(security);
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class NewNetworkContent extends BaseContent {
private boolean mIsOpenNetwork = false;
public NewNetworkContent(final Floating floating, final WifiManager wifiManager, ScanResult scanResult) {
super(floating, wifiManager, scanResult);
mView.findViewById(R.id.Status).setVisibility(View.GONE);
mView.findViewById(R.id.Speed).setVisibility(View.GONE);
mView.findViewById(R.id.IPAddress).setVisibility(View.GONE);
if(Wifi.ConfigSec.isOpenNetwork(mScanResultSecurity)) {
mIsOpenNetwork = true;
mView.findViewById(R.id.Password).setVisibility(View.GONE);
} else {
((TextView)mView.findViewById(R.id.Password_TextView)).setText(R.string.please_type_passphrase);
}
}
private OnClickListener mConnectOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
boolean connResult;
if(mIsOpenNetwork) {
connResult = Wifi.connectToNewNetwork(mFloating, mWifiManager, mScanResult, null, mNumOpenNetworksKept);
} else {
connResult = Wifi.connectToNewNetwork(mFloating, mWifiManager, mScanResult
, ((EditText)mView.findViewById(R.id.Password_EditText)).getText().toString()
, mNumOpenNetworksKept);
}
if(!connResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
}
};
private OnClickListener mOnClickListeners[] = {mConnectOnClick, mCancelOnClick};
@Override
public int getButtonCount() {
return 2;
}
@Override
public OnClickListener getButtonOnClickListener(int index) {
return mOnClickListeners[index];
}
@Override
public CharSequence getButtonText(int index) {
switch(index) {
case 0:
return mFloating.getText(R.string.connect);
case 1:
return getCancelString();
default:
return null;
}
}
@Override
public CharSequence getTitle() {
return mFloating.getString(R.string.wifi_connect_to, mScanResult.SSID);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ChangePasswordContent extends BaseContent {
private ChangingAwareEditText mPasswordEditText;
public ChangePasswordContent(Floating floating, WifiManager wifiManager,
ScanResult scanResult) {
super(floating, wifiManager, scanResult);
mView.findViewById(R.id.Status).setVisibility(View.GONE);
mView.findViewById(R.id.Speed).setVisibility(View.GONE);
mView.findViewById(R.id.IPAddress).setVisibility(View.GONE);
mPasswordEditText = ((ChangingAwareEditText)mView.findViewById(R.id.Password_EditText));
((TextView)mView.findViewById(R.id.Password_TextView)).setText(R.string.please_type_passphrase);
((EditText)mView.findViewById(R.id.Password_EditText)).setHint(R.string.wifi_password_unchanged);
}
@Override
public int getButtonCount() {
return 2;
}
@Override
public OnClickListener getButtonOnClickListener(int index) {
return mOnClickListeners[index];
}
@Override
public CharSequence getButtonText(int index) {
switch(index) {
case 0:
return mFloating.getString(R.string.wifi_save_config);
case 1:
return getCancelString();
default:
return null;
}
}
@Override
public CharSequence getTitle() {
return mScanResult.SSID;
}
private OnClickListener mSaveOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
if(mPasswordEditText.getChanged()) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean saveResult = false;
if(config != null) {
saveResult = Wifi.changePasswordAndConnect(mFloating, mWifiManager, config
, mPasswordEditText.getText().toString()
, mNumOpenNetworksKept);
}
if(!saveResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
}
mFloating.finish();
}
};
OnClickListener mOnClickListeners[] = {mSaveOnClick, mCancelOnClick};
@Override
public boolean onContextItemSelected(MenuItem item) {
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
}
}
|
Java
|
package com.farproc.wifi.connecter;
import java.lang.reflect.Field;
import android.os.Build.VERSION;;
/**
* Get Android version in different Android versions. :)
* @author yuanxiaohui
*
*/
public class Version {
public final static int SDK = get();
private static int get() {
final Class<VERSION> versionClass = VERSION.class;
try {
// First try to read the recommended field android.os.Build.VERSION.SDK_INT.
final Field sdkIntField = versionClass.getField("SDK_INT");
return sdkIntField.getInt(null);
}catch (NoSuchFieldException e) {
// If SDK_INT does not exist, read the deprecated field SDK.
return Integer.valueOf(VERSION.SDK);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public abstract class BaseContent implements Floating.Content, OnCheckedChangeListener {
protected final WifiManager mWifiManager;
protected final Floating mFloating;
protected final ScanResult mScanResult;
protected final String mScanResultSecurity;
protected final boolean mIsOpenNetwork ;
protected int mNumOpenNetworksKept;
protected View mView;
protected OnClickListener mCancelOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
mFloating.finish();
}
};
protected String getCancelString() {
return mFloating.getString(android.R.string.cancel);
}
private static final int[] SIGNAL_LEVEL = {R.string.wifi_signal_0, R.string.wifi_signal_1,
R.string.wifi_signal_2, R.string.wifi_signal_3};
public BaseContent(final Floating floating, final WifiManager wifiManager, final ScanResult scanResult) {
super();
mWifiManager = wifiManager;
mFloating = floating;
mScanResult = scanResult;
mScanResultSecurity = Wifi.ConfigSec.getScanResultSecurity(mScanResult);
mIsOpenNetwork = Wifi.ConfigSec.isOpenNetwork(mScanResultSecurity);
mView = View.inflate(mFloating, R.layout.base_content, null);
((TextView)mView.findViewById(R.id.SignalStrength_TextView)).setText(SIGNAL_LEVEL[WifiManager.calculateSignalLevel(mScanResult.level, SIGNAL_LEVEL.length)]);
final String rawSecurity = Wifi.ConfigSec.getDisplaySecirityString(mScanResult);
final String readableSecurity = Wifi.ConfigSec.isOpenNetwork(rawSecurity) ? mFloating.getString(R.string.wifi_security_open) : rawSecurity;
((TextView)mView.findViewById(R.id.Security_TextView)).setText(readableSecurity);
((CheckBox)mView.findViewById(R.id.ShowPassword_CheckBox)).setOnCheckedChangeListener(this);
mNumOpenNetworksKept = Settings.Secure.getInt(floating.getContentResolver(),
Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10);
}
@Override
public View getView() {
return mView;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
((EditText)mView.findViewById(R.id.Password_EditText)).setInputType(
InputType.TYPE_CLASS_TEXT |
(isChecked ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
:InputType.TYPE_TEXT_VARIATION_PASSWORD));
}
public OnClickListener mChangePasswordOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
changePassword();
}
};
public void changePassword() {
mFloating.setContent(new ChangePasswordContent(mFloating, mWifiManager, mScanResult));
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
public class ChangingAwareEditText extends EditText {
public ChangingAwareEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
private boolean mChanged = false;
public boolean getChanged() {
return mChanged;
}
protected void onTextChanged (CharSequence text, int start, int before, int after) {
mChanged = true;
}
}
|
Java
|
package com.farproc.wifi.connecter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
public abstract class ConfigurationSecurities {
/**
* @return The security of a given {@link WifiConfiguration}.
*/
public abstract String getWifiConfigurationSecurity(WifiConfiguration wifiConfig);
/**
* @return The security of a given {@link ScanResult}.
*/
public abstract String getScanResultSecurity(ScanResult scanResult);
/**
* Fill in the security fields of WifiConfiguration config.
* @param config The object to fill.
* @param security If is OPEN, password is ignored.
* @param password Password of the network if security is not OPEN.
*/
public abstract void setupSecurity(WifiConfiguration config, String security, final String password);
public abstract String getDisplaySecirityString(final ScanResult scanResult);
public abstract boolean isOpenNetwork(final String security);
public static ConfigurationSecurities newInstance() {
if(Version.SDK < 8) {
return new ConfigurationSecuritiesOld();
} else {
return new ConfigurationSecuritiesV8();
}
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import android.widget.TwoLineListItem;
import android.widget.AdapterView.OnItemClickListener;
public class TestWifiScan extends ListActivity {
private WifiManager mWifiManager;
private List<ScanResult> mScanResults;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
setListAdapter(mListAdapter);
getListView().setOnItemClickListener(mItemOnClick);
}
@Override
public void onResume() {
super.onResume();
final IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(mReceiver, filter);
mWifiManager.startScan();
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
mScanResults = mWifiManager.getScanResults();
mListAdapter.notifyDataSetChanged();
mWifiManager.startScan();
}
}
};
private BaseAdapter mListAdapter = new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null || !(convertView instanceof TwoLineListItem)) {
convertView = View.inflate(getApplicationContext(),
android.R.layout.simple_list_item_2, null);
}
final ScanResult result = mScanResults.get(position);
((TwoLineListItem)convertView).getText1().setText(result.SSID);
((TwoLineListItem)convertView).getText2().setText(
String.format("%s %d", result.BSSID, result.level)
);
return convertView;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getCount() {
return mScanResults == null ? 0 : mScanResults.size();
}
};
private OnItemClickListener mItemOnClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
final ScanResult result = mScanResults.get(position);
launchWifiConnecter(TestWifiScan.this, result);
}
};
/**
* Try to launch Wifi Connecter with {@link #hostspot}. Prompt user to download if Wifi Connecter is not installed.
* @param activity
* @param hotspot
*/
private static void launchWifiConnecter(final Activity activity, final ScanResult hotspot) {
final Intent intent = new Intent("com.farproc.wifi.connecter.action.CONNECT_OR_EDIT");
intent.putExtra("com.farproc.wifi.connecter.extra.HOTSPOT", hotspot);
try {
activity.startActivity(intent);
} catch(ActivityNotFoundException e) {
// Wifi Connecter Library is not installed.
Toast.makeText(activity, "Wifi Connecter is not installed.", Toast.LENGTH_LONG).show();
downloadWifiConnecter(activity);
}
}
private static void downloadWifiConnecter(final Activity activity) {
Intent downloadIntent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id=com.farproc.wifi.connecter"));
try {
activity.startActivity(downloadIntent);
Toast.makeText(activity, "Please install this app.", Toast.LENGTH_LONG).show();
} catch (ActivityNotFoundException e) {
// Market app is not available in this device.
// Show download page of this project.
try {
downloadIntent.setData(Uri.parse("http://code.google.com/p/android-wifi-connecter/downloads/list"));
activity.startActivity(downloadIntent);
Toast.makeText(activity, "Please download the apk and install it manully.", Toast.LENGTH_LONG).show();
} catch (ActivityNotFoundException e2) {
// Even the Browser app is not available!!!!!
// Show a error message!
Toast.makeText(activity, "Fatel error! No web browser app in your device!!!", Toast.LENGTH_LONG).show();
}
}
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class ConfiguredNetworkContent extends BaseContent {
public ConfiguredNetworkContent(Floating floating, WifiManager wifiManager,
ScanResult scanResult) {
super(floating, wifiManager, scanResult);
mView.findViewById(R.id.Status).setVisibility(View.GONE);
mView.findViewById(R.id.Speed).setVisibility(View.GONE);
mView.findViewById(R.id.IPAddress).setVisibility(View.GONE);
mView.findViewById(R.id.Password).setVisibility(View.GONE);
}
@Override
public int getButtonCount() {
return 3;
}
@Override
public OnClickListener getButtonOnClickListener(int index) {
switch(index) {
case 0:
return mConnectOnClick;
case 1:
if(mIsOpenNetwork) {
return mForgetOnClick;
} else {
return mOpOnClick;
}
case 2:
return mCancelOnClick;
default:
return null;
}
}
@Override
public CharSequence getButtonText(int index) {
switch(index) {
case 0:
return mFloating.getString(R.string.connect);
case 1:
if(mIsOpenNetwork) {
return mFloating.getString(R.string.forget_network);
} else {
return mFloating.getString(R.string.buttonOp);
}
case 2:
return getCancelString();
default:
return null;
}
}
@Override
public CharSequence getTitle() {
return mFloating.getString(R.string.wifi_connect_to, mScanResult.SSID);
}
private OnClickListener mConnectOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean connResult = false;
if(config != null) {
connResult = Wifi.connectToConfiguredNetwork(mFloating, mWifiManager, config, false);
}
if(!connResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
}
};
private OnClickListener mOpOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
mFloating.registerForContextMenu(v);
mFloating.openContextMenu(v);
mFloating.unregisterForContextMenu(v);
}
};
private OnClickListener mForgetOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
forget();
}
};
private void forget() {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean result = false;
if(config != null) {
result = mWifiManager.removeNetwork(config.networkId)
&& mWifiManager.saveConfiguration();
}
if(!result) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
}
private static final int MENU_FORGET = 0;
private static final int MENU_CHANGE_PASSWORD = 1;
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case MENU_FORGET:
forget();
break;
case MENU_CHANGE_PASSWORD:
changePassword();
break;
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, MENU_FORGET, Menu.NONE, R.string.forget_network);
menu.add(Menu.NONE, MENU_CHANGE_PASSWORD, Menu.NONE, R.string.wifi_change_password);
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import java.util.List;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.IBinder;
public class ReenableAllApsWhenNetworkStateChanged {
public static void schedule(final Context ctx) {
ctx.startService(new Intent(ctx, BackgroundService.class));
}
private static void reenableAllAps(final Context ctx) {
final WifiManager wifiMgr = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
if(configurations != null) {
for(final WifiConfiguration config:configurations) {
wifiMgr.enableNetwork(config.networkId, false);
}
}
}
public static class BackgroundService extends Service {
private boolean mReenabled;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState();
if(detailed != NetworkInfo.DetailedState.DISCONNECTED
&& detailed != NetworkInfo.DetailedState.DISCONNECTING
&& detailed != NetworkInfo.DetailedState.SCANNING) {
if(!mReenabled) {
mReenabled = true;
reenableAllAps(context);
stopSelf();
}
}
}
}
};
private IntentFilter mIntentFilter;
@Override
public IBinder onBind(Intent intent) {
return null; // We need not bind to it at all.
}
@Override
public void onCreate() {
super.onCreate();
mReenabled = false;
mIntentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(mReceiver, mIntentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
}
|
Java
|
package com.farproc.wifi.connecter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.util.Log;
public class ConfigurationSecuritiesV8 extends ConfigurationSecurities {
static final int SECURITY_NONE = 0;
static final int SECURITY_WEP = 1;
static final int SECURITY_PSK = 2;
static final int SECURITY_EAP = 3;
enum PskType {
UNKNOWN,
WPA,
WPA2,
WPA_WPA2
}
private static final String TAG = "ConfigurationSecuritiesV14";
private static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
private static int getSecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
@Override
public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) {
return String.valueOf(getSecurity(wifiConfig));
}
@Override
public String getScanResultSecurity(ScanResult scanResult) {
return String.valueOf(getSecurity(scanResult));
}
@Override
public void setupSecurity(WifiConfiguration config, String security, String password) {
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
final int sec = security == null ? SECURITY_NONE : Integer.valueOf(security);
final int passwordLen = password == null ? 0 : password.length();
switch (sec) {
case SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
break;
case SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (passwordLen != 0) {
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) &&
password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
break;
case SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (passwordLen != 0) {
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
break;
case SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
// config.eap.setValue((String) mEapMethodSpinner.getSelectedItem());
//
// config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition() == 0) ? "" :
// "auth=" + mPhase2Spinner.getSelectedItem());
// config.ca_cert.setValue((mEapCaCertSpinner.getSelectedItemPosition() == 0) ? "" :
// KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
// (String) mEapCaCertSpinner.getSelectedItem());
// config.client_cert.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.private_key.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ?
// "" : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
// (String) mEapUserCertSpinner.getSelectedItem());
// config.identity.setValue((mEapIdentityView.length() == 0) ? "" :
// mEapIdentityView.getText().toString());
// config.anonymous_identity.setValue((mEapAnonymousView.length() == 0) ? "" :
// mEapAnonymousView.getText().toString());
// if (mPasswordView.length() != 0) {
// config.password.setValue(mPasswordView.getText().toString());
// }
break;
default:
Log.e(TAG, "Invalid security type: " + sec);
}
// config.proxySettings = mProxySettings;
// config.ipAssignment = mIpAssignment;
// config.linkProperties = new LinkProperties(mLinkProperties);
}
private static PskType getPskType(ScanResult result) {
boolean wpa = result.capabilities.contains("WPA-PSK");
boolean wpa2 = result.capabilities.contains("WPA2-PSK");
if (wpa2 && wpa) {
return PskType.WPA_WPA2;
} else if (wpa2) {
return PskType.WPA2;
} else if (wpa) {
return PskType.WPA;
} else {
Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
return PskType.UNKNOWN;
}
}
@Override
public String getDisplaySecirityString(final ScanResult scanResult) {
final int security = getSecurity(scanResult);
if(security == SECURITY_PSK) {
switch(getPskType(scanResult)) {
case WPA:
return "WPA";
case WPA_WPA2:
case WPA2:
return "WPA2";
default:
return "?";
}
} else {
switch(security) {
case SECURITY_NONE:
return "OPEN";
case SECURITY_WEP:
return "WEP";
case SECURITY_EAP:
return "EAP";
}
}
return "?";
}
@Override
public boolean isOpenNetwork(String security) {
return String.valueOf(SECURITY_NONE).equals(security);
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;
public class Wifi {
public static final ConfigurationSecurities ConfigSec = ConfigurationSecurities.newInstance();
private static final String TAG = "Wifi Connecter";
/**
* Change the password of an existing configured network and connect to it
* @param wifiMgr
* @param config
* @param newPassword
* @return
*/
public static boolean changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) {
ConfigSec.setupSecurity(config, ConfigSec.getWifiConfigurationSecurity(config), newPassword);
final int networkId = wifiMgr.updateNetwork(config);
if(networkId == -1) {
// Update failed.
return false;
}
// Force the change to apply.
wifiMgr.disconnect();
return connectToConfiguredNetwork(ctx, wifiMgr, config, true);
}
/**
* Configure a network, and connect to it.
* @param wifiMgr
* @param scanResult
* @param password Password for secure network or is ignored.
* @return
*/
public static boolean connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) {
final String security = ConfigSec.getScanResultSecurity(scanResult);
if(ConfigSec.isOpenNetwork(security)) {
checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept);
}
WifiConfiguration config = new WifiConfiguration();
config.SSID = convertToQuotedString(scanResult.SSID);
config.BSSID = scanResult.BSSID;
ConfigSec.setupSecurity(config, security, password);
int id = -1;
try {
id = wifiMgr.addNetwork(config);
} catch(NullPointerException e) {
Log.e(TAG, "Weird!! Really!! What's wrong??", e);
// Weird!! Really!!
// This exception is reported by user to Android Developer Console(https://market.android.com/publish/Home)
}
if(id == -1) {
return false;
}
if(!wifiMgr.saveConfiguration()) {
return false;
}
config = getWifiConfiguration(wifiMgr, config, security);
if(config == null) {
return false;
}
return connectToConfiguredNetwork(ctx, wifiMgr, config, true);
}
/**
* Connect to a configured network.
* @param wifiManager
* @param config
* @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT
* @return
*/
public static boolean connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) {
final String security = ConfigSec.getWifiConfigurationSecurity(config);
int oldPri = config.priority;
// Make it the highest priority.
int newPri = getMaxPriority(wifiMgr) + 1;
if(newPri > MAX_PRIORITY) {
newPri = shiftPriorityAndSave(wifiMgr);
config = getWifiConfiguration(wifiMgr, config, security);
if(config == null) {
return false;
}
}
// Set highest priority to this configured network
config.priority = newPri;
int networkId = wifiMgr.updateNetwork(config);
if(networkId == -1) {
return false;
}
// Do not disable others
if(!wifiMgr.enableNetwork(networkId, false)) {
config.priority = oldPri;
return false;
}
if(!wifiMgr.saveConfiguration()) {
config.priority = oldPri;
return false;
}
// We have to retrieve the WifiConfiguration after save.
config = getWifiConfiguration(wifiMgr, config, security);
if(config == null) {
return false;
}
ReenableAllApsWhenNetworkStateChanged.schedule(ctx);
// Disable others, but do not save.
// Just to force the WifiManager to connect to it.
if(!wifiMgr.enableNetwork(config.networkId, true)) {
return false;
}
final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect();
if(!connect) {
return false;
}
return true;
}
private static void sortByPriority(final List<WifiConfiguration> configurations) {
java.util.Collections.sort(configurations, new Comparator<WifiConfiguration>() {
@Override
public int compare(WifiConfiguration object1,
WifiConfiguration object2) {
return object1.priority - object2.priority;
}
});
}
/**
* Ensure no more than numOpenNetworksKept open networks in configuration list.
* @param wifiMgr
* @param numOpenNetworksKept
* @return Operation succeed or not.
*/
private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) {
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
sortByPriority(configurations);
boolean modified = false;
int tempCount = 0;
for(int i = configurations.size() - 1; i >= 0; i--) {
final WifiConfiguration config = configurations.get(i);
if(ConfigSec.isOpenNetwork(ConfigSec.getWifiConfigurationSecurity(config))) {
tempCount++;
if(tempCount >= numOpenNetworksKept) {
modified = true;
wifiMgr.removeNetwork(config.networkId);
}
}
}
if(modified) {
return wifiMgr.saveConfiguration();
}
return true;
}
private static final int MAX_PRIORITY = 99999;
private static int shiftPriorityAndSave(final WifiManager wifiMgr) {
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
sortByPriority(configurations);
final int size = configurations.size();
for(int i = 0; i < size; i++) {
final WifiConfiguration config = configurations.get(i);
config.priority = i;
wifiMgr.updateNetwork(config);
}
wifiMgr.saveConfiguration();
return size;
}
private static int getMaxPriority(final WifiManager wifiManager) {
final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
int pri = 0;
for(final WifiConfiguration config : configurations) {
if(config.priority > pri) {
pri = config.priority;
}
}
return pri;
}
public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final ScanResult hotsopt, String hotspotSecurity) {
final String ssid = convertToQuotedString(hotsopt.SSID);
if(ssid.length() == 0) {
return null;
}
final String bssid = hotsopt.BSSID;
if(bssid == null) {
return null;
}
if(hotspotSecurity == null) {
hotspotSecurity = ConfigSec.getScanResultSecurity(hotsopt);
}
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
if(configurations == null) {
return null;
}
for(final WifiConfiguration config : configurations) {
if(config.SSID == null || !ssid.equals(config.SSID)) {
continue;
}
if(config.BSSID == null || bssid.equals(config.BSSID)) {
final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config);
if(hotspotSecurity.equals(configSecurity)) {
return config;
}
}
}
return null;
}
public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final WifiConfiguration configToFind, String security) {
final String ssid = configToFind.SSID;
if(ssid.length() == 0) {
return null;
}
final String bssid = configToFind.BSSID;
if(security == null) {
security = ConfigSec.getWifiConfigurationSecurity(configToFind);
}
final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
for(final WifiConfiguration config : configurations) {
if(config.SSID == null || !ssid.equals(config.SSID)) {
continue;
}
if(config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) {
final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config);
if(security.equals(configSecurity)) {
return config;
}
}
}
return null;
}
public static String convertToQuotedString(String string) {
if (TextUtils.isEmpty(string)) {
return "";
}
final int lastPos = string.length() - 1;
if(lastPos > 0 && (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) {
return string;
}
return "\"" + string + "\"";
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Floating {
public static final String EXTRA_HOTSPOT = "com.farproc.wifi.connecter.extra.HOTSPOT";
private ScanResult mScanResult;
private Floating.Content mContent;
private WifiManager mWifiManager;
@Override
protected void onNewIntent (Intent intent) {
setIntent(intent);
// This activity has "singleInstance" launch mode.
// Update content to reflect the newest intent.
doNewIntent(intent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
doNewIntent(getIntent());
}
private boolean isAdHoc(final ScanResult scanResule) {
return scanResule.capabilities.indexOf("IBSS") != -1;
}
private void doNewIntent(final Intent intent) {
mScanResult = intent.getParcelableExtra(EXTRA_HOTSPOT);
if(mScanResult == null) {
Toast.makeText(this, "No data in Intent!", Toast.LENGTH_LONG).show();
finish();
return;
}
if(isAdHoc(mScanResult)) {
Toast.makeText(this, R.string.adhoc_not_supported_yet, Toast.LENGTH_LONG).show();
finish();
return;
}
final String security = Wifi.ConfigSec.getScanResultSecurity(mScanResult);
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, security);
if(config == null) {
mContent = new NewNetworkContent(this, mWifiManager, mScanResult);
} else {
final boolean isCurrentNetwork_ConfigurationStatus = config.status == WifiConfiguration.Status.CURRENT;
final WifiInfo info = mWifiManager.getConnectionInfo();
final boolean isCurrentNetwork_WifiInfo = info != null
&& android.text.TextUtils.equals(info.getSSID(), mScanResult.SSID)
&& android.text.TextUtils.equals(info.getBSSID(), mScanResult.BSSID);
if(isCurrentNetwork_ConfigurationStatus || isCurrentNetwork_WifiInfo) {
mContent = new CurrentNetworkContent(this, mWifiManager, mScanResult);
} else {
mContent = new ConfiguredNetworkContent(this, mWifiManager, mScanResult);
}
}
setContent(mContent);
}
}
|
Java
|
/*
* Wifi Connecter
*
* Copyright (c) 20101 Kevin Yuan (farproc@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**/
package com.farproc.wifi.connecter;
import com.farproc.wifi.connecter.R;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class CurrentNetworkContent extends BaseContent {
public CurrentNetworkContent(Floating floating, WifiManager wifiManager,
ScanResult scanResult) {
super(floating, wifiManager, scanResult);
mView.findViewById(R.id.Status).setVisibility(View.GONE);
mView.findViewById(R.id.Speed).setVisibility(View.GONE);
mView.findViewById(R.id.IPAddress).setVisibility(View.GONE);
mView.findViewById(R.id.Password).setVisibility(View.GONE);
final WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
if(wifiInfo == null) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
} else {
final SupplicantState state = wifiInfo.getSupplicantState();
final NetworkInfo.DetailedState detailedState = WifiInfo.getDetailedStateOf(state);
if(detailedState == NetworkInfo.DetailedState.CONNECTED
|| (detailedState == NetworkInfo.DetailedState.OBTAINING_IPADDR && wifiInfo.getIpAddress() != 0)) {
mView.findViewById(R.id.Status).setVisibility(View.VISIBLE);
mView.findViewById(R.id.Speed).setVisibility(View.VISIBLE);
mView.findViewById(R.id.IPAddress).setVisibility(View.VISIBLE);
((TextView)mView.findViewById(R.id.Status_TextView)).setText(R.string.status_connected);
((TextView)mView.findViewById(R.id.LinkSpeed_TextView)).setText(wifiInfo.getLinkSpeed() + " " + WifiInfo.LINK_SPEED_UNITS);
((TextView)mView.findViewById(R.id.IPAddress_TextView)).setText(getIPAddress(wifiInfo.getIpAddress()));
} else if(detailedState == NetworkInfo.DetailedState.AUTHENTICATING
|| detailedState == NetworkInfo.DetailedState.CONNECTING
|| detailedState == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
mView.findViewById(R.id.Status).setVisibility(View.VISIBLE);
((TextView)mView.findViewById(R.id.Status_TextView)).setText(R.string.status_connecting);
}
}
}
@Override
public int getButtonCount() {
// No Modify button for open network.
return mIsOpenNetwork ? 2 : 3;
}
@Override
public OnClickListener getButtonOnClickListener(int index) {
if(mIsOpenNetwork && index == 1) {
// No Modify button for open network.
// index 1 is Cancel(index 2).
return mOnClickListeners[2];
}
return mOnClickListeners[index];
}
@Override
public CharSequence getButtonText(int index) {
switch(index) {
case 0:
return mFloating.getString(R.string.forget_network);
case 1:
if(mIsOpenNetwork) {
// No Modify button for open network.
// index 1 is Cancel.
return getCancelString();
}
return mFloating.getString(R.string.button_change_password);
case 2:
return getCancelString();
default:
return null;
}
}
@Override
public CharSequence getTitle() {
return mScanResult.SSID;
}
private OnClickListener mForgetOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean result = false;
if(config != null) {
result = mWifiManager.removeNetwork(config.networkId)
&& mWifiManager.saveConfiguration();
}
if(!result) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
mFloating.finish();
}
};
private OnClickListener mOnClickListeners[] = {mForgetOnClick, mChangePasswordOnClick, mCancelOnClick};
private String getIPAddress(int address) {
StringBuilder sb = new StringBuilder();
sb.append(address & 0x000000FF).append(".")
.append((address & 0x0000FF00) >> 8).append(".")
.append((address & 0x00FF0000) >> 16).append(".")
.append((address & 0xFF000000L) >> 24);
return sb.toString();
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
}
}
|
Java
|
public class fdf {
}
|
Java
|
public @interface df {
}
|
Java
|
public class fdfd {
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.falcon4ever.fIRC3.service.ChatService;
import com.falcon4ever.fIRC3.service.ChatService.LocalBinder;
import com.falcon4ever.fIRC3.service.IRCConnection;
import com.falcon4ever.fIRC3.utils.DBProfileManager;
import com.falcon4ever.fIRC3.utils.ProfileState;
// TODO: Update server connection status
public class ServerlistActivity extends ListActivity {
private ArrayList<ProfileState> mServers = new ArrayList<ProfileState>();
private ServerlistAdapter mAdapter;
private ChatService mService;
private boolean mBound = false;
private Handler IncomingHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
// Initialize panels
case ChatService.MSG_UI_SERVERLIST_UPDATE:
{
updateConnectionStatus();
}
break;
default:
Log.e(getClass().getSimpleName(), "Unhandled message IncomingHandler " + msg.what);
}
}
};
private void updateConnectionStatus()
{
// Cycle over current server list
for(int i = 0; i < mServers.size(); i++)
{
mServers.get(i).setConnected(
mService.getConnectionStatus(
mServers.get(i).getProfileId()
)
);
}
mAdapter.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.serverlist);
// Set and Update listview
mAdapter = new ServerlistAdapter(this, R.layout.serverlist_row, mServers);
setListAdapter(mAdapter);
registerForContextMenu(getListView());
}
@Override
protected void onResume() {
super.onResume();
// Bind to LocalService
Intent intent = new Intent(this, ChatService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
queryProfiles();
}
@Override
protected void onPause() {
super.onPause();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
private void queryProfiles()
{
DBProfileManager db = new DBProfileManager(this);
ArrayList<ArrayList<Object>> profiles = db.getAllRowsAsArrays();
db.close();
mServers.clear();
for(int i = 0; i < profiles.size(); i++)
{
ArrayList<Object> values = profiles.get(i);
ProfileState ps = new ProfileState();
ps.setProfileId(Integer.parseInt(values.get(0).toString()));
ps.setProfileName(values.get(1).toString());
ps.setConnected(IRCConnection.CONNECTION_OFFLINE);
Log.d(getClass().getSimpleName(), "Loading: pID " + values.get(0).toString() + ", ProfileName " + values.get(1).toString());
mServers.add(ps);
}
mAdapter.notifyDataSetChanged();
}
///////////////////////////////////////////////////////////////////////////////////////////////
// ServiceConnection
///////////////////////////////////////////////////////////////////////////////////////////////
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
mService.setHandler(IncomingHandler);
updateConnectionStatus();
}
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mService.setHandler(null);
}
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Menu at bottom
///////////////////////////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.serverlist_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId())
{
case R.id.serverlist_new_profile:
{
Intent intent = new Intent();
intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ProfileActivity");
intent.putExtra("profile_type", "new_profile");
startActivity(intent);
}
return true;
case R.id.serverlist_connect_all:
if (mBound) {
mService.connectAll();
}
return true;
case R.id.serverlist_disconnect_all:
if (mBound) {
mService.disconnectAll();
}
// check status
return true;
case R.id.serverlist_help:
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.multigesture.net/projects/firc/"));
startActivity(browserIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Enter ChatView
///////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
if(mService.getConnectionStatus(mServers.get(position).getProfileId()) < 1)
{
Toast.makeText(this, "Profile is not connected", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent();
intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ChatActivity");
intent.putExtra("profile_id", mServers.get(position).getProfileId());
startActivity(intent);
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Context menu
///////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 0, 0, "Edit profile");
menu.add(0, 1, 0, "Remove profile");
menu.add(0, 2, 0, "Connect");
menu.add(0, 3, 0, "Disconnect");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
switch(item.getItemId())
{
case 0:
{
Intent intent = new Intent();
intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ProfileActivity");
intent.putExtra("profile_type", "edit_profile");
intent.putExtra("profile_id", mServers.get(info.position).getProfileId());
startActivity(intent);
}
break;
case 1:
{
// Disconnect !
mService.disconnect(mServers.get(info.position).getProfileId());
// Remove from service
DBProfileManager db = new DBProfileManager(this);
db.deleteRow(mServers.get(info.position).getProfileId());
db.close();
queryProfiles();
}
return true;
case 2:
{
// Connect
mService.connect(mServers.get(info.position).getProfileId());
}
break;
case 3:
{
// Disconnect
mService.disconnect(mServers.get(info.position).getProfileId());
}
break;
}
return super.onContextItemSelected(item);
}
///////////////////////////////////////////////////////////////////////////////////////////////
// ServerlistAdapter
///////////////////////////////////////////////////////////////////////////////////////////////
private class ServerlistAdapter extends ArrayAdapter<ProfileState> {
private ArrayList<ProfileState> mItems;
private LayoutInflater mInflater;
public ServerlistAdapter(Context context, int textViewResourceId, ArrayList<ProfileState> items) {
super(context, textViewResourceId, items);
mItems = items;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Inflate XML gui template
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.serverlist_row, parent, false);
}
// Get item from adapter
ProfileState o = mItems.get(position);
if (o != null)
{
// Get Views
TextView tvServerAddress = (TextView)convertView.findViewById(R.id.serverlist_profile);
TextView tvServerStatus = (TextView)convertView.findViewById(R.id.serverlist_status);
ImageView ivServerStatus = (ImageView)convertView.findViewById(R.id.serverlist_status_icon);
// Set Views
if(tvServerAddress != null)
{
tvServerAddress.setText("Profile: " + o.getProfile_name());
}
if(tvServerStatus != null)
{
if(o.getConnected() == IRCConnection.CONNECTION_OFFLINE)
tvServerStatus.setText("Status: Offline");
else if(o.getConnected() == IRCConnection.CONNECTION_CONNECTING)
tvServerStatus.setText("Status: Connecting...");
else if(o.getConnected() == IRCConnection.CONNECTION_ONLINE)
tvServerStatus.setText("Status: Online");
else
tvServerStatus.setText("Status: Unknown");
}
if(ivServerStatus != null)
{
if(o.getConnected() == IRCConnection.CONNECTION_OFFLINE)
ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_offline));
else if(o.getConnected() == IRCConnection.CONNECTION_CONNECTING)
ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_invisible));
else if(o.getConnected() == IRCConnection.CONNECTION_ONLINE)
ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_online));
else
ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_offline));
}
}
return convertView;
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.service;
public class DCCConnection {
// Used for incoming and outgoing transfers
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import android.util.Log;
import com.falcon4ever.fIRC3.utils.ChatMessage;
import com.falcon4ever.fIRC3.utils.ProfileState;
// http://www.ietf.org/rfc/rfc1459.txt
// http://www.zigwap.com/mirc/raw_events.php
// http://www.mirc.net/raws/
// TODO: Output to logfile on SDcard
public class IRCConnection implements Runnable {
// Thread
private Thread mIrcThread;
private volatile boolean mThreadDone = false;
// Connection
private Socket mIrcSocket = null;
private BufferedReader mIrcInput = null;
private BufferedWriter mIrcOutput = null;
private int mConnectionStatus = CONNECTION_OFFLINE;
public synchronized int getConnectionStatus() {
return mConnectionStatus;
}
// Profile and encoding
private ProfileState mProfile;
private String mEncoding;
private int mCurrentScreen = 0;
private ChatService mParent;
//[channel name][channel msg]
private HashMap<String, ArrayList<ChatMessage>> mChatMessagesList = new HashMap<String, ArrayList<ChatMessage>>();
private synchronized HashMap<String, ArrayList<ChatMessage>> getChatMessagesList() {
return mChatMessagesList;
}
private SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm"); // ("HH:mm:ss");
// Constants
public static final int MAX_CHAT_HISTORY = 1000;
public static final int CONNECTION_OFFLINE = 0;
public static final int CONNECTION_CONNECTING = 1;
public static final int CONNECTION_ONLINE = 2;
///////////////////////////////////////////////////////////////////////////////////////////////
// IRCConnection
///////////////////////////////////////////////////////////////////////////////////////////////
// Constructor
public IRCConnection(ProfileState profile, String encoding, ChatService parent)
{
mProfile = profile;
mEncoding = encoding;
mParent = parent;
mCurrentScreen = 0;
updateConnectionStatus(CONNECTION_OFFLINE);
}
public synchronized void updateConnectionStatus(int connectionStatus)
{
mConnectionStatus = connectionStatus;
if(mParent.getHandler() != null)
{
mParent.getHandler().obtainMessage(ChatService.MSG_UI_SERVERLIST_UPDATE).sendToTarget();
}
}
public void run()
{
addChannel("server");
Log.d(getClass().getSimpleName(), "Starting profile: " + mProfile.getProfile_name());
updateConnectionStatus(CONNECTION_CONNECTING);
try {
//1. creating a socket to connect to the server
mIrcSocket = new Socket(mProfile.getProfileServer(), mProfile.getProfilePort());
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Connected to " + mProfile.getProfileServer() + " in port " + mProfile.getProfilePort());
//2. get Input and Output streams
mIrcInput = new BufferedReader(new InputStreamReader(mIrcSocket.getInputStream(), mEncoding));
mIrcOutput = new BufferedWriter(new OutputStreamWriter(mIrcSocket.getOutputStream(), mEncoding));
mIrcOutput.flush();
// 4.1.2 Nick message TODO: set limit
int nickname_limit =9;
if(mProfile.getProfileNickname().length() > nickname_limit)
mProfile.setProfileName(mProfile.getProfileNickname().substring(0, nickname_limit));
sendMessage("NICK " + mProfile.getProfileNickname());
// 4.1.3 User message
sendMessage("USER " + mProfile.getProfileIdent() + " 0 * :" + mProfile.getProfileRealname());
//3: Communicating with the server
do
{
processMessage(mIrcInput.readLine());
}
while(!mThreadDone);
}
catch(UnknownHostException unknownHost)
{
Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": You are trying to connect to an unknown host!");
}
catch(IOException ioException)
{
//Log.e(getClass().getSimpleName(), connName + " Error1" + ioException.getMessage(), ioException);
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Forcing shutdown? " + ioException.getMessage());
}
finally
{
if(mIrcOutput != null)
sendMessage("QUIT :Powered by fIRC v3.0, the android IRC client.");
//4: Closing connection
try
{
if(mIrcInput != null)
mIrcInput.close();
if(mIrcOutput != null)
mIrcOutput.close();
if(mIrcSocket != null)
mIrcSocket.close();
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Closed socket");
}
catch(IOException ioException)
{
ioException.printStackTrace();
Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": ioException while closing connection", ioException);
}
}
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Finished");
updateConnectionStatus(CONNECTION_OFFLINE);
mIrcThread = null;
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Process
///////////////////////////////////////////////////////////////////////////////////////////////
// http://www.ietf.org/rfc/rfc1459.txt
private void processMessage(String msg)
{
Log.d(getClass().getSimpleName(), "Incoming message: " + msg);
// If something went wrong, kill thread
if(msg == null)
{
mThreadDone = true;
return;
}
// 4.6.2 Ping message
if(msg.substring(0,4).equalsIgnoreCase("PING"))
{
addMessage("server", "< " + msg, 2);
int values = msg.indexOf(":");
// 4.6.3 Pong message
sendMessage("PONG " + msg.substring(values));
return;
}
// Figure out what's happening
String cmds_text = msg;
String[] cmds_item = null;
cmds_item = cmds_text.split(" ");
if(cmds_item[1].equalsIgnoreCase("001"))
{
sendMessage("USERHOST " + mProfile.getProfileNickname());
}
//else if(cmds_item[1].equalsIgnoreCase("422"))
else if(cmds_item[1].equalsIgnoreCase("376"))
{
updateConnectionStatus(CONNECTION_ONLINE);
String[] chatrooms = null;
chatrooms = mProfile.getProfileChatrooms().split("\n");
for(String room : chatrooms)
{
sendMessage("JOIN " + room);
//addChannel(room);
}
}
else if(cmds_item[1].equalsIgnoreCase("JOIN"))
{
// TODO Handle join by others
// Handle own channel join
String[] values_item = cmds_item[0].substring(1).split("!");
if(values_item[0].equalsIgnoreCase(mProfile.getProfileNickname()))
{
int values = cmds_item[2].indexOf(":") + 1;
addMessage(cmds_item[2].substring(values), "Now talking in " + cmds_item[2].substring(values), 2);
}
}
if(cmds_item[1].equalsIgnoreCase("PRIVMSG"))
{
int values = msg.indexOf(":",1) + 1;
String nickname = cmds_item[0].substring(1, cmds_item[0].indexOf("!"));
Date date = new Date();
String line = "[" + mDateFormat.format(date) + "] <" + nickname + "> " + msg.substring(values);
addMessage(cmds_item[2], line, 1);
}
else
addMessage("server", "< " + msg, 2);
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Public Methods
///////////////////////////////////////////////////////////////////////////////////////////////
public void sendMessage(String msg)
{
try
{
mIrcOutput.write(msg);
mIrcOutput.newLine();
mIrcOutput.flush();
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": RAW sendMessage: " + msg);
// LOG OUTPUT
addMessage("server", "> " + msg, 2);
// Incase of privmsg
String[] cmds_item = msg.split(" ");
if(cmds_item[0].equalsIgnoreCase("PRIVMSG"))
{
Date date = new Date();
//String line = "[" + mDateFormat.format(date) + "] <" + mProfile.getProfile_nickname() + "> " + cmds_item[2].substring(1);
//String[] chatmsg = msg.split(":");
String chatmsg = msg.substring(msg.indexOf(":")+1);
String line = "[" + mDateFormat.format(date) + "] <" + mProfile.getProfileNickname() + "> " + chatmsg;
addMessage(cmds_item[1], line, 0);
}
}
catch(IOException ioException)
{
ioException.printStackTrace();
}
}
public int getCurrentScreen() {
return mCurrentScreen;
}
public void setCurrentScreen(int currentScreen) {
mCurrentScreen = currentScreen;
}
public String getConnectionName()
{
return mProfile.getProfile_name();
}
public int getConnectionID()
{
return mProfile.getProfileId();
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Thread
///////////////////////////////////////////////////////////////////////////////////////////////
public void startThread() {
if ( mIrcThread == null )
{
mIrcThread = new Thread(this);
mThreadDone = false;
mIrcThread.start();
}
}
public void stopThread() {
mThreadDone = true;
try
{
if(mIrcSocket != null)
mIrcSocket.close();
Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Forcing shutdown (closing socket)");
}
catch(IOException ioException)
{
ioException.printStackTrace();
Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": Error while forcing shutdown", ioException);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Chat History
///////////////////////////////////////////////////////////////////////////////////////////////
public synchronized void initializePanels()
{
if(mParent.getHandler() != null)
{
if(mParent.getActiveProfile() == mProfile.getProfileId())
{
// Dirty replay messages
for (Entry<String, ArrayList<ChatMessage>> entry : getChatMessagesList().entrySet())
{
for(ChatMessage chatmsg : entry.getValue())
{
mParent.getHandler().obtainMessage(ChatService.MSG_UI_INIT, 0, 0, chatmsg).sendToTarget();
}
}
// Finished update panels
mParent.getHandler().obtainMessage(ChatService.MSG_UI_INIT_DONE).sendToTarget();
}
}
}
private void addChannel(String channelName) {
getChatMessagesList().put(channelName, new ArrayList<ChatMessage>());
}
private void addMessage(String channel, String message, int type) {
ChatMessage msg = new ChatMessage();
msg.setChatMessage(message);
msg.setChannel(channel);
msg.setType(type);
if(getChatMessagesList().containsKey(channel))
{
if(getChatMessagesList().get(channel).size() >= MAX_CHAT_HISTORY)
getChatMessagesList().get(channel).remove(0);
getChatMessagesList().get(channel).add(msg);
}
else
{
getChatMessagesList().put(channel, new ArrayList<ChatMessage>());
getChatMessagesList().get(channel).add(msg);
}
if(mParent.getHandler() != null)
{
if(mParent.getActiveProfile() == mProfile.getProfileId())
mParent.getHandler().obtainMessage(ChatService.MSG_UI_UPDATE,0,0,msg).sendToTarget();
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.service;
import java.util.ArrayList;
import java.util.Hashtable;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.falcon4ever.fIRC3.utils.DBProfileManager;
import com.falcon4ever.fIRC3.utils.ProfileState;
public class ChatService extends Service {
public static final int MSG_UI_INIT = 1;
public static final int MSG_UI_INIT_DONE = 2;
public static final int MSG_UI_UPDATE = 3;
public static final int MSG_UI_SERVERLIST_UPDATE = 4;
private Handler mHandler;
private int mActiveProfile = -1;
private final IBinder mBinder = new LocalBinder();
// List of Connections
private Hashtable<Integer, IRCConnection> mConnectionList = new Hashtable<Integer, IRCConnection>();
@Override
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(),"Start fIRC3 background service");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(),"Shutting down fIRC3 background service");
disconnectAll();
}
public class LocalBinder extends Binder {
public ChatService getService() {
// Return this instance of LocalService so clients can call public methods
return ChatService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void connect(int profile_id)
{
DBProfileManager db = new DBProfileManager(this);
ArrayList<Object> curProfile = db.getRowAsArray(profile_id);
db.close();
ProfileState ps = new ProfileState();
ps.setProfileId(Integer.parseInt(curProfile.get(0).toString()));
ps.setProfileName(curProfile.get(1).toString());
ps.setProfileNickname(curProfile.get(2).toString());
ps.setProfileAltnick(curProfile.get(3).toString());
ps.setProfileServer(curProfile.get(4).toString());
ps.setProfilePort(Integer.parseInt(curProfile.get(5).toString()));
ps.setProfileChatrooms(curProfile.get(6).toString());
ps.setProfileIdent(curProfile.get(7).toString());
ps.setProfileRealname(curProfile.get(8).toString());
ps.setProfileEncoding(Integer.parseInt(curProfile.get(9).toString()));
ps.setProfileOnconnect(curProfile.get(10).toString());
//ps.setConnected(false);
String[] encoding_array = getResources().getStringArray(com.falcon4ever.fIRC3.R.array.encoding_array);
String profile_encoding = encoding_array[Integer.parseInt(curProfile.get(9).toString())];
addConnection(ps, profile_encoding);
Log.d(getClass().getSimpleName(), "Launching single profile: " + mConnectionList.get(profile_id).getConnectionName());
mConnectionList.get(profile_id).startThread();
}
public void disconnect(int profile_id)
{
if(mConnectionList.containsKey(profile_id))
{
mConnectionList.get(profile_id).stopThread();
mConnectionList.remove(profile_id);
}
}
private void addConnection(ProfileState ps, String encoding)
{
if(mConnectionList.containsKey(ps.getProfileId()))
{
mConnectionList.get(ps.getProfileId()).stopThread();
mConnectionList.remove(ps.getProfileId());
}
IRCConnection myConn = new IRCConnection(ps, encoding, this);
mConnectionList.put(ps.getProfileId(), myConn);
}
public void connectAll()
{
// Query all connections from db
DBProfileManager db = new DBProfileManager(this);
ArrayList<ArrayList<Object>> profiles = db.getAllRowsAsArrays();
db.close();
// Fill profiles
for(int i = 0; i < profiles.size(); i++)
{
ArrayList<Object> values = profiles.get(i);
ProfileState ps = new ProfileState();
ps.setProfileId(Integer.parseInt(values.get(0).toString()));
ps.setProfileName(values.get(1).toString());
ps.setProfileNickname(values.get(2).toString());
ps.setProfileAltnick(values.get(3).toString());
ps.setProfileServer(values.get(4).toString());
ps.setProfilePort(Integer.parseInt(values.get(5).toString()));
ps.setProfileChatrooms(values.get(6).toString());
ps.setProfileIdent(values.get(7).toString());
ps.setProfileRealname(values.get(8).toString());
ps.setProfileEncoding(Integer.parseInt(values.get(9).toString()));
ps.setProfileOnconnect(values.get(10).toString());
//ps.setConnected(false);
String[] encoding_array = getResources().getStringArray(com.falcon4ever.fIRC3.R.array.encoding_array);
String profile_encoding = encoding_array[Integer.parseInt(values.get(9).toString())];
addConnection(ps, profile_encoding);
}
for(IRCConnection conn : mConnectionList.values())
{
Log.d(getClass().getSimpleName(), "Launching profile: " + conn.getConnectionName());
conn.startThread();
}
}
public void disconnectAll()
{
for(IRCConnection conn : mConnectionList.values())
conn.stopThread();
mConnectionList.clear();
// TODO: Update status?
}
public int getConnectionStatus(int profileId)
{
if(mConnectionList.containsKey(profileId))
return mConnectionList.get(profileId).getConnectionStatus();
else
return IRCConnection.CONNECTION_OFFLINE;
}
public IRCConnection getIrcConn(int profileId)
{
if(mConnectionList.containsKey(profileId))
return mConnectionList.get(profileId);
else
return null;
}
public synchronized Handler getHandler() {
return mHandler;
}
public synchronized void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
public synchronized void setActiveProfile(int activeProfile) {
mActiveProfile = activeProfile;
}
public synchronized int getActiveProfile() {
return mActiveProfile;
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.falcon4ever.fIRC3.service.ChatService;
public class HomeActivity extends Activity {
private Shortcut mIcons[] = {
new Shortcut(R.drawable.ic_menu_start_conversation, "Chat", "com.falcon4ever.fIRC3.ServerlistActivity"),
new Shortcut(R.drawable.ic_menu_refresh, "File transfers", "com.falcon4ever.fIRC3.PlaceholderActivity"),
new Shortcut(R.drawable.ic_menu_preferences, "Settings", "com.falcon4ever.fIRC3.PlaceholderActivity"),
new Shortcut(R.drawable.ic_menu_help, "Manual", "homepage"),
new Shortcut(R.drawable.ic_menu_info_details, "About", "about"),
new Shortcut(R.drawable.ic_lock_power_off, "Logout", "logout"),
};
private LinearLayout mIconRows[] = new LinearLayout[4];
private String mVersion;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
try {
PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0);
mVersion = manager.versionName;
setTitle("fIRC - The Android IRC Client (v" + mVersion + ")");
}
catch (NameNotFoundException e) {
mVersion = "";
}
// Initialize icon rows
for(int i = 0; i < mIconRows.length; i++)
{
mIconRows[i] = new LinearLayout(this);
mIconRows[i].setOrientation(LinearLayout.HORIZONTAL);
}
// Place icons
switch(getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_UNDEFINED:
case Configuration.ORIENTATION_SQUARE:
case Configuration.ORIENTATION_PORTRAIT:
{
for(int i = 0; i < mIconRows.length; i++)
mIconRows[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
addIcons(Configuration.ORIENTATION_PORTRAIT, 3);
}
break;
case Configuration.ORIENTATION_LANDSCAPE:
{
mIconRows[1].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
mIconRows[2].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
addIcons(Configuration.ORIENTATION_LANDSCAPE, 5);
}
break;
default:
}
// Add views
final LinearLayout homeIcons = (LinearLayout)findViewById(R.id.home_screen);
for(int i = 0; i < mIconRows.length; i++)
homeIcons.addView(mIconRows[i]);
// Start background service
startService(new Intent(this, ChatService.class));
// One time disclaimer
SharedPreferences settings = getSharedPreferences("fIRC_settings", 0);
boolean disclaimer = settings.getBoolean("firc_disclaimer", false);
if(!disclaimer) {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.alert_dialog_title);
builder.setMessage(R.string.alert_dialog_msg);
builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences settings = getSharedPreferences("fIRC_settings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firc_disclaimer", true);
editor.commit();
}
});
builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
stopService(new Intent(HomeActivity.this, ChatService.class));
finish();
}
});
builder.show();
}
}
private void addIcons(int orientation, int maxicons)
{
int row = 0, counter = 0;
if(orientation == Configuration.ORIENTATION_LANDSCAPE)
row = 1;
for(int i = 0; i < mIcons.length; i++)
{
final int j = i;
++counter;
LinearLayout iconWrap = new LinearLayout(this);
iconWrap.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
iconWrap.setOrientation(LinearLayout.VERTICAL);
LinearLayout iconImageWrap = new LinearLayout(this);
iconImageWrap.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
iconImageWrap.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
ImageView iconImage = new ImageView(this);
iconImage.setImageResource(mIcons[i].getResId());
iconImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
TextView iconText = new TextView(this);
iconText.setText(mIcons[i].getLabel());
iconText.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
iconText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, (float) 1.35));
iconImageWrap.addView(iconImage);
iconWrap.addView(iconImageWrap);
iconWrap.addView(iconText);
iconWrap.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
// Set action
if(mIcons[j].getClassname().equals("logout"))
{
stopService(new Intent(HomeActivity.this, ChatService.class));
finish();
}
else if(mIcons[j].getClassname().equals("homepage"))
{
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.multigesture.net/projects/firc/"));
startActivity(browserIntent);
}
else if(mIcons[j].getClassname().equals("about"))
{
AlertDialog alertDialog = new AlertDialog.Builder(HomeActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage(
"Author: Laurence Muller\n" +
"E-mail: info@falcon4ever.com\n" +
"Website: multigesture.net/firc\n\n" +
"fIRC version: v" + mVersion + "\n" +
"License type: Freeware\n\n" +
"Special thanks to (*donated):\n\nThisRob*, SanMehat, languish, Disconnect, hmepass, JesusFreke, kirberich, rashed2020, kash and everyone else I forgot.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
else
{
Intent intent = new Intent();
intent.setClassName(HomeActivity.this, mIcons[j].getClassname());
startActivity(intent);
}
}
});
mIconRows[row].addView(iconWrap);
if(counter == maxicons)
{
++row;
counter = 0;
}
}
}
private class Shortcut
{
public int mResId;
public String mLabel;
public String mClassname;
Shortcut(int resId, String label, String classname)
{
mResId = resId;
mLabel = label;
mClassname = classname;
}
public int getResId() {
return mResId;
}
public String getLabel() {
return mLabel;
}
public String getClassname() {
return mClassname;
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import org.jared.commons.ui.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.falcon4ever.fIRC3.utils.DBProfileManager;
public class ProfileActivity extends Activity {
private final String mDefaultNetwork = "EFnet";
private final Random mGenerator = new Random();
private Hashtable<String, Network> mNetworksList;
/*
* Silly hack since setOnItemSelectedListener(new ServerOnItemSelectedListener());
* is calling onItemSelected on initialization.
* http://stackoverflow.com/questions/5624825/spinner-onitemselected-executes-when-it-is-not-suppose-to/5918177#5918177
*/
private int mCount=0;
private int mInitializedCount=0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide keyboard on Activity launch
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.profile);
// Load hardcoded serverlist (Slow?)
loadServerlist();
// Get extras
final Bundle extras = getIntent().getExtras();
String profileType = extras.getString("profile_type");
if(profileType.equals("new_profile"))
{
newProfile();
}
else if(profileType.equals("edit_profile"))
{
setTitle(R.string.profile_title_edit);
editProfile(extras.getInt("profile_id"));
}
else
{
Log.d(getClass().getSimpleName(), "no extras");
finish();
}
}
private void setupSpinners()
{
// Enumerate Networks (Groups)
// Get list of networks, store it and sort the List
Enumeration<String> e = mNetworksList.keys();
List<String> ircNetworksNames = new ArrayList<String>();
while(e.hasMoreElements())
ircNetworksNames.add(mNetworksList.get(e.nextElement()).getName());
Collections.sort(ircNetworksNames);
// Prepare to copy list to ircnetworks so it can be attached to the Adapter
int defaultPos = 0;
List<CharSequence> ircNetworks = new ArrayList<CharSequence>();
for (int i=0; i< ircNetworksNames.size(); i++)
{
// Set default Network
if(ircNetworksNames.get(i).equals(mDefaultNetwork))
defaultPos = ircNetworks.size();
ircNetworks.add((CharSequence)ircNetworksNames.get(i));
}
final Spinner profileNetworkSpinner = (Spinner) findViewById(R.id.profile_network_spinner);
ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, ircNetworks);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
profileNetworkSpinner.setAdapter(adapter1);
profileNetworkSpinner.setOnItemSelectedListener(new NetworkOnItemSelectedListener());
profileNetworkSpinner.setSelection(defaultPos);
// Enumerate Servers
final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner);
ArrayAdapter<CharSequence> adapter2 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
profileServerSpinner.setAdapter(adapter2);
profileServerSpinner.setOnItemSelectedListener(new ServerOnItemSelectedListener());
setServerValues();
// Enumerate encodings
final Spinner profileEncodingSpinner = (Spinner) findViewById(R.id.profile_encoding_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.encoding_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
profileEncodingSpinner.setAdapter(adapter);
}
private void newProfile()
{
final Button profileSave = (Button)findViewById(R.id.profile_save);
profileSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Prepare values
String r01 = ((EditText)findViewById(R.id.profile_name)).getText().toString();
String r02 = ((EditText)findViewById(R.id.profile_nickname)).getText().toString();
String r03 = ((EditText)findViewById(R.id.profile_altnick)).getText().toString();
String r04 = ((EditText)findViewById(R.id.profile_server_address)).getText().toString();
String port= ((EditText)findViewById(R.id.profile_server_port)).getText().toString();
int r05 = Integer.parseInt(port);
String r06 = ((EditText)findViewById(R.id.profile_chatrooms)).getText().toString();
String r07 = ((EditText)findViewById(R.id.profile_ident)).getText().toString();
String r08 = ((EditText)findViewById(R.id.profile_realname)).getText().toString();
final Spinner profile_encoding_spinner = (Spinner) findViewById(R.id.profile_encoding_spinner);
int r09 = profile_encoding_spinner.getSelectedItemPosition();
String r10 = ((EditText)findViewById(R.id.profile_onconnect)).getText().toString();
// Connect to db and submit
DBProfileManager db = new DBProfileManager(ProfileActivity.this);
db.addRow(r01, r02, r03, r04, r05, r06, r07, r08, r09, r10);
db.close();
finish();
}
});
final Button profileCancel = (Button)findViewById(R.id.profile_cancel);
profileCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Ignore changes
finish();
}
});
setupSpinners();
// Set defaults
final EditText profileNickname = (EditText)findViewById(R.id.profile_nickname);
profileNickname.setText("Android" + mGenerator.nextInt(100));
final EditText profileAltnick = (EditText)findViewById(R.id.profile_altnick);
profileAltnick.setText("Android" + mGenerator.nextInt(100));
final EditText profileName = (EditText)findViewById(R.id.profile_name);
profileName.setText("New profile");
}
private void editProfile(final int profile_id)
{
setupSpinners();
// Set values
DBProfileManager db = new DBProfileManager(ProfileActivity.this);
ArrayList<Object> row = db.getRowAsArray(profile_id);
db.close();
final EditText profileName = (EditText)findViewById(R.id.profile_name);
profileName.setText((String)row.get(1));
final EditText profileNickname = (EditText)findViewById(R.id.profile_nickname);
profileNickname.setText((String)row.get(2));
final EditText profileAltnick = (EditText)findViewById(R.id.profile_altnick);
profileAltnick.setText((String)row.get(3));
final EditText profileServerAddress = (EditText)findViewById(R.id.profile_server_address);
profileServerAddress.setText((String)row.get(4));
final EditText profileServerPort = (EditText)findViewById(R.id.profile_server_port);
profileServerPort.setText((String)row.get(5).toString());
final EditText profileChatrooms = (EditText)findViewById(R.id.profile_chatrooms);
profileChatrooms.setText((String)row.get(6));
final EditText profileIdent = (EditText)findViewById(R.id.profile_ident);
profileIdent.setText((String)row.get(7));
final EditText profileRealname = (EditText)findViewById(R.id.profile_realname);
profileRealname.setText((String)row.get(8));
final Spinner profileEncodingSpinner = (Spinner) findViewById(R.id.profile_encoding_spinner);
profileEncodingSpinner.setSelection(Integer.parseInt(row.get(9).toString()));
final EditText profileOnconnect = (EditText)findViewById(R.id.profile_onconnect);
profileOnconnect.setText((String)row.get(10));
final Button profileSave = (Button)findViewById(R.id.profile_save);
profileSave.setText("Update profile");
profileSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Prepare values
String r01 = ((EditText)findViewById(R.id.profile_name)).getText().toString();
String r02 = ((EditText)findViewById(R.id.profile_nickname)).getText().toString();
String r03 = ((EditText)findViewById(R.id.profile_altnick)).getText().toString();
String r04 = ((EditText)findViewById(R.id.profile_server_address)).getText().toString();
String port= ((EditText)findViewById(R.id.profile_server_port)).getText().toString();
int r05 = Integer.parseInt(port);
String r06 = ((EditText)findViewById(R.id.profile_chatrooms)).getText().toString();
String r07 = ((EditText)findViewById(R.id.profile_ident)).getText().toString();
String r08 = ((EditText)findViewById(R.id.profile_realname)).getText().toString();
final Spinner profile_encoding_spinner = (Spinner) findViewById(R.id.profile_encoding_spinner);
int r09 = profile_encoding_spinner.getSelectedItemPosition();
String r10 = ((EditText)findViewById(R.id.profile_onconnect)).getText().toString();
// Connect to db and submit
DBProfileManager db = new DBProfileManager(ProfileActivity.this);
db.updateRow(profile_id, r01, r02, r03, r04, r05, r06, r07, r08, r09, r10);
db.close();
finish();
}
});
final Button profileCancel = (Button)findViewById(R.id.profile_cancel);
profileCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Ignore changes
finish();
}
});
// hack to ignore 2 OnItemSelectedListener items
mCount = 2;
}
public void setWizardValues()
{
Log.d(getClass().getSimpleName(),"setWizardValues()");
final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner);
int pos = profileServerSpinner.getSelectedItemPosition();
if(pos == AdapterView.INVALID_POSITION)
return;
String[] values = profileServerSpinner.getItemAtPosition(pos).toString().split(":");
if(values.length == 2)
{
final EditText profileServerAddress = (EditText)findViewById(R.id.profile_server_address);
final EditText profileServerPort = (EditText)findViewById(R.id.profile_server_port);
profileServerAddress.setText(values[0]);
profileServerPort.setText(values[1]);
}
}
public void setServerValues()
{
Log.d(getClass().getSimpleName(),"setServerValues()");
final Spinner profileNetworkSpinner = (Spinner) findViewById(R.id.profile_network_spinner);
String currentNetwork = profileNetworkSpinner.getItemAtPosition(profileNetworkSpinner.getSelectedItemPosition()).toString();
Network n = (Network)mNetworksList.get(currentNetwork);
final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner);
@SuppressWarnings("unchecked")
ArrayAdapter<CharSequence> adapter = (ArrayAdapter<CharSequence>) profileServerSpinner.getAdapter();
adapter.clear(); // empty adapter
// Iterate over all servers from current network
for(int i = 0; i < n.getServers().size(); i++)
{
// Iterate over all available ports
for (int j = 0; j < n.getServers().get(i).getPorts().size(); j++)
adapter.add(n.getServers().get(i).getAddress() + ":" + Integer.toString(n.getServers().get(i).getPorts().get(j)));
}
// Choose a random server from the list after selecting a network to balance load
profileServerSpinner.setSelection(mGenerator.nextInt(profileServerSpinner.getCount()));
// Apply values
setWizardValues();
}
public class NetworkOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (mInitializedCount < mCount)
mInitializedCount++;
else
setServerValues();
}
public void onNothingSelected(AdapterView<?> parent) { }
}
public class ServerOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (mInitializedCount < mCount)
mInitializedCount++;
else
setWizardValues();
}
public void onNothingSelected(AdapterView<?> parent) { }
}
private void loadServerlist()
{
ServerList serverlist = new ServerList();
mNetworksList = serverlist.getNetworksList();
}
private class ServerList {
Hashtable<String, Network> networksList = new Hashtable<String, Network>();
public ServerList() {
importServerlist();
}
private void importServerlist()
{
// Original source: http://www.mirc.com/servers.html
InputStream is = getResources().openRawResource(R.raw.servers);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
int label = 0;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null)
{
// Read Label to set label state
if(readLine.equals("[timestamp]")) // Reading timestamp
{
label = 0;
continue;
}
else if(readLine.equals("[networks]")) // Reading networks
{
label = 1;
continue;
}
else if(readLine.equals("[servers]")) // Reading server addresses
{
label = 2;
// Used for networks without group name
networksList.put("Random", new Network("Random"));
continue;
}
else if(readLine.equals(""))
{
continue;
}
// Values
if(label == 1)
{
String networks[] = readLine.split("=");
// Add Groups
networksList.put(networks[1], new Network(networks[1]));
}
else if(label == 2)
{
List<Integer> portsList = new ArrayList<Integer>();
String servers[] = readLine.split("=");
// Get name, group, address and portlist
String name = servers[1].split("SERVER:")[0];
String group = servers[1].split("GROUP:")[1];
String address = servers[1].split(":")[1];
String ports = servers[1].split(":")[2].split("GROUP")[0];
// Split up port array
String portArray[] = ports.split(",");
for(int i=0; i < portArray.length; i++)
{
// Check if entry is a range
String portNumbers[] = portArray[i].split("-");
if(portNumbers.length == 2)
{
// Add all ports one by one
for(int p = Integer.parseInt(portNumbers[0]); p <= Integer.parseInt(portNumbers[1]); p++)
portsList.add(p);
}
else
{
// Add single port, no clue why some have a + sign
if(portArray[i].charAt(0) == "+".charAt(0))
portsList.add(Integer.parseInt(portArray[i].substring(1)));
else
portsList.add(Integer.parseInt(portArray[i]));
}
}
// All data is know, create a server object
Server sv = new Server(name);
sv.setAddress(address);
sv.setPorts(portsList);
// Add server object to the network list (check if the group exists)
if(networksList.containsKey(group))
networksList.get(group).getServers().add(sv);
else
{
//Log.d("group", "Group does not exist in list: " + group);
networksList.get("Random").getServers().add(sv);
}
}
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Hashtable<String, Network> getNetworksList() {
return networksList;
}
}
public class Network
{
private String mName;
private List<Server> mServers = new ArrayList<Server>();
public Network(String name) {
mName = name;
}
public String getName() {
return mName;
}
public List<Server> getServers() {
return mServers;
}
}
public class Server
{
private String mName;
private String mAddress;
private List<Integer> mPorts = new ArrayList<Integer>();
public Server(String name) {
mName = name;
}
public String getName() {
return mName;
}
public String getAddress() {
return mAddress;
}
public void setAddress(String address) {
mAddress = address;
}
public List<Integer> getPorts() {
return mPorts;
}
public void setPorts(List<Integer> ports) {
mPorts = ports;
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import org.jared.commons.ui.R;
import org.jared.commons.ui.WorkspaceView;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.falcon4ever.fIRC3.service.ChatService;
import com.falcon4ever.fIRC3.service.ChatService.LocalBinder;
import com.falcon4ever.fIRC3.utils.ChatMessage;
public class ChatActivity extends Activity {
private HashMap<String, ArrayList<ChatMessage>> mChatMessagesList = new HashMap<String, ArrayList<ChatMessage>>();
private HashMap<String, ChatAdapter> mChatAdapterList = new HashMap<String, ChatAdapter>();
private HashMap<Integer, String> mScreenLUT = new HashMap<Integer, String>();
private ChatService mService;
private boolean mBound = false;
private int mProfileId;
private EditText mChatInput;
private WorkspaceView mWorkView = null;
private LayoutInflater mInflater;
private Handler IncomingHandler = new Handler()
{
public void handleMessage(Message msg)
{
//Log.d("IncomingHandler", "UI msg: " + msg.what);
switch (msg.what)
{
// Replay messages
case ChatService.MSG_UI_INIT:
{
ChatMessage chatmsg = (ChatMessage) msg.obj;
if(mChatMessagesList.containsKey(chatmsg.getChannel()))
{
mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg);
}
else
{
// Add channel
mChatMessagesList.put(chatmsg.getChannel(), new ArrayList<ChatMessage>());
mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg);
}
}
break;
// Initialize panels
case ChatService.MSG_UI_INIT_DONE:
{
addPanels();
}
break;
// Update UI
case ChatService.MSG_UI_UPDATE:
{
ChatMessage chatmsg = (ChatMessage)msg.obj;
if(mChatMessagesList.containsKey(chatmsg.getChannel()))
{
mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg);
}
else
{
mChatMessagesList.put(chatmsg.getChannel(), new ArrayList<ChatMessage>());
mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg);
addPanels();
return;
}
// update adapter
mChatAdapterList.get(chatmsg.getChannel()).notifyDataSetChanged();
}
break;
default:
Log.e(getClass().getSimpleName(), "Unhandled message IncomingHandler " + msg.what);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View mainLayout = mInflater.inflate(R.layout.chat, null, false);
setContentView(mainLayout);
mChatInput = (EditText)findViewById(R.id.chat_input);
final Button submitButton = (Button)findViewById(R.id.chat_submit);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
submitMessage();
}
});
final Bundle extras = getIntent().getExtras();
mProfileId = extras.getInt("profile_id");
Log.d(getClass().getSimpleName(),"Chat: profile_id: " + Integer.toString(mProfileId));
// Hide keyboard on Activity launch
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// Bind to LocalService
Intent intent = new Intent(this, ChatService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mChatMessagesList.put("server", new ArrayList<ChatMessage>());
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
@Override
protected void onPause() {
super.onPause();
if (mBound) {
if(mWorkView != null)
mService.getIrcConn(mProfileId).setCurrentScreen(mWorkView.getCurrentScreen());
mService.setHandler(null);
mService.setActiveProfile(-1);
}
}
private void submitMessage()
{
String msg = mChatInput.getText().toString();
if(msg.length() > 0)
{
String newmessage = "";
if(mScreenLUT.get(mWorkView.getCurrentScreen()).equalsIgnoreCase("server"))
{
// Send RAW message to server
newmessage = msg;
}
else
{
// PRIVMSG dest :msg
newmessage = "PRIVMSG " + mScreenLUT.get(mWorkView.getCurrentScreen()) + " :" + msg;
}
if (mBound)
{
if(mService.getIrcConn(mProfileId) != null)
mService.getIrcConn(mProfileId).sendMessage(newmessage);
}
}
mChatInput.setText("");
}
private void addPanels()
{
Log.d(getClass().getSimpleName(), "addPanels()");
mChatAdapterList.clear();
FrameLayout chatFrame = (FrameLayout)findViewById(R.id.chat_frame);
chatFrame.removeAllViews();
mWorkView = null;
// Create new WorkspaceView
mWorkView = new WorkspaceView(this, null);
mWorkView.setTouchSlop(32);
boolean hasChannels = false;
int i = 0;
if(mBound)
{
for (Entry<String, ArrayList<ChatMessage>> entry: mChatMessagesList.entrySet()) {
hasChannels = true;
View view = mInflater.inflate(R.layout.chat_view, null, false);
mWorkView.addView(view);
TextView chatTitlebar = (TextView)view.findViewById(R.id.chat_titlebar);
chatTitlebar.setText(entry.getKey());
ListView lv = (ListView)view.findViewById(R.id.chat_list);
lv.setFastScrollEnabled(true);
ChatAdapter ca = new ChatAdapter(this, R.layout.chat_row, (ArrayList<ChatMessage>)entry.getValue());
mChatAdapterList.put(entry.getKey(), ca);
mScreenLUT.put(i++, entry.getKey());
lv.setAdapter(ca);
}
if(hasChannels)
{
chatFrame.addView(mWorkView);
if(mWorkView != null)
mWorkView.setCurrentScreen(mService.getIrcConn(mProfileId).getCurrentScreen());
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// ServiceConnection
///////////////////////////////////////////////////////////////////////////////////////////////
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
Log.d("ChatActivity", "onServiceConnected");
mService.setHandler(IncomingHandler);
mService.setActiveProfile(mProfileId);
mService.getIrcConn(mProfileId).initializePanels();
}
public void onServiceDisconnected(ComponentName className) {
mBound = false;
}
};
///////////////////////////////////////////////////////////////////////////////////////////////
// ChatAdapter
///////////////////////////////////////////////////////////////////////////////////////////////
private class ChatAdapter extends ArrayAdapter<ChatMessage> {
public static final int USER_TEXT_COLOR = 0xff000000;
public static final int USER_BACKGROUND_COLOR = 0xfff8d8f8;
public static final int CHANNEL_TEXT_COLOR = 0xff000000;
public static final int CHANNEL_BACKGROUND_COLOR = 0xffd8e8f8;
public static final int SERVER_TEXT_COLOR = 0xff000000;
public static final int SERVER_BACKGROUND_COLOR = 0xffe0e0e0;
private ArrayList<ChatMessage> mItems;
private LayoutInflater mInflater;
public ChatAdapter(Context context, int textViewResourceId, ArrayList<ChatMessage> items) {
super(context, textViewResourceId, items);
mItems = items;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.chat_row, parent, false);
}
ChatMessage o = mItems.get(position);
if (o != null) {
TextView tt = (TextView) convertView.findViewById(R.id.label);
if (tt != null) {
if(o.getType() == 0)
{
tt.setTextColor(USER_TEXT_COLOR);
tt.setBackgroundColor(USER_BACKGROUND_COLOR);
}
else if(o.getType() == 1)
{
tt.setTextColor(CHANNEL_TEXT_COLOR);
tt.setBackgroundColor(CHANNEL_BACKGROUND_COLOR);
}
else
{
tt.setTextColor(SERVER_TEXT_COLOR);
tt.setBackgroundColor(SERVER_BACKGROUND_COLOR);
}
tt.setText(o.getChatMessage());
}
}
return convertView;
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.utils;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
// Based on: http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/
public class DBProfileManager {
private Context context;
private SQLiteDatabase db;
private final String DB_NAME = "firc_db";
private final int DB_VERSION = 1;
private final String TABLE_NAME = "db_profiles";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_01 = "profile_name"; // TEXT
private final String TABLE_ROW_02 = "profile_nickname"; // TEXT
private final String TABLE_ROW_03 = "profile_altnick"; // TEXT
private final String TABLE_ROW_04 = "profile_server_address";//TEXT
private final String TABLE_ROW_05 = "profile_port"; // INTEGER
private final String TABLE_ROW_06 = "profile_chatrooms"; // TEXT
private final String TABLE_ROW_07 = "profile_ident"; // TEXT
private final String TABLE_ROW_08 = "profile_realname"; // TEXT
private final String TABLE_ROW_09 = "profile_encoding"; // INTEGER
private final String TABLE_ROW_10 = "profile_onconnect"; // TEXT
private CustomSQLiteOpenHelper helper;
public DBProfileManager(Context context)
{
this.setContext(context);
// create or open the database
helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
public void close()
{
if (helper != null)
helper.close();
if (db != null)
db.close();
}
public void addRow(String r01, String r02, String r03, String r04, int r05, String r06, String r07, String r08, int r09, String r10)
{
ContentValues values = new ContentValues();
values.put(TABLE_ROW_01, r01);
values.put(TABLE_ROW_02, r02);
values.put(TABLE_ROW_03, r03);
values.put(TABLE_ROW_04, r04);
values.put(TABLE_ROW_05, r05);
values.put(TABLE_ROW_06, r06);
values.put(TABLE_ROW_07, r07);
values.put(TABLE_ROW_08, r08);
values.put(TABLE_ROW_09, r09);
values.put(TABLE_ROW_10, r10);
// ask the database object to insert the new data
try
{
long rowID = db.insert(TABLE_NAME, null, values);
Log.d(getClass().getSimpleName(), "SQLiteDatabase addRow - Row ID: " + Integer.toString((int)rowID));
}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID)
{
Log.d(getClass().getSimpleName(), "SQLiteDatabase delete - Row ID: " + Integer.toString((int)rowID));
// ask the database manager to delete the row of given id
try
{
db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String r01, String r02, String r03, String r04, int r05, String r06, String r07, String r08, int r09, String r10)
{
Log.d(getClass().getSimpleName(), "SQLiteDatabase update - Row ID: " + Integer.toString((int)rowID));
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(TABLE_ROW_01, r01);
values.put(TABLE_ROW_02, r02);
values.put(TABLE_ROW_03, r03);
values.put(TABLE_ROW_04, r04);
values.put(TABLE_ROW_05, r05);
values.put(TABLE_ROW_06, r06);
values.put(TABLE_ROW_07, r07);
values.put(TABLE_ROW_08, r08);
values.put(TABLE_ROW_09, r09);
values.put(TABLE_ROW_10, r10);
// ask the database object to update the database row of given rowID
try
{
db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);
}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public ArrayList<Object> getRowAsArray(long rowID)
{
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try
{
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_01, TABLE_ROW_02, TABLE_ROW_03, TABLE_ROW_04, TABLE_ROW_05, TABLE_ROW_06, TABLE_ROW_07, TABLE_ROW_08, TABLE_ROW_09, TABLE_ROW_10 },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
// move the pointer to position zero in the cursor.
cursor.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!cursor.isAfterLast())
{
do
{
rowArray.add(cursor.getLong(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
rowArray.add(cursor.getLong(5));
rowArray.add(cursor.getString(6));
rowArray.add(cursor.getString(7));
rowArray.add(cursor.getString(8));
rowArray.add(cursor.getLong(9));
rowArray.add(cursor.getString(10));
}
while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
// return the ArrayList containing the given row from the database.
return rowArray;
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try
{
// ask the database object to create the cursor.
cursor = db.query(
TABLE_NAME,
new String[]{TABLE_ROW_ID, TABLE_ROW_01, TABLE_ROW_02, TABLE_ROW_03, TABLE_ROW_04, TABLE_ROW_05, TABLE_ROW_06, TABLE_ROW_07, TABLE_ROW_08, TABLE_ROW_09, TABLE_ROW_10},
null, null, null, null, null
);
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it
// to the ArrayList.
if (!cursor.isAfterLast())
{
do
{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataList.add(cursor.getString(4));
dataList.add(cursor.getLong(5));
dataList.add(cursor.getString(6));
dataList.add(cursor.getString(7));
dataList.add(cursor.getString(8));
dataList.add(cursor.getLong(9));
dataList.add(cursor.getString(10));
dataArrays.add(dataList);
}
// move the cursor's pointer up one position.
while (cursor.moveToNext());
}
}
catch (SQLException e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from
// the database.
return dataArrays;
}
public void setContext(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
Log.d(getClass().getSimpleName(), "onCreate(SQLiteDatabase db)");
// This string is used to create the database. It should
// be changed to suit your needs.
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_01 + " text," +
TABLE_ROW_02 + " text," +
TABLE_ROW_03 + " text," +
TABLE_ROW_04 + " text," +
TABLE_ROW_05 + " integer," +
TABLE_ROW_06 + " text," +
TABLE_ROW_07 + " text," +
TABLE_ROW_08 + " text," +
TABLE_ROW_09 + " integer," +
TABLE_ROW_10 + " text" +
");";
// execute the query string to the database.
db.execSQL(newTableQueryString);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// only used when updating database
}
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.utils;
import android.os.Parcel;
import android.os.Parcelable;
public class ChatMessage implements Parcelable {
private int mType;
private String mChannel;
private String mChatMessage;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mType);
out.writeString(mChannel);
out.writeString(mChatMessage);
}
public static final Parcelable.Creator<ChatMessage> CREATOR
= new Parcelable.Creator<ChatMessage>() {
public ChatMessage createFromParcel(Parcel in) {
return new ChatMessage(in);
}
public ChatMessage[] newArray(int size) {
return new ChatMessage[size];
}
};
private ChatMessage(Parcel in) {
mType = in.readInt();
mChannel = in.readString();
mChatMessage = in.readString();
}
///////
public ChatMessage(){
}
public String getChatMessage() {
return mChatMessage;
}
public void setChatMessage(String chatMessage) {
mChatMessage = chatMessage;
}
public int getType() {
return mType;
}
public void setType(int type) {
mType = type;
}
public String getChannel() {
return mChannel;
}
public void setChannel(String channel) {
mChannel = channel;
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3.utils;
public class ProfileState {
private int mProfileId;
private String mProfileName;
private String mProfileNickname;
private String mProfileAltnick;
private String mProfileServer;
private int mProfilePort;
private String mProfileChatrooms;
private String mProfileIdent;
private String mProfileRealname;
private int mProfileEncoding;
private String mProfileOnconnect;
private int mConnected;
public int getProfileId() {
return mProfileId;
}
public void setProfileId(int profileId) {
mProfileId = profileId;
}
public String getProfile_name() {
return mProfileName;
}
public void setProfileName(String profileName) {
mProfileName = profileName;
}
public String getProfileNickname() {
return mProfileNickname;
}
public void setProfileNickname(String profileNickname) {
mProfileNickname = profileNickname;
}
public String getProfileAltnick() {
return mProfileAltnick;
}
public void setProfileAltnick(String profileAltnick) {
mProfileAltnick = profileAltnick;
}
public String getProfileServer() {
return mProfileServer;
}
public void setProfileServer(String profileServer) {
mProfileServer = profileServer;
}
public int getProfilePort() {
return mProfilePort;
}
public void setProfilePort(int profilePort) {
mProfilePort = profilePort;
}
public String getProfileChatrooms() {
return mProfileChatrooms;
}
public void setProfileChatrooms(String profileChatrooms) {
mProfileChatrooms = profileChatrooms;
}
public String getProfileIdent() {
return mProfileIdent;
}
public void setProfileIdent(String profileIdent) {
mProfileIdent = profileIdent;
}
public String getProfileRealname() {
return mProfileRealname;
}
public void setProfileRealname(String profileRealname) {
mProfileRealname = profileRealname;
}
public int getProfileEncoding() {
return mProfileEncoding;
}
public void setProfileEncoding(int profileEncoding) {
mProfileEncoding = profileEncoding;
}
public String getProfileOnconnect() {
return mProfileOnconnect;
}
public void setProfileOnconnect(String profileOnconnect) {
mProfileOnconnect = profileOnconnect;
}
public int getConnected() {
return mConnected;
}
public void setConnected(int connected) {
mConnected = connected;
}
}
|
Java
|
/*
* fIRC - a free IRC client for the Android platform.
* http://code.google.com/p/firc-chat/
*
* Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com>
* http://www.multigesture.net/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.falcon4ever.fIRC3;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
// Notes: Just an experiment to show current playing track info
public class PlaceholderActivity extends Activity {
private String mTrack = null;
private String mArtist = null;
private String mAlbum = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.placeholder);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("com.android.music.metachanged");
registerReceiver(mReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
mTrack = intent.getStringExtra("track");
mArtist = intent.getStringExtra("artist");
mAlbum = intent.getStringExtra("album");
String lastSong = "Playing: \"" + mArtist + " - " + mTrack + " (" + mAlbum + ")\"";
Log.d("NowPlaying", lastSong);
}
};
}
|
Java
|
package org.jared.commons.ui;
/**
* Copyright 2010 Eric Taix (eric.taix@gmail.com) 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.
*/
import android.content.Context;
import android.graphics.*;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
/**
* The workspace is a wide area with a infinite number of screens. Each screen contains a view. A workspace is meant to
* be used with a fixed width only.<br/>
* <br/>
* This code has been done by using com.android.launcher.Workspace.java
*/
public class WorkspaceView extends ViewGroup {
private static final int INVALID_POINTER = -1;
private int mActivePointerId = INVALID_POINTER;
private static final int INVALID_SCREEN = -1;
// The velocity at which a fling gesture will cause us to snap to the next screen
private static final int SNAP_VELOCITY = 500;
// the default screen index
private int defaultScreen;
// The current screen index
private int currentScreen;
// The next screen index
private int nextScreen = INVALID_SCREEN;
// Wallpaper properties
private Bitmap wallpaper;
private Paint paint;
private int wallpaperWidth;
private int wallpaperHeight;
private float wallpaperOffset;
private boolean wallpaperLoaded;
private boolean firstWallpaperLayout = true;
private static final int TAB_INDICATOR_HEIGHT_PCT = 1;
private RectF selectedTab;
// The scroller which scroll each view
private Scroller scroller;
// A tracker which to calculate the velocity of a mouvement
private VelocityTracker mVelocityTracker;
// Tha last known values of X and Y
private float lastMotionX;
private float lastMotionY;
private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
// The current touch state
private int touchState = TOUCH_STATE_REST;
// The minimal distance of a touch slop
private int touchSlop;
// An internal flag to reset long press when user is scrolling
private boolean allowLongPress;
// A flag to know if touch event have to be ignored. Used also in internal
private boolean locked;
private WorkspaceOvershootInterpolator mScrollInterpolator;
private int mMaximumVelocity;
private Paint selectedTabPaint;
private Canvas canvas;
private RectF bar;
private Paint tabIndicatorBackgroundPaint;
private static class WorkspaceOvershootInterpolator implements Interpolator {
private static final float DEFAULT_TENSION = 1.3f;
private float mTension;
public WorkspaceOvershootInterpolator() {
mTension = DEFAULT_TENSION;
}
public void setDistance(int distance) {
mTension = distance > 0 ? DEFAULT_TENSION / distance : DEFAULT_TENSION;
}
public void disableSettle() {
mTension = 0.f;
}
public float getInterpolation(float t) {
// _o(t) = t * t * ((tension + 1) * t + tension)
// o(t) = _o(t - 1) + 1
t -= 1.0f;
return t * t * ((mTension + 1) * t + mTension) + 1.0f;
}
}
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
*/
public WorkspaceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
* @param defStyle Unused.
*/
public WorkspaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
defaultScreen = 0;
initWorkspace();
}
/**
* Initializes various states for this workspace.
*/
private void initWorkspace() {
mScrollInterpolator = new WorkspaceOvershootInterpolator();
scroller = new Scroller(getContext(),mScrollInterpolator);
currentScreen = defaultScreen;
paint = new Paint();
paint.setDither(false);
// Does this do anything for me?
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
touchSlop = configuration.getScaledTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
selectedTabPaint = new Paint();
//selectedTabPaint.setColor(Color.rgb(0x99, 0xC2, 0x24)/*Color.CYAN*/);
//selectedTabPaint.setColor(Color.RED);
selectedTabPaint.setColor(Color.rgb(0x98, 0xc8, 0xe8));
selectedTabPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tabIndicatorBackgroundPaint = new Paint();
tabIndicatorBackgroundPaint.setColor(Color.GRAY);
tabIndicatorBackgroundPaint.setStyle(Paint.Style.FILL);
}
/**
* Set a new distance that a touch can wander before we think the user is scrolling in pixels slop<br/>
*
* @param touchSlopP
*/
public void setTouchSlop(int touchSlopP) {
touchSlop = touchSlopP;
}
/**
* Set the background's wallpaper.
*/
public void loadWallpaper(Bitmap bitmap) {
wallpaper = bitmap;
wallpaperLoaded = true;
requestLayout();
invalidate();
}
boolean isDefaultScreenShowing() {
return currentScreen == defaultScreen;
}
/**
* Returns the index of the currently displayed screen.
*
* @return The index of the currently displayed screen.
*/
public int getCurrentScreen() {
return currentScreen;
}
/**
* Sets the current screen.
*
* @param currentScreen
*/
public void setCurrentScreen(int theCurrentScreen) {
if (!scroller.isFinished()) scroller.abortAnimation();
currentScreen = Math.max(0, Math.min(theCurrentScreen, getChildCount()));
scrollTo(currentScreen * getWidth(), 0);
//Log.d("workspace", "setCurrentScreen: width is " + getWidth());
invalidate();
}
/**
* Shows the default screen (defined by the firstScreen attribute in XML.)
*/
void showDefaultScreen() {
setCurrentScreen(defaultScreen);
}
/**
* Registers the specified listener on each screen contained in this workspace.
*
* @param l The listener used to respond to long clicks.
*/
@Override
public void setOnLongClickListener(OnLongClickListener l) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).setOnLongClickListener(l);
}
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
} else if (nextScreen != INVALID_SCREEN) {
currentScreen = Math.max(0, Math.min(nextScreen, getChildCount() - 1));
nextScreen = INVALID_SCREEN;
}
}
/**
* ViewGroup.dispatchDraw() supports many features we don't need: clip to padding, layout animation, animation
* listener, disappearing children, etc. The following implementation attempts to fast-track the drawing dispatch by
* drawing only what we know needs to be drawn.
*/
@Override
protected void dispatchDraw(Canvas canvas) {
// First draw the wallpaper if needed
if (wallpaper != null) {
float x = getScrollX() * wallpaperOffset;
if (x + wallpaperWidth < getRight() - getLeft()) {
x = getRight() - getLeft() - wallpaperWidth;
}
canvas.drawBitmap(wallpaper, x, (getBottom() - getTop() - wallpaperHeight) / 2, paint);
}
// Determine if we need to draw every child or only the current screen
boolean fastDraw = touchState != TOUCH_STATE_SCROLLING && nextScreen == INVALID_SCREEN;
// If we are not scrolling or flinging, draw only the current screen
if (fastDraw) {
View v = getChildAt(currentScreen);
drawChild(canvas, v, getDrawingTime());
}
else {
final long drawingTime = getDrawingTime();
// If we are flinging, draw only the current screen and the target screen
if (nextScreen >= 0 && nextScreen < getChildCount() && Math.abs(currentScreen - nextScreen) == 1) {
drawChild(canvas, getChildAt(currentScreen), drawingTime);
drawChild(canvas, getChildAt(nextScreen), drawingTime);
}
else {
// If we are scrolling, draw all of our children
final int count = getChildCount();
for (int i = 0; i < count; i++) {
drawChild(canvas, getChildAt(i), drawingTime);
}
}
}
updateTabIndicator();
canvas.drawBitmap(bitmap, getScrollX(), getMeasuredHeight()*(100-TAB_INDICATOR_HEIGHT_PCT)/100, paint);
}
/**
* Measure the workspace AND also children
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int height = MeasureSpec.getSize(heightMeasureSpec);
// Log.d("workspace","Height is " + height);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
// The children are given the same width and height as the workspace
final int count = getChildCount();
for (int i = 0; i < count; i++) {
int adjustedHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height*(100-TAB_INDICATOR_HEIGHT_PCT)/100, heightMode);
getChildAt(i).measure(widthMeasureSpec,adjustedHeightMeasureSpec);
}
// Compute wallpaper
if (wallpaperLoaded) {
wallpaperLoaded = false;
wallpaper = centerToFit(wallpaper, width, height, getContext());
wallpaperWidth = wallpaper.getWidth();
wallpaperHeight = wallpaper.getHeight();
}
wallpaperOffset = wallpaperWidth > width ? (count * width - wallpaperWidth) / ((count - 1) * (float) width) : 1.0f;
if (firstWallpaperLayout) {
scrollTo(currentScreen * width, 0);
firstWallpaperLayout = false;
}
// Log.d("workspace","Top is "+getTop()+", bottom is "+getBottom()+", left is "+getLeft()+", right is "+getRight());
updateTabIndicator();
invalidate();
}
Bitmap bitmap;
private OnLoadListener load;
private int lastEvHashCode;
private void updateTabIndicator(){
int width = getMeasuredWidth();
int height = getMeasuredHeight();
//For drawing in its own bitmap:
bar = new RectF(0, 0, width, (TAB_INDICATOR_HEIGHT_PCT*height/100));
int startPos = getScrollX()/(getChildCount());
selectedTab = new RectF(startPos, 0, startPos+width/getChildCount(), (TAB_INDICATOR_HEIGHT_PCT*height/100));
bitmap = Bitmap.createBitmap(width, (TAB_INDICATOR_HEIGHT_PCT*height/100), Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawRoundRect(bar,0,0, tabIndicatorBackgroundPaint);
canvas.drawRoundRect(selectedTab, 5,5, selectedTabPaint);
}
/**
* Overrided method to layout child
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int childLeft = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
final int childWidth = child.getMeasuredWidth();
child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
childLeft += childWidth;
}
}
if (load!=null) {
load.onLoad();
}
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (direction == View.FOCUS_LEFT) {
if (getCurrentScreen() > 0) {
scrollToScreen(getCurrentScreen() - 1);
return true;
}
}
else if (direction == View.FOCUS_RIGHT) {
if (getCurrentScreen() < getChildCount() - 1) {
scrollToScreen(getCurrentScreen() + 1);
return true;
}
}
return super.dispatchUnhandledMove(focused, direction);
}
/**
* This method JUST determines whether we want to intercept the motion. If we return true, onTouchEvent will be called
* and we do the actual scrolling there.
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// Log.d("workspace","Intercepted a touch event");
if (locked) {
return true;
}
/*
* Shortcut the most recurring case: the user is in the dragging state and he is moving his finger. We want to
* intercept this motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (touchState != TOUCH_STATE_REST)) {
return true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
// switch (action & MotionEvent.ACTION_MASK) {
switch (action) {
case MotionEvent.ACTION_MOVE:
// Log.d("workspace","Intercepted a move event");
/*
* Locally do absolute value. mLastMotionX is set to the y value of the down event.
*/
handleInterceptMove(ev);
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
final float x1 = ev.getX();
final float y1 = ev.getY();
lastMotionX = x1;
lastMotionY = y1;
allowLongPress = true;
mActivePointerId = ev.getPointerId(0);
/*
* If being flinged and user touches the screen, initiate drag; otherwise don't. mScroller.isFinished should be
* false when being flinged.
*/
touchState = scroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER;
allowLongPress = false;
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
touchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
/*
* The only time we want to intercept motion events is if we are in the drag mode.
*/
return touchState != TOUCH_STATE_REST;
}
private void handleInterceptMove(MotionEvent ev) {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
final int xDiff = (int) Math.abs(x - lastMotionX);
final int yDiff = (int) Math.abs(y - lastMotionY);
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
//Log.d("workspace","Detected move. Checking to scroll.");
if (xMoved && !yMoved) {
//Log.d("workspace","Detected X move. Scrolling.");
// Scroll if the user moved far enough along the X axis
touchState = TOUCH_STATE_SCROLLING;
lastMotionX = x;
}
// Either way, cancel any pending longpress
if (allowLongPress) {
allowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentView = getChildAt(currentScreen);
currentView.cancelLongPress();
}
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >>
MotionEvent.ACTION_POINTER_ID_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
lastMotionX = ev.getX(newPointerIndex);
lastMotionY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
/**
* Track the touch event
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Log.d("workspace","caught a touch event");
if (locked) {
return true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
final float x = ev.getX();
switch (action) {
case MotionEvent.ACTION_DOWN:
//We can still get here even if we returned false from the intercept function.
//That's the only way we can get a TOUCH_STATE_REST (0) here.
//That means that our child hasn't handled the event, so we need to
// Log.d("workspace","caught a down touch event and touchstate =" + touchState);
if(touchState != TOUCH_STATE_REST){
/*
* If being flinged and user touches, stop the fling. isFinished will be false if being flinged.
*/
if (!scroller.isFinished()) {
scroller.abortAnimation();
}
// Remember where the motion event started
lastMotionX = x;
mActivePointerId = ev.getPointerId(0);
}
break;
case MotionEvent.ACTION_MOVE:
if (touchState == TOUCH_STATE_SCROLLING) {
handleScrollMove(ev);
} else {
// Log.d("workspace","caught a move touch event but not scrolling");
//NOTE: We will never hit this case in Android 2.2. This is to fix a 2.1 bug.
//We need to do the work of interceptTouchEvent here because we don't intercept the move
//on children who don't scroll.
Log.d("workspace","handling move from onTouch");
if(onInterceptTouchEvent(ev) && touchState == TOUCH_STATE_SCROLLING){
handleScrollMove(ev);
}
}
break;
case MotionEvent.ACTION_UP:
// Log.d("workspace","caught an up touch event");
if (touchState == TOUCH_STATE_SCROLLING) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity();
if (velocityX > SNAP_VELOCITY && currentScreen > 0) {
// Fling hard enough to move left
scrollToScreen(currentScreen - 1);
}
else if (velocityX < -SNAP_VELOCITY && currentScreen < getChildCount() - 1) {
// Fling hard enough to move right
scrollToScreen(currentScreen + 1);
}
else {
snapToDestination();
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
touchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
break;
case MotionEvent.ACTION_CANCEL:
Log.d("workspace","caught a cancel touch event");
touchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
break;
case MotionEvent.ACTION_POINTER_UP:
Log.d("workspace","caught a pointer up touch event");
onSecondaryPointerUp(ev);
break;
}
return true;
}
private void handleScrollMove(MotionEvent ev){
// Scroll to follow the motion event
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x1 = ev.getX(pointerIndex);
final int deltaX = (int) (lastMotionX - x1);
lastMotionX = x1;
if (deltaX < 0) {
if (getScrollX() > 0) {
//Scrollby invalidates automatically
scrollBy(Math.max(-getScrollX(), deltaX), 0);
}
}
else if (deltaX > 0) {
final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - getScrollX() - getWidth();
if (availableToScroll > 0) {
//Scrollby invalidates automatically
scrollBy(Math.min(availableToScroll, deltaX), 0);
}
} else {
awakenScrollBars();
}
}
/**
* Scroll to the appropriated screen depending of the current position
*/
private void snapToDestination() {
final int screenWidth = getWidth();
final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth;
//Log.d("workspace", "snapToDestination");
scrollToScreen(whichScreen);
}
/**
* Scroll to a specific screen
*
* @param whichScreen
*/
public void scrollToScreen(int whichScreen) {
scrollToScreen(whichScreen, false);
}
private void scrollToScreen(int whichScreen, boolean immediate){
//Log.d("workspace", "snapToScreen=" + whichScreen);
boolean changingScreens = whichScreen != currentScreen;
nextScreen = whichScreen;
View focusedChild = getFocusedChild();
if (focusedChild != null && changingScreens && focusedChild == getChildAt(currentScreen)) {
focusedChild.clearFocus();
}
final int newX = whichScreen * getWidth();
final int delta = newX - getScrollX();
//Log.d("workspace", "newX=" + newX + " scrollX=" + getScrollX() + " delta=" + delta);
scroller.startScroll(getScrollX(), 0, delta, 0, immediate ? 0 : Math.abs(delta) * 2);
invalidate();
}
public void scrollToScreenImmediate(int whichScreen){
scrollToScreen(whichScreen, true);
}
/**
* Return the parceable instance to be saved
*/
@Override
protected Parcelable onSaveInstanceState() {
final SavedState state = new SavedState(super.onSaveInstanceState());
state.currentScreen = currentScreen;
return state;
}
/**
* Restore the previous saved current screen
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
if (savedState.currentScreen != -1) {
currentScreen = savedState.currentScreen;
}
}
/**
* Scroll to the left right screen
*/
public void scrollLeft() {
if (nextScreen == INVALID_SCREEN && currentScreen > 0 && scroller.isFinished()) {
scrollToScreen(currentScreen - 1);
}
}
/**
* Scroll to the next right screen
*/
public void scrollRight() {
if (nextScreen == INVALID_SCREEN && currentScreen < getChildCount() - 1 && scroller.isFinished()) {
scrollToScreen(currentScreen + 1);
}
}
/**
* Return the screen's index where a view has been added to.
*
* @param v
* @return
*/
public int getScreenForView(View v) {
int result = -1;
if (v != null) {
ViewParent vp = v.getParent();
int count = getChildCount();
for (int i = 0; i < count; i++) {
if (vp == getChildAt(i)) {
return i;
}
}
}
return result;
}
/**
* Return a view instance according to the tag parameter or null if the view could not be found
*
* @param tag
* @return
*/
public View getViewForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
View child = getChildAt(screen);
if (child.getTag() == tag) {
return child;
}
}
return null;
}
/**
* Unlocks the SlidingDrawer so that touch events are processed.
*
* @see #lock()
*/
public void unlock() {
locked = false;
}
/**
* Locks the SlidingDrawer so that touch events are ignores.
*
* @see #unlock()
*/
public void lock() {
locked = true;
}
/**
* @return True is long presses are still allowed for the current touch
*/
public boolean allowLongPress() {
return allowLongPress;
}
/**
* Move to the default screen
*/
public void moveToDefaultScreen() {
scrollToScreen(defaultScreen);
getChildAt(defaultScreen).requestFocus();
}
// ========================= INNER CLASSES ==============================
/**
* A SavedState which save and load the current screen
*/
public static class SavedState extends BaseSavedState {
int currentScreen = -1;
/**
* Internal constructor
*
* @param superState
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Private constructor
*
* @param in
*/
private SavedState(Parcel in) {
super(in);
currentScreen = in.readInt();
}
/**
* Save the current screen
*/
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(currentScreen);
}
/**
* Return a Parcelable creator
*/
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
//Added for "flipper" compatibility
public int getDisplayedChild(){
return getCurrentScreen();
}
public void setDisplayedChild(int i){
// setCurrentScreen(i);
scrollToScreen(i);
getChildAt(i).requestFocus();
}
public void setOnLoadListener(OnLoadListener load){
this.load = load;
}
public void flipLeft(){
scrollLeft();
}
public void flipRight(){
scrollRight();
}
// ======================== UTILITIES METHODS ==========================
/**
* Return a centered Bitmap
*
* @param bitmap
* @param width
* @param height
* @param context
* @return
*/
static Bitmap centerToFit(Bitmap bitmap, int width, int height, Context context) {
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
if (bitmapWidth < width || bitmapHeight < height) {
// Normally should get the window_background color of the context
int color = Integer.valueOf("FF191919", 16);
Bitmap centered = Bitmap.createBitmap(bitmapWidth < width ? width : bitmapWidth, bitmapHeight < height ? height
: bitmapHeight, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(centered);
canvas.drawColor(color);
canvas.drawBitmap(bitmap, (width - bitmapWidth) / 2.0f, (height - bitmapHeight) / 2.0f, null);
bitmap = centered;
}
return bitmap;
}
}
|
Java
|
package org.jared.commons.ui;
public interface OnLoadListener {
void onLoad();
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.http;
/**
* Mock for {@link LowLevelHttpRequest}.
*
* @author Yaniv Inbar
*/
public class MockLowLevelHttpRequest extends LowLevelHttpRequest {
@Override
public void addHeader(String name, String value) {
}
@Override
public LowLevelHttpResponse execute() {
return new MockLowLevelHttpResponse();
}
@Override
public void setContent(HttpContent content) {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.http;
import java.io.IOException;
import java.io.OutputStream;
/**
* Mock for {@link HttpContent}.
*
* @author Yaniv Inbar
*/
public class MockHttpContent implements HttpContent {
public String encoding;
public long length = -1;
public String type;
public byte[] content = "".getBytes();
public String getEncoding() {
return encoding;
}
public long getLength() {
return length;
}
public String getType() {
return type;
}
public void writeTo(OutputStream out) throws IOException {
out.write(content);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.http;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
/**
* Mock for {@link LowLevelHttpTransport}.
*
* @author Yaniv Inbar
*/
public class MockLowLevelHttpTransport extends LowLevelHttpTransport {
public Set<String> supportedOptionalMethods = new TreeSet<String>();
@Override
public LowLevelHttpRequest buildDeleteRequest(String url) {
return new MockLowLevelHttpRequest();
}
@Override
public LowLevelHttpRequest buildGetRequest(String url) {
return new MockLowLevelHttpRequest();
}
@Override
public LowLevelHttpRequest buildHeadRequest(String url) throws IOException {
if (!supportsHead()) {
return super.buildHeadRequest(url);
}
return new MockLowLevelHttpRequest();
}
@Override
public LowLevelHttpRequest buildPatchRequest(String url) throws IOException {
if (!supportsPatch()) {
return super.buildPatchRequest(url);
}
return new MockLowLevelHttpRequest();
}
@Override
public LowLevelHttpRequest buildPostRequest(String url) {
return new MockLowLevelHttpRequest();
}
@Override
public LowLevelHttpRequest buildPutRequest(String url) {
return new MockLowLevelHttpRequest();
}
@Override
public boolean supportsHead() {
return supportedOptionalMethods.contains("HEAD");
}
@Override
public boolean supportsPatch() {
return supportedOptionalMethods.contains("PATCH");
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.http;
import com.google.api.client.util.Strings;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Mock for {@link LowLevelHttpResponse}.
*
* @author Yaniv Inbar
*/
public class MockLowLevelHttpResponse extends LowLevelHttpResponse {
public InputStream content = null;
public String contentType = "application/json";
public int statusCode = 200;
public ArrayList<String> headerNames = new ArrayList<String>();
public ArrayList<String> headerValues = new ArrayList<String>();
public void addHeader(String name, String value) {
headerNames.add(name);
headerValues.add(value);
}
public void setContent(String stringContent) {
content = new ByteArrayInputStream(Strings.toBytesUtf8(stringContent));
}
@Override
public InputStream getContent() {
return content;
}
@Override
public String getContentEncoding() {
return null;
}
@Override
public long getContentLength() {
return 0;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public int getHeaderCount() {
return headerNames.size();
}
@Override
public String getHeaderName(int index) {
return headerNames.get(index);
}
@Override
public String getHeaderValue(int index) {
return headerValues.get(index);
}
@Override
public String getReasonPhrase() {
return null;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getStatusLine() {
return null;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.linewrap.LineWrapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Yaniv Inbar
*/
public class Generation {
static void compute(List<AbstractFileGenerator> fileGenerators, File outputDirectory)
throws IOException {
int size = 0;
List<FileComputer> fileComputers = new ArrayList<FileComputer>();
System.out.println();
System.out.println("Computing " + fileGenerators.size() + " file(s):");
Set<String> outputFilePaths = new HashSet<String>();
for (AbstractFileGenerator fileGenerator : fileGenerators) {
FileComputer fileComputer = new FileComputer(fileGenerator, outputDirectory);
if (!outputFilePaths.add(fileComputer.outputFilePath)) {
System.err.println("Error: duplicate output file path: " + fileComputer.outputFilePath);
System.exit(1);
}
fileComputers.add(fileComputer);
fileComputer.compute();
System.out.print('.');
if (fileComputer.status != FileStatus.UNCHANGED) {
size++;
}
}
System.out.println();
System.out.println();
System.out.println("Output root directory: " + outputDirectory);
System.out.println();
if (size != 0) {
System.out.println(size + " update(s):");
int index = 0;
for (FileComputer fileComputer : fileComputers) {
if (fileComputer.status != FileStatus.UNCHANGED) {
index++;
System.out.println(
fileComputer.outputFilePath + " (" + fileComputer.status.toString().toLowerCase()
+ ")");
}
}
} else {
System.out.println("All files up to date.");
}
}
static File getDirectory(String path) {
File directory = new File(path);
if (!directory.isDirectory()) {
System.err.println("not a directory: " + path);
System.exit(1);
}
return directory;
}
private enum FileStatus {
UNCHANGED, ADDED, UPDATED, DELETED
}
private static class FileComputer {
private final AbstractFileGenerator fileGenerator;
FileStatus status = FileStatus.UNCHANGED;
final String outputFilePath;
private final File outputDirectory;
FileComputer(AbstractFileGenerator fileGenerator, File outputDirectory) {
this.fileGenerator = fileGenerator;
this.outputDirectory = outputDirectory;
outputFilePath = fileGenerator.getOutputFilePath();
}
void compute() throws IOException {
File file = new File(outputDirectory, outputFilePath);
boolean exists = file.exists();
boolean isGenerated = fileGenerator.isGenerated();
if (isGenerated) {
StringWriter stringWriter = new StringWriter();
PrintWriter stringPrintWriter = new PrintWriter(stringWriter);
fileGenerator.generate(stringPrintWriter);
String content = stringWriter.toString();
LineWrapper lineWrapper = fileGenerator.getLineWrapper();
if (lineWrapper != null) {
content = lineWrapper.compute(content);
}
if (exists) {
String currentContent = readFile(file);
if (currentContent.equals(content)) {
return;
}
}
file.getParentFile().mkdirs();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
if (exists) {
status = FileStatus.UPDATED;
} else {
status = FileStatus.ADDED;
}
} else if (exists) {
file.delete();
status = FileStatus.DELETED;
}
}
}
static String readFile(File file) throws IOException {
InputStream content = new FileInputStream(file);
try {
int length = (int) file.length();
byte[] buffer = new byte[length];
content.read(buffer);
return new String(buffer, 0, length);
} finally {
content.close();
}
}
private Generation() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.model;
/**
* @author Yaniv Inbar
*/
public final class DependencyModel implements Comparable<DependencyModel> {
public String artifactId;
public String groupId;
public String scope;
public String version;
public int compareTo(DependencyModel other) {
int compare = groupId.compareTo(other.groupId);
if (compare != 0) {
return compare;
}
return artifactId.compareTo(other.artifactId);
}
@Override
public int hashCode() {
return artifactId.hashCode() * 31 + groupId.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DependencyModel)) {
return false;
}
DependencyModel other = (DependencyModel) obj;
return artifactId.equals(other.artifactId) && groupId.equals(other.groupId);
}
@Override
public String toString() {
return "DependencyModel [artifactId=" + artifactId + ", groupId=" + groupId
+ (scope != null ? ", scope=" + scope : "")
+ (version != null ? ", version=" + version : "") + "]";
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.model;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Yaniv Inbar
*/
public final class PackageModel implements Comparable<PackageModel> {
public static final String VERSION = "1.2.3-alpha";
public static final String VERSION_SNAPSHOT = VERSION + "-SNAPSHOT";
private static final Pattern IMPORT_PATTERN = Pattern.compile("\nimport ([\\w.]+);");
public final String artifactId;
public final String directoryPath;
public final TreeSet<DependencyModel> dependencies = new TreeSet<DependencyModel>();
private PackageModel(String artifactId) {
this.artifactId = artifactId;
directoryPath = "com/" + artifactId.replace('-', '/');
}
public int compareTo(PackageModel other) {
return artifactId.compareTo(other.artifactId);
}
@Override
public String toString() {
return "PackageModel [artifactId=" + artifactId + ", directoryPath=" + directoryPath
+ ", dependencies=" + dependencies + "]";
}
public static SortedSet<PackageModel> compute(File googleApiClientDirectory) throws IOException {
SortedSet<PackageModel> pkgs = new TreeSet<PackageModel>();
File srcDirectory = new File(googleApiClientDirectory, "src/com");
int rootPathLength = srcDirectory.getCanonicalPath().length();
addPackageModels(rootPathLength, srcDirectory, pkgs);
return pkgs;
}
private static void addPackageModels(int rootPathLength, File dir, SortedSet<PackageModel> pkgs)
throws IOException {
PackageModel pkg = null;
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
addPackageModels(rootPathLength, file, pkgs);
} else {
if (file.getName().endsWith(".java")) {
if (pkg == null) {
pkg =
new PackageModel(file
.getParentFile()
.getCanonicalPath()
.substring(1 + rootPathLength)
.replace('/', '-'));
pkgs.add(pkg);
}
String content = readFile(file);
Matcher matcher = IMPORT_PATTERN.matcher(content);
while (matcher.find()) {
String className = matcher.group(1);
String packageName = getPackageName(className);
if (className.startsWith("com.google.")) {
if (className.startsWith("com.google.api.client")) {
DependencyModel dep = new DependencyModel();
dep.groupId = "com.google.api.client";
dep.artifactId = packageName.substring("com.".length()).replace('.', '-');
dep.version = VERSION_SNAPSHOT;
if (!pkg.artifactId.equals(dep.artifactId)) {
pkg.dependencies.add(dep);
}
} else if (className.startsWith("com.google.appengine")) {
DependencyModel dep = new DependencyModel();
dep.groupId = "com.google.appengine";
dep.artifactId = "appengine-api-1.0-sdk";
dep.scope = "provided";
pkg.dependencies.add(dep);
}
} else if (className.startsWith("android.")) {
DependencyModel dep = new DependencyModel();
dep.groupId = "com.google.android";
dep.artifactId = "android";
pkg.dependencies.add(dep);
} else if (className.startsWith("org.apache.")) {
DependencyModel dep = new DependencyModel();
dep.groupId = "org.apache.httpcomponents";
dep.artifactId = "httpclient";
pkg.dependencies.add(dep);
} else if (className.startsWith("org.xmlpull.v1.")) {
DependencyModel dep = new DependencyModel();
dep.groupId = dep.artifactId = "xpp3";
pkg.dependencies.add(dep);
} else if (className.startsWith("org.codehaus.jackson.")) {
DependencyModel dep = new DependencyModel();
dep.groupId = "org.codehaus.jackson";
dep.artifactId = "jackson-core-asl";
pkg.dependencies.add(dep);
} else if (className.startsWith("java.") || className.startsWith("javax.")) {
// ignore
} else {
throw new IllegalArgumentException("unrecognized package: " + packageName);
}
}
}
}
}
}
public static String readFile(File file) throws IOException {
InputStreamContent content = new InputStreamContent();
content.setFileInput(file);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
content.writeTo(byteStream);
return new String(byteStream.toByteArray());
}
/**
* Returns the package name for the given Java class or package name, assuming that class names
* always start with a capital letter and package names always start with a lowercase letter.
*/
public static String getPackageName(String classOrPackageName) {
int lastDot = classOrPackageName.length();
if (lastDot == 0) {
return "";
}
while (true) {
int nextDot = classOrPackageName.lastIndexOf('.', lastDot - 1);
// check for error case of 2 dots in a row or starts/ends in dot
Preconditions.checkArgument(nextDot + 1 < lastDot);
if (Character.isLowerCase(classOrPackageName.charAt(nextDot + 1))) {
// check for case that input string is already a package
if (lastDot == classOrPackageName.length()) {
return classOrPackageName;
}
return classOrPackageName.substring(0, lastDot);
}
if (nextDot == -1) {
return "";
}
lastDot = nextDot;
}
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Abstract super class for all language-specific line wrappers.
*
* @author Yaniv Inbar
*/
abstract class AbstractLineWrapper implements LineWrapper {
private static final ThreadLocal<StringBuilder> LOCAL_OUT_BUFFER = new ThreadLocalStringBuilder();
private static final ThreadLocal<StringBuilder> LOCAL_PREFIX_BUFFER =
new ThreadLocalStringBuilder();
/**
* Computation state interface used for storing arbitrary data during the line wrapping
* computation that can be shared across all lines.
*/
interface ComputationState {
}
/** Thread-local string builder instance. */
static class ThreadLocalStringBuilder extends ThreadLocal<StringBuilder> {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
}
public final String compute(String text) {
// parse into separate lines
ComputationState computationState = computationState();
int nextNewLine = 0;
int lineSeparatorLength = Strings.LINE_SEPARATOR.length();
int textLength = text.length();
int copyFromTextIndex = 0;
StringBuilder prefix = LOCAL_PREFIX_BUFFER.get();
StringBuilder outBuffer = LOCAL_OUT_BUFFER.get();
outBuffer.setLength(0);
for (int curIndex = 0; nextNewLine != -1 && curIndex < textLength; curIndex = nextNewLine + 1) {
// find next line separator which we know ends in '\n'
nextNewLine = text.indexOf('\n', curIndex);
int highIndex = nextNewLine == -1 ? textLength - 1 : nextNewLine - lineSeparatorLength;
// remove whitespace from end of line
int lastNonSpace = Strings.lastIndexOfNonSpace(text, highIndex, curIndex);
if (lastNonSpace == -1) {
// empty line
if (nextNewLine == -1) {
// end of text but missing new line
outBuffer.append(text, copyFromTextIndex, curIndex);
outBuffer.append(Strings.LINE_SEPARATOR);
copyFromTextIndex = textLength;
} else if (nextNewLine != curIndex) {
// line may up of >= 1 space
outBuffer.append(text, copyFromTextIndex, curIndex);
copyFromTextIndex = highIndex + 1;
}
continue;
}
// remove whitespace from beginning of line, remembering it as a "prefix"
int firstNonSpace = Strings.indexOfNonSpace(text, curIndex, lastNonSpace);
prefix.setLength(0);
prefix.append(text, curIndex, firstNonSpace);
// iterate over each line "cut"
boolean firstCut = true;
while (true) {
// run the language-specific line-wrapping algorithm
int originalPrefixLength = prefix.length();
String line = text.substring(firstNonSpace, lastNonSpace + 1);
int cut = getCuttingPoint(computationState, line, prefix, firstCut);
// remove spaces from end of cut
cut = Strings.lastIndexOfNonSpace(line, cut - 1) + 1;
// don't want infinite recursion!
if (cut == 0) {
throw new IllegalStateException(
"illegal cutting point:" + "\nline (" + line.length() + "):" + line + "\nprefix ("
+ originalPrefixLength + "): " + prefix.substring(0, originalPrefixLength)
+ "\nfirstCut: " + firstCut);
}
if (cut == line.length() && nextNewLine != -1 && lastNonSpace == highIndex) {
// preserve to the end of line
if (!firstCut) {
copyFromTextIndex = firstNonSpace;
}
} else {
// make a cut
if (firstCut) {
outBuffer.append(text, copyFromTextIndex, firstNonSpace + cut);
copyFromTextIndex = nextNewLine == -1 ? textLength : nextNewLine + 1;
} else {
outBuffer.append(text, firstNonSpace, firstNonSpace + cut);
}
// insert a line separator
outBuffer.append(Strings.LINE_SEPARATOR);
}
// find next non-space character to start next line
int next = Strings.indexOfNonSpace(line, cut);
if (next == -1) {
break;
}
// insert prefix for next line
outBuffer.append(prefix);
firstNonSpace += next;
firstCut = false;
}
}
// optimize for case where original text is unchanged
if (copyFromTextIndex == 0) {
return text;
}
return outBuffer.append(text, copyFromTextIndex, textLength).toString();
}
/**
* Instantiates a new computation state. By default just returns an empty object, but may be
* overriden by subclasses.
*/
ComputationState computationState() {
return new ComputationState() {};
}
/**
* Returns an index in the given string where the line should be broken. If no cut is desired or
* no cut can be found, it should just return the line length. Also, this method is responsible
* for updating the current line's prefix, i.e. any additional indent to use after any subsequent
* cuts.
* <p/>
* The default implementation cuts on a space if the line length is greater than maximum width but
* subclasses may override.
*
* @param computationState computation state
* @param line current line content to be cut
* @param prefix current line prefix to be updated if necessary
* @param firstCut whether this is the first cut in the original input line
* @return index of the character at which at cut {@code >= 1} and {@code <= line.length()}
*/
abstract int getCuttingPoint(
ComputationState computationState, String line, StringBuilder prefix, boolean firstCut);
/**
* Returns a cut on a space or {@code -1} if no space found. It will try to return an index that
* is {@code <= maxWidth}.
*/
static int getCutOnSpace(String line, int maxWidth) {
int max = Math.min(line.length() - 1, maxWidth);
int index = line.lastIndexOf(' ', max);
if (index == -1) {
index = line.indexOf(' ', max + 1);
}
return index;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Utilities for strings.
*
* @author Yaniv Inbar
*/
public class Strings {
/**
* Line separator to use for this OS, i.e. {@code "\n"} or {@code "\r\n"}.
*/
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/**
* Returns the index of the first non-space ({@code ' '}) character in the given string whose
* index is greater than or equal to the given lower bound.
*
* @param string string or {@code null} for {@code -1} result
* @param lowerBound lower bound for index
* @return index or {@code -1} if not found or for {@code null} input
*/
public static int indexOfNonSpace(String string, int lowerBound) {
if (string == null) {
return -1;
}
return indexOfNonSpace(string, lowerBound, string.length() - 1);
}
/**
* Returns the index of the first non-space ({@code ' '}) character in the given string whose
* index is greater than or equal to the given lower bound and less than or equal to the given
* upper bound.
*
* @param string string or {@code null} for {@code -1} result
* @param lowerBound lower bound for index
* @param upperBound upper bound for index
* @return index or {@code -1} if not found or for {@code null} input
*/
public static int indexOfNonSpace(String string, int lowerBound, int upperBound) {
if (string != null) {
upperBound = Math.min(upperBound, string.length() - 1);
for (int i = Math.max(0, lowerBound); i <= upperBound; i++) {
if (' ' != string.charAt(i)) {
return i;
}
}
}
return -1;
}
/**
* Returns the index of the last non-space ({@code ' '}) character in the given string whose index
* is less than or equal to the given upper bound.
*
* @param string string or {@code null} for {@code -1} result
* @param upperBound upper bound for index
* @return index or {@code -1} if not found or for {@code null} input
*/
public static int lastIndexOfNonSpace(String string, int upperBound) {
return lastIndexOfNonSpace(string, upperBound, 0);
}
/**
* Returns the index of the first non-space ({@code ' '}) character in the given string whose
* index is greater than or equal to the given lower bound and less than or equal to the given
* upper bound.
*
* @param string string or {@code null} for {@code -1} result
* @param upperBound upper bound for index
* @param lowerBound lower bound for index
* @return index or {@code -1} if not found or for {@code null} input
*/
public static int lastIndexOfNonSpace(String string, int upperBound, int lowerBound) {
if (string != null) {
lowerBound = Math.max(0, lowerBound);
for (int i = Math.min(upperBound, string.length() - 1); i >= lowerBound; i--) {
if (' ' != string.charAt(i)) {
return i;
}
}
}
return -1;
}
private Strings() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Computes line wrapping on a section of text by inserting line separators and updating the
* indentation as necessary. Implementations of this interface are thread-safe.
*
* @author Yaniv Inbar
*/
public interface LineWrapper {
/** Computes line wrapping result for the given text. */
String compute(String text);
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Processes any single-line comments in the line.
*
* @author Yaniv Inbar
*/
final class SingleLineCommentProcessor {
private final String commentPrefix;
private boolean inComment;
/**
* @param commentPrefix prefix to recognize the start of a single-line comment, e.g. {@code "//"}
* in Java.
*/
SingleLineCommentProcessor(String commentPrefix) {
this.commentPrefix = commentPrefix;
}
/**
* Process the given line to check if it starts with a single-line comment.
*
* @param line current line content to be cut
* @param prefix current line prefix to be updated if necessary
* @param firstCut whether this is the first cut in the original input line
* @return whether the line starts with the single-line comment prefix
*/
boolean start(String line, StringBuilder prefix, boolean firstCut) {
if (firstCut) {
inComment = false;
}
if (!inComment && isCuttingPoint(line, 0)) {
inComment = true;
prefix.append(commentPrefix).append(' ');
}
return inComment;
}
/**
* Returns wehther the given index is the location of the single-line comment prefix.
*
* @param line current line content to be cut
*/
boolean isCuttingPoint(String line, int index) {
return line.startsWith(commentPrefix, index);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Line wrapper for XML files.
*
* @author Yaniv Inbar
*/
public class XmlLineWrapper extends AbstractLineWrapper {
/** Maximum XML line length. */
private static final int MAX_LINE_LENGTH = 80;
private static final XmlLineWrapper INSTANCE = new XmlLineWrapper();
/** Returns the instance of the XML line wrapper. */
public static LineWrapper get() {
return INSTANCE;
}
/** Computes line wrapping result for the given XML text. */
public static String wrap(String text) {
return INSTANCE.compute(text);
}
@Override
final int getCuttingPoint(
ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) {
// if there's space, don't cut the line
int maxWidth = MAX_LINE_LENGTH - prefix.length();
if (line.length() <= maxWidth) {
return line.length();
}
// indent on the first cut
if (firstCut) {
prefix.append(" ");
}
QuoteProcessor quoteProcessor = new QuoteProcessor();
int spaceCutWithinMaxWidth = -1;
int elementEndCutWithinMaxWidth = -1;
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (!quoteProcessor.isSkipped(ch)) {
switch (ch) {
case ' ':
// if past max width or found a space preceding an element start
if (i > maxWidth || i + 1 < line.length() && line.charAt(i + 1) == '<') {
// then cut here
return i;
}
// else find maximum space cut within max width
spaceCutWithinMaxWidth = i;
break;
case '/':
// falls through
case '>':
// element close?
// if first occurence of element end (not at beginning of line)
if (elementEndCutWithinMaxWidth == -1 && i != 0
&& (ch == '>' || i + 1 != line.length() && line.charAt(i + 1) == '>')) {
// if past max width, cut here
if (i > maxWidth) {
return i;
}
// find last occurence within max width
elementEndCutWithinMaxWidth = i;
// can skip parsing the slash
if (ch == '/') {
i++;
}
}
break;
}
}
// check if over max space
if (i >= maxWidth) {
if (spaceCutWithinMaxWidth != -1) {
return spaceCutWithinMaxWidth;
}
if (elementEndCutWithinMaxWidth != -1) {
return elementEndCutWithinMaxWidth;
}
}
}
return line.length();
}
XmlLineWrapper() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Processes quotes in a line. Used to detect if there are any quotes. Both {@code '"'} and {@code
* '\''} are valid quote characters.
*
* @author Yaniv Inbar
*/
final class QuoteProcessor {
private boolean lastSlash = false;
private char lastQuote = 0;
/**
* Returns whether to skip processing the given character because it is part of a quote. Note that
* this method must be called for all previous characters on the line in order for the result to
* be correct.
*/
boolean isSkipped(char ch) {
if (lastSlash) {
lastSlash = false;
return true;
}
if (lastQuote != 0) {
if (ch == lastQuote) {
// end of quote sequence
lastQuote = 0;
} else if (ch == '\\') {
// skip escaped character
lastSlash = true;
}
return true;
}
if (ch == '\'' || ch == '"') {
// start of quote sequence
lastQuote = ch;
return true;
}
return false;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Line wrapper for HTML files.
*
* @author Yaniv Inbar
*/
public final class HtmlLineWrapper extends XmlLineWrapper {
private static final HtmlLineWrapper INSTANCE = new HtmlLineWrapper();
/** Returns the instance of the HTML line wrapper. */
public static LineWrapper get() {
return INSTANCE;
}
/** Computes line wrapping result for the given HTML text. */
public static String wrap(String text) {
return INSTANCE.compute(text);
}
private HtmlLineWrapper() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Line wrapper for Java files.
*
* @author Yaniv Inbar
*/
public final class JavaLineWrapper extends AbstractLineWrapper {
/** Maximum Java line length. */
static final int MAX_LINE_LENGTH = 80;
private static final JavaLineWrapper INSTANCE = new JavaLineWrapper();
/** Java line wrapper computation state. */
static class JavaComputationState implements ComputationState {
final JavaLikeCommentProcessor multiLineComment;
final SingleLineCommentProcessor singleLineComment;
JavaComputationState(boolean useJavaMultiLineCommentProcessor, String singleLineCommentPrefix) {
multiLineComment = useJavaMultiLineCommentProcessor ? new JavaLikeCommentProcessor() : null;
singleLineComment = new SingleLineCommentProcessor(singleLineCommentPrefix);
}
/**
* Returns whether to cut on the line for a space character. Default implementation returns
* {@code true}, but subclasses may override.
*/
boolean isSpaceCut(String line, int index) {
return true;
}
}
/** Returns the instance of the Java line wrapper. */
public static LineWrapper get() {
return INSTANCE;
}
/** Computes line wrapping result for the given Java text. */
public static String wrap(String text) {
return get().compute(text);
}
/**
* {@inheritDoc}
*
* @return by default returns {@code new JavaComputationState(true, "//")}, but subclasses may
* override.
*/
@Override
ComputationState computationState() {
return new JavaComputationState(true, "//");
}
@Override
int getCuttingPoint(
ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) {
// don't cut an import
if (firstCut && line.startsWith("import ")) {
return line.length();
}
return getCuttingPointImpl(computationState,
line,
prefix,
firstCut,
MAX_LINE_LENGTH,
MAX_LINE_LENGTH);
}
/** Cutting algorithm for Java. */
static int getCuttingPointImpl(
ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) {
return getCuttingPointImpl(computationState,
line,
prefix,
firstCut,
MAX_LINE_LENGTH,
MAX_LINE_LENGTH);
}
/** Cutting algorithm for Java, with caller specified line lengths. */
static int getCuttingPointImpl(ComputationState computationState,
String line,
StringBuilder prefix,
boolean firstCut,
int maxLineLength,
int maxDocLineLength) {
// process for a multi-line comment
JavaComputationState javaCompState = (JavaComputationState) computationState;
JavaLikeCommentProcessor multiLineComment = javaCompState.multiLineComment;
if (multiLineComment != null) {
multiLineComment.processLine(line);
}
// process for single line comment
int originalPrefixLength = prefix.length();
if ((multiLineComment == null || multiLineComment.getCommentStart() == null)
&& !javaCompState.singleLineComment.start(line, prefix, firstCut)) {
// if there's space, don't cut the line
int maxWidth = maxLineLength - originalPrefixLength;
if (line.length() <= maxWidth) {
return line.length();
}
int spaceCutWithinMaxWidth = -1;
int commaSpaceCutWithinMaxWidth = -1;
int openParenCutWithinMaxWidth = -1;
int result = line.length();
QuoteProcessor quoteProcessor = new QuoteProcessor();
for (int i = 0; i < result; i++) {
char ch = line.charAt(i);
// process for quotes
if (!quoteProcessor.isSkipped(ch)) {
// process for a single-line comment
if (i >= 1 && javaCompState.singleLineComment.isCuttingPoint(line, i)) {
return i;
}
switch (ch) {
case ',':
if (i + 1 < line.length() && line.charAt(i + 1) == ' ') {
if (i + 1 <= maxWidth) {
commaSpaceCutWithinMaxWidth = i + 1;
} else {
result = i + 1;
}
}
break;
case ' ':
if (javaCompState.isSpaceCut(line, i)) {
if (i <= maxWidth) {
spaceCutWithinMaxWidth = i;
} else {
result = i;
}
}
break;
case '[':
if (i + 1 <= maxWidth) {
openParenCutWithinMaxWidth = i + 1;
} else {
result = i + 1;
}
break;
case '(':
int nextChIndex = Strings.indexOfNonSpace(line, i + 1);
if (nextChIndex != -1) {
if (line.charAt(nextChIndex) != ')') {
if (i + 1 <= maxWidth) {
openParenCutWithinMaxWidth = i + 1;
} else {
result = i + 1;
}
}
i = nextChIndex - 1;
}
break;
}
}
// check if over max space
if (i >= maxWidth) {
if (commaSpaceCutWithinMaxWidth != -1) {
result = commaSpaceCutWithinMaxWidth;
} else if (spaceCutWithinMaxWidth != -1) {
result = spaceCutWithinMaxWidth;
} else if (openParenCutWithinMaxWidth != -1) {
result = openParenCutWithinMaxWidth;
}
}
}
// indent on the first cut
if (firstCut) {
prefix.append(" ");
}
return result;
}
// is it a JavaDoc comment start?
boolean isJavaDoc =
multiLineComment != null && "/**".equals(multiLineComment.getCommentStart());
int localLength = isJavaDoc ? maxDocLineLength : maxLineLength;
// if there's space, don't cut the line
int maxWidth = localLength - originalPrefixLength;
if (line.length() <= maxWidth) {
return line.length();
}
// in a comment, so use default algorithm
int index = getCutOnSpace(line, maxWidth);
if (index != -1) {
// update the prefix so next lines are properly indented
if (firstCut && multiLineComment != null && multiLineComment.getCommentStart() != null) {
if (line.startsWith("/*")) {
prefix.append(' ');
}
prefix.append("* ");
if (isJavaDoc && javaDocAtParamPattern(line)) {
prefix.append(" ");
}
}
return index;
}
return line.length();
}
/** Returns whether it finds the {@code "@param"} in the JavaDoc. */
private static boolean javaDocAtParamPattern(String line) {
int index = 0;
if (line.startsWith("/*")) {
index += 2;
}
if (line.charAt(index) != '*') {
return false;
}
index = Strings.indexOfNonSpace(line, index + 1);
return index != -1 && (line.startsWith("@param ", index) || line.startsWith("@return ", index));
}
private JavaLineWrapper() {
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator.linewrap;
/**
* Processes multi-line comments like the ones in Java, i.e. those that start with {@code "/*"}. The
* current implementation of this processor is that {@code "/*"} must be at the beginning of the
* line, and {@code "*\/"} must be at the end of the line.
*
* @author Yaniv Inbar
*/
final class JavaLikeCommentProcessor {
/**
* Multi-line comment start prefix or {@code null} if not inside a multi-line comment.
*/
private String commentStart = null;
/**
* Current line's multi-line comment start prefix or {@code null} for none.
*/
private String curCommentStart = null;
/**
* Processes the current line for a multi-line comment. Must be called regardless of whether the
* line is going to be cut.
*/
void processLine(String line) {
/*
* TODO: support case where multi-line comments don't start at beginning of line or end at end
* of line
*/
// check if we're in a multi-line comment
if (commentStart == null && line.startsWith("/*")) {
if (line.length() >= 3 && line.charAt(2) == '*') {
// Javadoc comment
commentStart = "/**";
} else {
// non-Javadoc comment
commentStart = "/*";
}
}
// cur line's comment
curCommentStart = commentStart;
// check for end of comment
if (commentStart != null && line.endsWith("*/")) {
commentStart = null;
}
}
/**
* Returns the current line's multi-line comment start prefix or {@code null} for none.
*/
String getCommentStart() {
return curCommentStart;
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.linewrap.LineWrapper;
import com.google.api.client.generator.linewrap.XmlLineWrapper;
/**
* @author Yaniv Inbar
*/
abstract class AbstractXmlFileGenerator extends AbstractFileGenerator {
@Override
public final LineWrapper getLineWrapper() {
return XmlLineWrapper.get();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.linewrap.HtmlLineWrapper;
import com.google.api.client.generator.linewrap.LineWrapper;
/**
* @author Yaniv Inbar
*/
abstract class AbstractHtmlFileGenerator extends AbstractFileGenerator {
@Override
public final LineWrapper getLineWrapper() {
return HtmlLineWrapper.get();
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.model.PackageModel;
import java.io.PrintWriter;
import java.util.SortedSet;
/**
* @author Yaniv Inbar
*/
final class DistXmlFileGenerator extends AbstractFileGenerator {
private final SortedSet<PackageModel> pkgs;
DistXmlFileGenerator(SortedSet<PackageModel> pkgs) {
this.pkgs = pkgs;
}
@Override
public void generate(PrintWriter out) {
out.println("<assembly xmlns=\"http://maven.apache.org/plugins/"
+ "maven-assembly-plugin/assembly/1.1.0\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://maven.apache.org/plugins/"
+ "maven-assembly-plugin/assembly/1.1.0 "
+ "http://maven.apache.org/xsd/assembly-1.1.0.xsd\">");
out.println(" <id>java</id>");
out.println(" <formats>");
out.println(" <format>zip</format>");
out.println(" </formats>");
out.println(" <files>");
out.println(" <file>");
out.println(" <source>target/${project.artifactId}-${project.version}.jar</source>");
out.println(" </file>");
out.println(" <file>");
out.println(
" <source>target/${project.artifactId}-${project.version}-sources.jar</source>");
out.println(" </file>");
out.println(" <file>");
out.println(
" <source>target/${project.artifactId}-${project.version}-javadoc.jar</source>");
out.println(" </file>");
out.println(" <file>");
out.println(" <source>assemble/LICENSE</source>");
out.println(" </file>");
out.println(" <file>");
out.println(" <source>assemble/packages/readme.html</source>");
out.println(" <outputDirectory>packages</outputDirectory>");
out.println(" <filtered>true</filtered>");
out.println(" </file>");
out.println(" <file>");
out.println(" <source>assemble/readme.html</source>");
out.println(" <filtered>true</filtered>");
out.println(" </file>");
out.println(" <file>");
out.println(" <source>assemble/dependencies/readme.html</source>");
out.println(" <outputDirectory>dependencies</outputDirectory>");
out.println(" <filtered>true</filtered>");
out.println(" </file>");
for (PackageModel pkg : pkgs) {
out.println(" <file>");
out.println(" <source>modules/" + pkg.artifactId + "/target/" + pkg.artifactId + "-"
+ PackageModel.VERSION + ".jar</source>");
out.println(" <outputDirectory>packages</outputDirectory>");
out.println(" </file>");
}
out.println(" </files>");
out.println(" <fileSets>");
out.println(" <fileSet>");
out.println(" <directory>assemble/dependencies/java</directory>");
out.println(" <outputDirectory>dependencies/java</outputDirectory>");
out.println(" </fileSet>");
out.println(" </fileSets>");
out.println(" <dependencySets>");
out.println(" <dependencySet>");
out.println(" <outputDirectory>dependencies</outputDirectory>");
out.println(" <useProjectArtifact>false</useProjectArtifact>");
out.println(" </dependencySet>");
out.println(" </dependencySets>");
out.println("</assembly>");
out.close();
}
@Override
public String getOutputFilePath() {
return "assemble/dist.xml";
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.linewrap.JavaLineWrapper;
import com.google.api.client.generator.linewrap.LineWrapper;
import java.io.PrintWriter;
/**
* @author Yaniv Inbar
*/
abstract class AbstractJavaFileGenerator extends AbstractFileGenerator {
final String packageName;
final String className;
AbstractJavaFileGenerator(String packageName, String className) {
this.packageName = packageName;
this.className = className;
}
@Override
public final LineWrapper getLineWrapper() {
return JavaLineWrapper.get();
}
@Override
public final String getOutputFilePath() {
return "src/" + packageName.replace('.', '/') + "/" + className + ".java";
}
void generateHeader(PrintWriter out) {
out.println("/*");
out.println(" * Copyright (c) 2010 Google Inc.");
out.println(" *");
out.println(" * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not");
out.println(" * use this file except in compliance with the License. You may obtain a copy of");
out.println(" * the License at");
out.println(" *");
out.println(" * http://www.apache.org/licenses/LICENSE-2.0");
out.println(" *");
out.println(" * Unless required by applicable law or agreed to in writing, software");
out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT");
out.println(" * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the");
out.println(" * License for the specific language governing permissions and limitations under");
out.println(" * the License.");
out.println(" */");
out.println();
out.println("package " + packageName + ";");
out.println();
}
String useClass(Class<?> clazz) {
String fullName = clazz.getName();
int lastDot = fullName.lastIndexOf('.');
return fullName.substring(lastDot + 1).replace('$', '.');
}
static String indent(int numSpaces) {
return " ".substring(0, numSpaces);
}
}
|
Java
|
/*
* Copyright (c) 2010 Google Inc.
*
* 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.google.api.client.generator;
import com.google.api.client.generator.model.DependencyModel;
import com.google.api.client.generator.model.PackageModel;
import java.io.PrintWriter;
/**
* @author Yaniv Inbar
*/
final class ModulePomFileGenerator extends AbstractFileGenerator {
private final PackageModel pkg;
ModulePomFileGenerator(PackageModel pkg) {
this.pkg = pkg;
}
@Override
public void generate(PrintWriter out) {
out.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 "
+ "http://maven.apache.org/maven-v4_0_0.xsd\">");
out.println(" <modelVersion>4.0.0</modelVersion>");
out.println(" <parent>");
out.println(" <groupId>com.google.api.client</groupId>");
out.println(" <artifactId>google-api-client-modules-parent</artifactId>");
out.println(" <version>" + PackageModel.VERSION_SNAPSHOT + "</version>");
out.println(" </parent>");
out.println(" <artifactId>" + pkg.artifactId + "</artifactId>");
out.println(" <build>");
out.println(" <plugins>");
out.println(" <plugin>");
out.println(" <artifactId>maven-source-plugin</artifactId>");
out.println(" <version>2.0.4</version>");
out.println(" <configuration>");
out.println(" <excludeResources>true</excludeResources>");
out.println(" </configuration>");
out.println(" </plugin>");
out.println(" </plugins>");
out.println(" <resources>");
out.println(" <resource>");
out.println(" <filtering>false</filtering>");
out.println(" <directory>../../target/classes</directory>");
out.println(" <includes>");
out.println(" <include>" + pkg.directoryPath + "/*</include>");
out.println(" </includes>");
out.println(" </resource>");
out.println(" </resources>");
out.println(" </build>");
out.println(" <dependencies>");
for (DependencyModel dep : pkg.dependencies) {
out.println(" <dependency>");
out.println(" <groupId>" + dep.groupId + "</groupId>");
out.println(" <artifactId>" + dep.artifactId + "</artifactId>");
if (dep.version != null) {
out.println(" <version>" + dep.version + "</version>");
}
if (dep.scope != null) {
out.println(" <scope>" + dep.scope + "</scope>");
}
out.println(" </dependency>");
}
out.println(" </dependencies>");
out.println("</project>");
out.close();
}
@Override
public String getOutputFilePath() {
return "modules/" + pkg.artifactId + "/pom.xml";
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.