code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 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.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 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.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 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.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 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.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 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.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 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.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.tech; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.NfcF; import com.sinpo.xnfc.nfc.Util; public class FeliCa { public static final byte[] EMPTY = {}; protected byte[] data; protected FeliCa() { } protected FeliCa(byte[] bytes) { data = (bytes == null) ? FeliCa.EMPTY : bytes; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class IDm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public IDm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes); } public final String getManufactureCode() { return Util.toHexString(data, 0, 2); } public final String getCardIdentification() { return Util.toHexString(data, 2, 6); } public boolean isEmpty() { final byte[] d = data; for (final byte v : d) { if (v != 0) return false; } return true; } } public final static class PMm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public PMm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes); } public final String getIcCode() { return Util.toHexString(data, 0, 2); } public final String getMaximumResponseTime() { return Util.toHexString(data, 2, 6); } } public final static class SystemCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public SystemCode(byte[] sc) { super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc); } public int toInt() { return toInt(data); } public static int toInt(byte[] data) { return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1])); } } public final static class ServiceCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public static final int T_UNKNOWN = 0; public static final int T_RANDOM = 1; public static final int T_CYCLIC = 2; public static final int T_PURSE = 3; public ServiceCode(byte[] sc) { super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc); } public ServiceCode(int code) { this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) }); } public int toInt() { return 0x0000FFFF & ((data[1] << 8) | (0x000000FF & data[0])); } public boolean isEncrypt() { return (data[0] & 0x1) == 0; } public boolean isWritable() { final int f = data[0] & 0x3F; return (f & 0x2) == 0 || f == 0x13 || f == 0x12; } public int getAccessAttr() { return data[0] & 0x3F; } public int getDataType() { final int f = data[0] & 0x3F; if ((f & 0x10) == 0) return T_PURSE; return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC; } } public final static class Block extends FeliCa { public Block() { data = new byte[16]; } public Block(byte[] bytes) { super((bytes == null || bytes.length < 16) ? new byte[16] : bytes); } } public final static class BlockListElement extends FeliCa { private static final byte LENGTH_2_BYTE = (byte) 0x80; private static final byte LENGTH_3_BYTE = (byte) 0x00; // private static final byte ACCESSMODE_DECREMENT = (byte) 0x00; // private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01; private final byte lengthAndaccessMode; private final byte serviceCodeListOrder; public BlockListElement(byte mode, byte order, byte... blockNumber) { if (blockNumber.length > 1) { lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF); } else { lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF); } serviceCodeListOrder = (byte) (order & 0x0F); data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber; } @Override public byte[] getBytes() { if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) { ByteBuffer buff = ByteBuffer.allocate(2); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[0]); return buff.array(); } else { ByteBuffer buff = ByteBuffer.allocate(3); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[1]).put(data[0]); return buff.array(); } } } public final static class MemoryConfigurationBlock extends FeliCa { public MemoryConfigurationBlock(byte[] bytes) { super((bytes == null || bytes.length < 4) ? new byte[4] : bytes); } public boolean isNdefSupport() { return (data == null) ? false : (data[3] & (byte) 0xff) == 1; } public void setNdefSupport(boolean ndefSupport) { data[3] = (byte) (ndefSupport ? 1 : 0); } public boolean isWritable(int... addrs) { if (data == null) return false; boolean result = true; for (int a : addrs) { byte b = (byte) ((a & 0xff) + 1); if (a < 8) { result &= (data[0] & b) == b; continue; } else if (a < 16) { result &= (data[1] & b) == b; continue; } else result &= (data[2] & b) == b; } return result; } } public final static class Service extends FeliCa { private final ServiceCode[] serviceCodes; private final BlockListElement[] blockListElements; public Service(ServiceCode[] codes, BlockListElement... blocks) { serviceCodes = (codes == null) ? new ServiceCode[0] : codes; blockListElements = (blocks == null) ? new BlockListElement[0] : blocks; } @Override public byte[] getBytes() { int length = 0; for (ServiceCode s : this.serviceCodes) { length += s.getBytes().length; } for (BlockListElement b : blockListElements) { length += b.getBytes().length; } ByteBuffer buff = ByteBuffer.allocate(length); for (ServiceCode s : this.serviceCodes) { buff.put(s.getBytes()); } for (BlockListElement b : blockListElements) { buff.put(b.getBytes()); } return buff.array(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (ServiceCode s : serviceCodes) { sb.append(s.toString()); } for (BlockListElement b : blockListElements) { sb.append(b.toString()); } return sb.toString(); } } public final static class Command extends FeliCa { private final int length; private final byte code; private final IDm idm; public Command(final byte[] bytes) { this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length)); } public Command(byte code, final byte... bytes) { this.code = code; if (bytes.length >= 8) { idm = new IDm(Arrays.copyOfRange(bytes, 0, 8)); data = Arrays.copyOfRange(bytes, 8, bytes.length); } else { idm = null; data = bytes; } length = bytes.length + 2; } public Command(byte code, IDm idm, final byte... bytes) { this.code = code; this.idm = idm; this.data = bytes; this.length = idm.getBytes().length + data.length + 2; } public Command(byte code, byte[] idm, final byte... bytes) { this.code = code; this.idm = new IDm(idm); this.data = bytes; this.length = idm.length + data.length + 2; } @Override public byte[] getBytes() { ByteBuffer buff = ByteBuffer.allocate(length); byte length = (byte) this.length; if (idm != null) { buff.put(length).put(code).put(idm.getBytes()).put(data); } else { buff.put(length).put(code).put(data); } return buff.array(); } } public static class Response extends FeliCa { protected final int length; protected final byte code; protected final IDm idm; public Response(byte[] bytes) { if (bytes != null && bytes.length >= 10) { length = bytes[0] & 0xff; code = bytes[1]; idm = new IDm(Arrays.copyOfRange(bytes, 2, 10)); data = bytes; } else { length = 0; code = 0; idm = new IDm(null); data = FeliCa.EMPTY; } } public IDm getIDm() { return idm; } } public final static class PollingResponse extends Response { private final PMm pmm; public PollingResponse(byte[] bytes) { super(bytes); if (size() >= 18) { pmm = new PMm(Arrays.copyOfRange(data, 10, 18)); } else { pmm = new PMm(null); } } public PMm getPMm() { return pmm; } } public final static class ReadResponse extends Response { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF }; private final byte[] blockData; public ReadResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) { blockData = Arrays.copyOfRange(data, 13, data.length); } else { blockData = FeliCa.EMPTY; } } public int getStatusFlag1() { return data[10] & 0x000000FF; } public int getStatusFlag2() { return data[11] & 0x000000FF; } public int getStatusFlag12() { return (getStatusFlag1() << 8) | getStatusFlag2(); } public int getBlockCount() { return (data.length > 12) ? (0xFF & data[12]) : 0; } public byte[] getBlockData() { return blockData; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class WriteResponse extends Response { public WriteResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); } public int getStatusFlag1() { return data[0] & 0x000000FF; } public int getStatusFlag2() { return data[1] & 0x000000FF; } public int getStatusFlag12() { return (getStatusFlag1() << 8) | getStatusFlag2(); } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class Tag { private final NfcF nfcTag; private boolean isFeliCaLite; private byte[] sys; private IDm idm; private PMm pmm; public Tag(NfcF tag) { nfcTag = tag; sys = tag.getSystemCode(); idm = new IDm(tag.getTag().getId()); pmm = new PMm(tag.getManufacturer()); } public int getSystemCode() { return SystemCode.toInt(sys); } public byte[] getSystemCodeByte() { return sys; } public IDm getIDm() { return idm; } public PMm getPMm() { return pmm; } public boolean checkFeliCaLite() throws IOException { isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty(); return isFeliCaLite; } public boolean isFeliCaLite() { return isFeliCaLite; } public PollingResponse polling(int systemCode) throws IOException { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (systemCode >> 8), (byte) (systemCode & 0xff), (byte) 0x01, (byte) 0x00 }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final PollingResponse rsp = new PollingResponse(r); idm = rsp.getIDm(); pmm = rsp.getPMm(); return rsp; } public PollingResponse polling() throws IOException { return polling(SYS_FELICA_LITE); } public final SystemCode[] getSystemCodeList() throws IOException { final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final int num; if (r == null || r.length < 12 || r[1] != (byte) 0x0d) { num = 0; } else { num = r[10] & 0x000000FF; } final SystemCode ret[] = new SystemCode[num]; for (int i = 0; i < num; ++i) { ret[i] = new SystemCode(Arrays.copyOfRange(r, 11 + i * 2, 13 + i * 2)); } return ret; } public ServiceCode[] getServiceCodeList() throws IOException { ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>(); int index = 1; while (true) { byte[] bytes = searchServiceCode(index); if (bytes.length != 2 && bytes.length != 4) break; if (bytes.length == 2) { if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff) break; ret.add(new ServiceCode(bytes)); } ++index; } return ret.toArray(new ServiceCode[ret.size()]); } public byte[] searchServiceCode(int index) throws IOException { Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] { (byte) (index & 0xff), (byte) (index >> 8) }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final byte ret[]; if (r == null || r.length < 12 || r[1] != (byte) 0x0b) ret = FeliCa.EMPTY; else ret = Arrays.copyOfRange(r, 10, r.length); return ret; } public ReadResponse readWithoutEncryption(byte addr, byte... service) throws IOException { Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) service[0], (byte) service[1], (byte) 0x01, (byte) 0x80, addr }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final ReadResponse ret = new ReadResponse(r); return ret; } public ReadResponse readWithoutEncryption(ServiceCode code, byte addr) throws IOException { return readWithoutEncryption(addr, code.getBytes()); } public ReadResponse readWithoutEncryption(byte addr) throws IOException { final byte code0 = (byte) (SRV_FELICA_LITE_READWRITE >> 8); final byte code1 = (byte) (SRV_FELICA_LITE_READWRITE & 0xff); return readWithoutEncryption(addr, code0, code1); } public WriteResponse writeWithoutEncryption(ServiceCode code, byte addr, byte[] buff) throws IOException { byte[] bytes = code.getBytes(); ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, (byte) addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(byte addr, byte[] buff) throws IOException { ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READWRITE >> 8), (byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01, (byte) 0x80, addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public MemoryConfigurationBlock getMemoryConfigBlock() throws IOException { ReadResponse r = readWithoutEncryption((byte) 0x88); return new MemoryConfigurationBlock(r.getBlockData()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (idm != null) { sb.append(idm.toString()); if (pmm != null) sb.append(pmm.toString()); } return sb.toString(); } public void connect() throws IOException { nfcTag.connect(); } public void close() throws IOException { nfcTag.close(); } public byte[] transceive(Command cmd) throws IOException { return transceive(cmd.getBytes()); } public byte[] transceive(byte... cmd) throws IOException { return nfcTag.transceive(cmd); } } // polling public static final byte CMD_POLLING = 0x00; public static final byte RSP_POLLING = 0x01; // request service public static final byte CMD_REQUEST_SERVICE = 0x02; public static final byte RSP_REQUEST_SERVICE = 0x03; // request RESPONSE public static final byte CMD_REQUEST_RESPONSE = 0x04; public static final byte RSP_REQUEST_RESPONSE = 0x05; // read without encryption public static final byte CMD_READ_WO_ENCRYPTION = 0x06; public static final byte RSP_READ_WO_ENCRYPTION = 0x07; // write without encryption public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08; public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09; // search service code public static final byte CMD_SEARCH_SERVICECODE = 0x0a; public static final byte RSP_SEARCH_SERVICECODE = 0x0b; // request system code public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c; public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d; // authentication 1 public static final byte CMD_AUTHENTICATION1 = 0x10; public static final byte RSP_AUTHENTICATION1 = 0x11; // authentication 2 public static final byte CMD_AUTHENTICATION2 = 0x12; public static final byte RSP_AUTHENTICATION2 = 0x13; // read public static final byte CMD_READ = 0x14; public static final byte RSP_READ = 0x15; // write public static final byte CMD_WRITE = 0x16; public static final byte RSP_WRITE = 0x17; public static final int SYS_ANY = 0xffff; public static final int SYS_FELICA_LITE = 0x88b4; public static final int SYS_COMMON = 0xfe00; public static final int SRV_FELICA_LITE_READONLY = 0x0b00; public static final int SRV_FELICA_LITE_READWRITE = 0x0900; public static final int STA1_NORMAL = 0x00; public static final int STA1_ERROR = 0xff; public static final int STA2_NORMAL = 0x00; public static final int STA2_ERROR_LENGTH = 0x01; public static final int STA2_ERROR_FLOWN = 0x02; public static final int STA2_ERROR_MEMORY = 0x70; public static final int STA2_ERROR_WRITELIMIT = 0x71; }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.tech; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import com.sinpo.xnfc.nfc.Util; import android.nfc.tech.IsoDep; public class Iso7816 { public static final byte[] EMPTY = { 0 }; protected byte[] data; protected Iso7816() { data = Iso7816.EMPTY; } protected Iso7816(byte[] bytes) { data = (bytes == null) ? Iso7816.EMPTY : bytes; } public boolean match(byte[] bytes) { return match(bytes, 0); } public boolean match(byte[] bytes, int start) { final byte[] data = this.data; if (data.length <= bytes.length - start) { for (final byte v : data) { if (v != bytes[start++]) return false; } } else { return false; } return true; } public boolean match(byte tag) { return (data.length == 1 && data[0] == tag); } public boolean match(short tag) { final byte[] data = this.data; if (data.length == 2) { final byte d0 = (byte) (0x000000FF & (tag >> 8)); final byte d1 = (byte) (0x000000FF & tag); return (data[0] == d0 && data[1] == d1); } return (tag >= 0 && tag <= 255) ? match((byte) tag) : false; } public int size() { return data.length; } public byte[] getBytes() { return data; } public byte[] getBytes(int start, int count) { return Arrays.copyOfRange(data, start, start + count); } public int toInt() { return Util.toInt(getBytes()); } public int toIntR() { return Util.toIntR(getBytes()); } @Override public String toString() { return Util.toHexString(data, 0, data.length); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !(obj instanceof Iso7816)) return false; return match(((Iso7816) obj).getBytes(), 0); } public final static class ID extends Iso7816 { public ID(byte... bytes) { super(bytes); } } public static class Response extends Iso7816 { public static final byte[] EMPTY = {}; public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN public Response(byte[] bytes) { super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes); } public byte getSw1() { return data[data.length - 2]; } public byte getSw2() { return data[data.length - 1]; } public String getSw12String() { int sw1 = getSw1() & 0x000000FF; int sw2 = getSw2() & 0x000000FF; return String.format("0x%02X%02X", sw1, sw2); } public short getSw12() { final byte[] d = this.data; int n = d.length; return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1])); } public boolean isOkey() { return equalsSw12(SW_NO_ERROR); } public boolean equalsSw12(short val) { return getSw12() == val; } public int size() { return data.length - 2; } public byte[] getBytes() { return isOkey() ? Arrays.copyOfRange(data, 0, size()) : Response.EMPTY; } } public final static class MifareDResponse extends Response { public MifareDResponse(byte[] bytes) { super(bytes); } } public final static class BerT extends Iso7816 { // tag template public static final byte TMPL_FCP = 0x62; // File Control Parameters public static final byte TMPL_FMD = 0x64; // File Management Data public static final byte TMPL_FCI = 0x6F; // FCP and FMD // proprietary information public final static BerT CLASS_PRI = new BerT((byte) 0xA5); // short EF identifier public final static BerT CLASS_SFI = new BerT((byte) 0x88); // dedicated file name public final static BerT CLASS_DFN = new BerT((byte) 0x84); // application data object public final static BerT CLASS_ADO = new BerT((byte) 0x61); // application id public final static BerT CLASS_AID = new BerT((byte) 0x4F); // proprietary information public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x1F) == 0x1F) { while ((bytes[start + len] & 0x80) == 0x80) ++len; ++len; } return len; } public static BerT read(byte[] bytes, int start) { return new BerT(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerT(byte tag) { this(new byte[] { tag }); } public BerT(short tag) { this(new byte[] { (byte) (0x000000FF & (tag >> 8)), (byte) (0x000000FF & tag) }); } public BerT(byte[] bytes) { super(bytes); } public boolean hasChild() { return ((data[0] & 0x20) == 0x20); } public short toShort() { if (size() <= 2) { return (short) Util.toInt(data); } return 0; } } public final static class BerL extends Iso7816 { private final int val; public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x80) == 0x80) { len += bytes[start] & 0x07; } return len; } public static int calc(byte[] bytes, int start) { if ((bytes[start] & 0x80) == 0x80) { int v = 0; int e = start + bytes[start] & 0x07; while (++start <= e) { v <<= 8; v |= bytes[start] & 0xFF; } return v; } return bytes[start]; } public static BerL read(byte[] bytes, int start) { return new BerL(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerL(byte[] bytes) { super(bytes); val = calc(bytes, 0); } public BerL(int len) { super(null); val = len; } public int toInt() { return val; } } public final static class BerV extends Iso7816 { public static BerV read(byte[] bytes, int start, int len) { return new BerV(Arrays.copyOfRange(bytes, start, start + len)); } public BerV(byte[] bytes) { super(bytes); } } public final static class BerTLV extends Iso7816 { public static int test(byte[] bytes, int start) { final int lt = BerT.test(bytes, start); final int ll = BerL.test(bytes, start + lt); final int lv = BerL.calc(bytes, start + lt); return lt + ll + lv; } public static byte[] getValue(BerTLV tlv) { if (tlv == null || tlv.length() == 0) return null; return tlv.v.getBytes(); } public static BerTLV read(Iso7816 obj) { return read(obj.getBytes(), 0); } public static BerTLV read(byte[] bytes, int start) { int s = start; final BerT t = BerT.read(bytes, s); s += t.size(); final BerL l = BerL.read(bytes, s); s += l.size(); final BerV v = BerV.read(bytes, s, l.toInt()); s += v.size(); final BerTLV tlv = new BerTLV(t, l, v); tlv.data = Arrays.copyOfRange(bytes, start, s); return tlv; } public static void extractChildren(ArrayList<BerTLV> out, Iso7816 obj) { extractChildren(out, obj.getBytes()); } public static void extractChildren(ArrayList<BerTLV> out, byte[] data) { int start = 0; int end = data.length - 3; while (start <= end) { final BerTLV tlv = read(data, start); out.add(tlv); start += tlv.size(); } } public static void extractPrimitives(BerHouse out, Iso7816 obj) { extractPrimitives(out.tlvs, obj.getBytes()); } public static void extractPrimitives(ArrayList<BerTLV> out, Iso7816 obj) { extractPrimitives(out, obj.getBytes()); } public static void extractPrimitives(BerHouse out, byte[] data) { extractPrimitives(out.tlvs, data); } public static void extractPrimitives(ArrayList<BerTLV> out, byte[] data) { int start = 0; int end = data.length - 3; while (start <= end) { final BerTLV tlv = read(data, start); if (tlv.t.hasChild()) extractPrimitives(out, tlv.v.getBytes()); else out.add(tlv); start += tlv.size(); } } public static ArrayList<BerTLV> extractOptionList(byte[] data) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); int start = 0; int end = data.length; while (start < end) { final BerT t = BerT.read(data, start); start += t.size(); if (start < end) { BerL l = BerL.read(data, start); start += l.size(); if (start <= end) ret.add(new BerTLV(t, l, null)); } } return ret; } public final BerT t; public final BerL l; public final BerV v; public BerTLV(BerT t, BerL l, BerV v) { this.t = t; this.l = l; this.v = v; } public int length() { return l.toInt(); } } public final static class BerHouse { final ArrayList<BerTLV> tlvs = new ArrayList<BerTLV>(); public int count() { return tlvs.size(); } public void add(short t, Response v) { tlvs.add(new BerTLV(new BerT(t), new BerL(v.size()), new BerV(v .getBytes()))); } public void add(short t, byte[] v) { tlvs.add(new BerTLV(new BerT(t), new BerL(v.length), new BerV(v))); } public void add(BerT t, byte[] v) { tlvs.add(new BerTLV(t, new BerL(v.length), new BerV(v))); } public void add(BerTLV tlv) { tlvs.add(tlv); } public BerTLV get(int index) { return tlvs.get(index); } public BerTLV findFirst(byte tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(byte... tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(short tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(BerT tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag.getBytes())) return tlv; return null; } public ArrayList<BerTLV> findAll(byte tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(byte... tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(short tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(BerT tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag.getBytes())) ret.add(tlv); return ret; } public String toString() { final StringBuilder ret = new StringBuilder(); for (BerTLV t : tlvs) { ret.append(t.t.toString()).append(' '); ret.append(t.l.toInt()).append(' '); ret.append(t.v.toString()).append('\n'); } return ret.toString(); } } public final static class StdTag { private final IsoDep nfcTag; private ID id; public StdTag(IsoDep tag) { nfcTag = tag; id = new ID(tag.getTag().getId()); } public ID getID() { return id; } public Response getBalance(boolean isEP) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x5C, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x04, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi, int index) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) index, // P1 Parameter 1 (byte) ((sfi << 3) | 0x04), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) ((sfi << 3) | 0x05), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readBinary(int sfi) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB0, // INS Instruction (byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(int sfi) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (sfi & 0x1F), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response getData(short tag) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) ((tag >> 8) & 0xFF), (byte) (tag & 0xFF), (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(short tag) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) ((tag >> 8) & 0xFF), // P1 Parameter 1 (byte) (tag & 0x1F), // P2 Parameter 2 (byte) 0x00, // Lc (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response selectByID(byte... id) throws IOException { ByteBuffer buff = ByteBuffer.allocate(id.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) id.length) // Lc .put(id).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response selectByName(byte... name) throws IOException { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x04) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response getProcessingOptions(byte... pdol) throws IOException { ByteBuffer buff = ByteBuffer.allocate(pdol.length + 6); buff.put((byte) 0x80) // CLA Class .put((byte) 0xA8) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) pdol.length) // Lc .put(pdol).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public void connect() throws IOException { nfcTag.connect(); } public void close() throws IOException { nfcTag.close(); } public byte[] transceive(final byte[] cmd) throws IOException { try { byte[] rsp = null; byte c[] = cmd; do { byte[] r = nfcTag.transceive(c); if (r == null) break; int N = r.length - 2; if (N < 0) { rsp = r; break; } if (r[N] == CH_STA_LE) { c[c.length - 1] = r[N + 1]; continue; } if (rsp == null) { rsp = r; } else { int n = rsp.length; N += n; rsp = Arrays.copyOf(rsp, N); n -= 2; for (byte i : r) rsp[n++] = i; } if (r[N] != CH_STA_MORE) break; byte s = r[N + 1]; if (s != 0) { c = CMD_GETRESPONSE.clone(); } else { rsp[rsp.length - 1] = CH_STA_OK; break; } } while (true); return rsp; } catch (Exception e) { return Response.ERROR; } } private static final byte CH_STA_OK = (byte) 0x90; private static final byte CH_STA_MORE = (byte) 0x61; private static final byte CH_STA_LE = (byte) 0x6C; private static final byte CMD_GETRESPONSE[] = { 0, (byte) 0xC0, 0, 0, 0, }; } public static final short SW_NO_ERROR = (short) 0x9000; public static final short SW_DESFIRE_NO_ERROR = (short) 0x9100; public static final short SW_BYTES_REMAINING_00 = 0x6100; public static final short SW_WRONG_LENGTH = 0x6700; public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982; public static final short SW_FILE_INVALID = 0x6983; public static final short SW_DATA_INVALID = 0x6984; public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985; public static final short SW_COMMAND_NOT_ALLOWED = 0x6986; public static final short SW_APPLET_SELECT_FAILED = 0x6999; public static final short SW_WRONG_DATA = 0x6A80; public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81; public static final short SW_FILE_NOT_FOUND = 0x6A82; public static final short SW_RECORD_NOT_FOUND = 0x6A83; public static final short SW_INCORRECT_P1P2 = 0x6A86; public static final short SW_WRONG_P1P2 = 0x6B00; public static final short SW_CORRECT_LENGTH_00 = 0x6C00; public static final short SW_INS_NOT_SUPPORTED = 0x6D00; public static final short SW_CLA_NOT_SUPPORTED = 0x6E00; public static final short SW_UNKNOWN = 0x6F00; public static final short SW_FILE_FULL = 0x6A84; }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc; import static android.nfc.NfcAdapter.EXTRA_TAG; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import com.sinpo.xnfc.nfc.reader.ReaderListener; import com.sinpo.xnfc.nfc.reader.ReaderManager; public final class NfcManager { private final Activity activity; private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private static String[][] TECHLISTS; private static IntentFilter[] TAGFILTERS; private int status; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() }, { NfcF.class.getName() }, }; TAGFILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } public NfcManager(Activity activity) { this.activity = activity; nfcAdapter = NfcAdapter.getDefaultAdapter(activity); pendingIntent = PendingIntent.getActivity(activity, 0, new Intent( activity, activity.getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); setupBeam(true); status = getStatus(); } public void onPause() { setupOldFashionBeam(false); if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(activity); } public void onResume() { setupOldFashionBeam(true); if (nfcAdapter != null) nfcAdapter.enableForegroundDispatch(activity, pendingIntent, TAGFILTERS, TECHLISTS); } public boolean updateStatus() { int sta = getStatus(); if (sta != status) { status = sta; return true; } return false; } public boolean readCard(Intent intent, ReaderListener listener) { final Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG); if (tag != null) { ReaderManager.readCard(tag, listener); return true; } return false; } private int getStatus() { return (nfcAdapter == null) ? -1 : nfcAdapter.isEnabled() ? 1 : 0; } @SuppressLint("NewApi") private void setupBeam(boolean enable) { final int api = android.os.Build.VERSION.SDK_INT; if (nfcAdapter != null && api >= ICE_CREAM_SANDWICH) { if (enable) nfcAdapter.setNdefPushMessage(createNdefMessage(), activity); } } @SuppressWarnings("deprecation") private void setupOldFashionBeam(boolean enable) { final int api = android.os.Build.VERSION.SDK_INT; if (nfcAdapter != null && api >= GINGERBREAD_MR1 && api < ICE_CREAM_SANDWICH) { if (enable) nfcAdapter.enableForegroundNdefPush(activity, createNdefMessage()); else nfcAdapter.disableForegroundNdefPush(activity); } } NdefMessage createNdefMessage() { String uri = "3play.google.com/store/apps/details?id=com.sinpo.xnfc"; byte[] data = uri.getBytes(); // about this '3'.. see NdefRecord.createUri which need api level 14 data[0] = 3; NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, null, data); return new NdefMessage(new NdefRecord[] { record }); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc; public final class Util { private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private Util() { } public static byte[] toBytes(int a) { return new byte[] { (byte) (0x000000ff & (a >>> 24)), (byte) (0x000000ff & (a >>> 16)), (byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) }; } public static boolean testBit(byte data, int bit) { final byte mask = (byte) ((1 << bit) & 0x000000FF); return (data & mask) == mask; } public static int toInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toIntR(byte[] b, int s, int n) { int ret = 0; for (int i = s; (i >= 0 && n > 0); --i, --n) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toInt(byte... b) { int ret = 0; for (final byte a : b) { ret <<= 8; ret |= a & 0xFF; } return ret; } public static int toIntR(byte... b) { return toIntR(b, b.length - 1, b.length); } public static String toHexString(byte... d) { return (d == null || d.length == 0) ? "" : toHexString(d, 0, d.length); } public static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String toHexStringR(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; int x = 0; for (int i = s + n - 1; i >= s; --i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String ensureString(String str) { return str == null ? "" : str; } public static String toStringR(int n) { final StringBuilder ret = new StringBuilder(16).append('0'); long N = 0xFFFFFFFFL & n; while (N != 0) { ret.append((int) (N % 100)); N /= 100; } return ret.toString(); } public static int parseInt(String txt, int radix, int def) { int ret; try { ret = Integer.valueOf(txt, radix); } catch (Exception e) { ret = def; } return ret; } public static int BCDtoInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { int h = (b[i] >> 4) & 0x0F; int l = b[i] & 0x0F; if (h > 9 || l > 9) return -1; ret = ret * 100 + h * 10 + l; } return ret; } public static int BCDtoInt(byte... b) { return BCDtoInt(b, 0, b.length); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; public class Card extends Application { public static final Card EMPTY = new Card(); private final ArrayList<Application> applications; public Card() { applications = new ArrayList<Application>(2); } public Exception getReadingException() { return (Exception) getProperty(SPEC.PROP.EXCEPTION); } public boolean hasReadingException() { return hasProperty(SPEC.PROP.EXCEPTION); } public final boolean isUnknownCard() { return applicationCount() == 0; } public final int applicationCount() { return applications.size(); } public final Application getApplication(int index) { return applications.get(index); } public final void addApplication(Application app) { if (app != null) applications.add(app); } public String toHtml() { return HtmlFormatter.formatCardInfo(this); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import com.sinpo.xnfc.SPEC; import android.util.SparseArray; public class Application { private final SparseArray<Object> properties = new SparseArray<Object>(); public final void setProperty(SPEC.PROP prop, Object value) { properties.put(prop.ordinal(), value); } public final Object getProperty(SPEC.PROP prop) { return properties.get(prop.ordinal()); } public final boolean hasProperty(SPEC.PROP prop) { return getProperty(prop) != null; } public final String getStringProperty(SPEC.PROP prop) { final Object v = getProperty(prop); return (v != null) ? v.toString() : ""; } public final float getFloatProperty(SPEC.PROP prop) { final Object v = getProperty(prop); if (v == null) return Float.NaN; if (v instanceof Float) return ((Float) v).floatValue(); return Float.parseFloat(v.toString()); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import com.sinpo.xnfc.SPEC; public final class HtmlFormatter { static String formatCardInfo(Card card) { final StringBuilder ret = new StringBuilder(); startTag(ret, SPEC.TAG_BLK); final int N = card.applicationCount(); for (int i = 0; i < N; ++i) { if (i > 0) { newline(ret); newline(ret); } formatApplicationInfo(ret, card.getApplication(i)); } endTag(ret, SPEC.TAG_BLK); return ret.toString(); } private static void startTag(StringBuilder out, String tag) { out.append('<').append(tag).append('>'); } private static void endTag(StringBuilder out, String tag) { out.append('<').append('/').append(tag).append('>'); } private static void newline(StringBuilder out) { out.append("<br />"); } private static void spliter(StringBuilder out) { out.append("\n<").append(SPEC.TAG_SP).append(" />\n"); } private static boolean formatProperty(StringBuilder out, String tag, Object value) { if (value == null) return false; startTag(out, tag); out.append(value.toString()); endTag(out, tag); return true; } private static boolean formatProperty(StringBuilder out, String tag, Object prop, String value) { if (value == null || value.isEmpty()) return false; startTag(out, tag); out.append(prop.toString()); endTag(out, tag); startTag(out, SPEC.TAG_TEXT); out.append(value); endTag(out, SPEC.TAG_TEXT); return true; } private static boolean formatApplicationInfo(StringBuilder out, Application app) { if (!formatProperty(out, SPEC.TAG_H1, app.getProperty(SPEC.PROP.ID))) return false; newline(out); spliter(out); newline(out); { SPEC.PROP prop = SPEC.PROP.SERIAL; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.PARAM; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.VERSION; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.DATE; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.COUNT; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.TLIMIT; Float balance = (Float) app.getProperty(prop); if (balance != null && !balance.isNaN()) { String cur = app.getProperty(SPEC.PROP.CURRENCY).toString(); String val = String.format("%.2f %s", balance, cur); if (formatProperty(out, SPEC.TAG_LAB, prop, val)) newline(out); } } { SPEC.PROP prop = SPEC.PROP.DLIMIT; Float balance = (Float) app.getProperty(prop); if (balance != null && !balance.isNaN()) { String cur = app.getProperty(SPEC.PROP.CURRENCY).toString(); String val = String.format("%.2f %s", balance, cur); if (formatProperty(out, SPEC.TAG_LAB, prop, val)) newline(out); } } { SPEC.PROP prop = SPEC.PROP.ECASH; Float balance = (Float) app.getProperty(prop); if (balance != null) { formatProperty(out, SPEC.TAG_LAB, prop); if (balance.isNaN()) { out.append(SPEC.PROP.ACCESS); } else { formatProperty(out, SPEC.TAG_H2, String.format("%.2f ", balance)); formatProperty(out, SPEC.TAG_LAB, app.getProperty(SPEC.PROP.CURRENCY).toString()); } newline(out); } } { SPEC.PROP prop = SPEC.PROP.BALANCE; Float balance = (Float) app.getProperty(prop); if (balance != null) { formatProperty(out, SPEC.TAG_LAB, prop); if (balance.isNaN()) { out.append(SPEC.PROP.ACCESS); } else { formatProperty(out, SPEC.TAG_H2, String.format("%.2f ", balance)); formatProperty(out, SPEC.TAG_LAB, app.getProperty(SPEC.PROP.CURRENCY).toString()); } newline(out); } } { SPEC.PROP prop = SPEC.PROP.TRANSLOG; String[] logs = (String[]) app.getProperty(prop); if (logs != null && logs.length > 0) { spliter(out); newline(out); startTag(out, SPEC.TAG_PARAG); formatProperty(out, SPEC.TAG_LAB, prop); newline(out); endTag(out, SPEC.TAG_PARAG); for (String log : logs) { formatProperty(out, SPEC.TAG_H3, log); newline(out); } newline(out); } } return true; } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import android.os.AsyncTask; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.reader.pboc.StandardPboc; public final class ReaderManager extends AsyncTask<Tag, SPEC.EVENT, Card> { public static void readCard(Tag tag, ReaderListener listener) { new ReaderManager(listener).execute(tag); } private ReaderListener realListener; private ReaderManager(ReaderListener listener) { realListener = listener; } @Override protected Card doInBackground(Tag... detectedTag) { return readCard(detectedTag[0]); } @Override protected void onProgressUpdate(SPEC.EVENT... events) { if (realListener != null) realListener.onReadEvent(events[0]); } @Override protected void onPostExecute(Card card) { if (realListener != null) realListener.onReadEvent(SPEC.EVENT.FINISHED, card); } private Card readCard(Tag tag) { final Card card = new Card(); try { publishProgress(SPEC.EVENT.READING); card.setProperty(SPEC.PROP.ID, Util.toHexString(tag.getId())); final IsoDep isodep = IsoDep.get(tag); if (isodep != null) StandardPboc.readCard(isodep, card); final NfcF nfcf = NfcF.get(tag); if (nfcf != null) FelicaReader.readCard(nfcf, card); publishProgress(SPEC.EVENT.IDLE); } catch (Exception e) { card.setProperty(SPEC.PROP.EXCEPTION, e); publishProgress(SPEC.EVENT.ERROR); } return card; } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import com.sinpo.xnfc.SPEC; public interface ReaderListener { void onReadEvent(SPEC.EVENT event, Object... obj); }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; import android.nfc.tech.IsoDep; @SuppressWarnings("unchecked") public abstract class StandardPboc { private static Class<?>[][] readers = { { BeijingMunicipal.class, WuhanTong.class, ShenzhenTong.class, CityUnion.class, }, { Quickpass.class, } }; public static void readCard(IsoDep tech, Card card) throws InstantiationException, IllegalAccessException, IOException { final Iso7816.StdTag tag = new Iso7816.StdTag(tech); tag.connect(); for (final Class<?> g[] : readers) { HINT hint = HINT.RESETANDGONEXT; for (final Class<?> r : g) { final StandardPboc reader = (StandardPboc) r.newInstance(); switch (hint) { case RESETANDGONEXT: if (!reader.resetTag(tag)) continue; case GONEXT: hint = reader.readCard(tag, card); break; default: break; } if (hint == HINT.STOP) break; } } tag.close(); } protected boolean resetTag(Iso7816.StdTag tag) throws IOException { return tag.selectByID(DFI_MF).isOkey() || tag.selectByName(DFN_PSE).isOkey(); } protected enum HINT { STOP, GONEXT, RESETANDGONEXT, } protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 }; protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 }; protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] DFN_PXX = { (byte) 'P' }; protected final static int SFI_EXTRA = 21; protected static int MAX_LOG = 10; protected static int SFI_LOG = 24; protected final static byte TRANS_CSU = 6; protected final static byte TRANS_CSU_CPX = 9; protected abstract SPEC.APP getApplicationId(); protected byte[] getMainApplicationId() { return DFI_EP; } protected SPEC.CUR getCurrency() { return SPEC.CUR.CNY; } protected boolean selectMainApplication(Iso7816.StdTag tag) throws IOException { final byte[] aid = getMainApplicationId(); return ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid)) .isOkey(); } protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!selectMainApplication(tag)) return HINT.GONEXT; Iso7816.Response INFO, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo21(app, INFO, 4, true); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } protected void parseBalance(Application app, Iso7816.Response... data) { int amount = 0; for (Iso7816.Response rsp : data) { if (rsp.isOkey() && rsp.size() >= 4) { int n = Util.toInt(rsp.getBytes(), 0, 4); if (n > 1000000 || n < -1000000) n -= 0x80000000; amount += n; } } app.setProperty(SPEC.PROP.BALANCE, (amount / 100.0f)); } protected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { return; } final byte[] d = data.getBytes(); if (dec < 1 || dec > 10) { app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10)); } else { final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d, 20 - dec, dec); app.setProperty(SPEC.PROP.SERIAL, String.format("%d", 0xFFFFFFFFL & sn)); } if (d[9] != 0) app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27])); } protected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) { if (!r.isOkey()) return false; final byte[] raw = r.getBytes(); final int N = raw.length - 23; if (N < 0) return false; for (int s = 0, e = 0; s <= N; s = e) { l.add(Arrays.copyOfRange(raw, s, (e = s + 23))); } return true; } protected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi) throws IOException { final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG); final Iso7816.Response rsp = tag.readRecord(sfi); if (rsp.isOkey()) { addLog24(rsp, ret); } else { for (int i = 1; i <= MAX_LOG; ++i) { if (!addLog24(tag.readRecord(sfi, i), ret)) break; } } return ret; } protected void parseLog24(Application app, ArrayList<byte[]>... logs) { final ArrayList<String> ret = new ArrayList<String>(MAX_LOG); for (final ArrayList<byte[]> log : logs) { if (log == null) continue; for (final byte[] v : log) { final int money = Util.toInt(v, 5, 4); if (money > 0) { final char s = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-' : '+'; final int over = Util.toInt(v, 2, 3); final String slog; if (over > 0) { slog = String .format("%02X%02X.%02X.%02X %02X:%02X %c%.2f [o:%.2f] [%02X%02X%02X%02X%02X%02X]", v[16], v[17], v[18], v[19], v[20], v[21], s, (money / 100.0f), (over / 100.0f), v[10], v[11], v[12], v[13], v[14], v[15]); } else { slog = String .format("%02X%02X.%02X.%02X %02X:%02X %C%.2f [%02X%02X%02X%02X%02X%02X]", v[16], v[17], v[18], v[19], v[20], v[21], s, (money / 100.0f), v[10], v[11], v[12], v[13], v[14], v[15]); } ret.add(slog); } } } if (!ret.isEmpty()) app.setProperty(SPEC.PROP.TRANSLOG, ret.toArray(new String[ret.size()])); } protected Application createApplication() { return new Application(); } protected void configApplication(Application app) { app.setProperty(SPEC.PROP.ID, getApplicationId()); app.setProperty(SPEC.PROP.CURRENCY, getCurrency()); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; final class WuhanTong extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.WUHANTONG; } @Override protected byte[] getMainApplicationId() { return new byte[] { (byte) 0x41, (byte) 0x50, (byte) 0x31, (byte) 0x2E, (byte) 0x57, (byte) 0x48, (byte) 0x43, (byte) 0x54, (byte) 0x43, }; } @SuppressWarnings("unchecked") @Override protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { Iso7816.Response INFO, SERL, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (5, 10) /*--------------------------------------------------------------*/ if (!(SERL = tag.readBinary(SFI_SERL)).isOkey()) return HINT.GONEXT; if (!(INFO = tag.readBinary(SFI_INFO)).isOkey()) return HINT.GONEXT; BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!tag.selectByName(getMainApplicationId()).isOkey()) return HINT.RESETANDGONEXT; /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ if (!BALANCE.isOkey()) BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo5(app, SERL, INFO); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } private final static int SFI_INFO = 5; private final static int SFI_SERL = 10; private void parseInfo5(Application app, Iso7816.Response sn, Iso7816.Response info) { if (sn.size() < 27 || info.size() < 27) { return; } final byte[] d = info.getBytes(); app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(sn.getBytes(), 0, 5)); app.setProperty(SPEC.PROP.VERSION, String.format("%02d", d[24])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[16], d[17], d[18], d[19])); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import com.sinpo.xnfc.SPEC; final class ShenzhenTong extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.SHENZHENTONG; } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.tech.Iso7816; import android.annotation.SuppressLint; final class CityUnion extends StandardPboc { private SPEC.APP applicationId = SPEC.APP.UNKNOWN; @Override protected SPEC.APP getApplicationId() { return applicationId; } @Override protected byte[] getMainApplicationId() { return new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x86, (byte) 0x98, (byte) 0x07, (byte) 0x01, }; } @SuppressLint("DefaultLocale") @Override protected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { return; } final byte[] d = data.getBytes(); if (d[2] == 0x20 && d[3] == 0x00) { applicationId = SPEC.APP.SHANGHAIGJ; bigEndian = true; } else { applicationId = SPEC.APP.CHANGANTONG; bigEndian = false; } if (dec < 1 || dec > 10) { app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10)); } else { final int sn = Util.toInt(d, 20 - dec, dec); final String ss = bigEndian ? Util.toStringR(sn) : String.format( "%d", 0xFFFFFFFFL & sn); app.setProperty(SPEC.PROP.SERIAL, ss); } if (d[9] != 0) app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27])); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; import com.sinpo.xnfc.nfc.tech.Iso7816.BerHouse; import com.sinpo.xnfc.nfc.tech.Iso7816.BerTLV; public class Quickpass extends StandardPboc { protected final static byte[] DFN_PPSE = { (byte) '2', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] AID_DEBIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x01 }; protected final static byte[] AID_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x02 }; protected final static byte[] AID_QUASI_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x03 }; public final static short MARK_LOG = (short) 0xDFFF; protected final static short[] TAG_GLOBAL = { (short) 0x9F79 /* 电子现金余额 */, (short) 0x9F78 /* 电子现金单笔上限 */, (short) 0x9F77 /* 电子现金余额上限 */, (short) 0x9F13 /* 联机ATC */, (short) 0x9F36 /* ATC */, (short) 0x9F51 /* 货币代码 */, (short) 0x9F4F /* 日志文件格式 */, (short) 0x9F4D /* 日志文件ID */, (short) 0x5A /* 帐号 */, (short) 0x5F24 /* 失效日期 */, (short) 0x5F25 /* 生效日期 */, }; @Override protected SPEC.APP getApplicationId() { return SPEC.APP.QUICKPASS; } @Override protected boolean resetTag(Iso7816.StdTag tag) throws IOException { Iso7816.Response rsp = tag.selectByName(DFN_PPSE); if (!rsp.isOkey()) return false; BerTLV.extractPrimitives(topTLVs, rsp); return true; } protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { final ArrayList<Iso7816.ID> aids = getApplicationIds(tag); for (Iso7816.ID aid : aids) { /*--------------------------------------------------------------*/ // select application /*--------------------------------------------------------------*/ Iso7816.Response rsp = tag.selectByName(aid.getBytes()); if (!rsp.isOkey()) continue; final BerHouse subTLVs = new BerHouse(); /*--------------------------------------------------------------*/ // collect info /*--------------------------------------------------------------*/ BerTLV.extractPrimitives(subTLVs, rsp); collectTLVFromGlobalTags(tag, subTLVs); /*--------------------------------------------------------------*/ // parse PDOL and get processing options // 这是正规途径,但是每次GPO都会使ATC加1,达到65535卡片就锁定了 /*--------------------------------------------------------------*/ // rsp = tag.getProcessingOptions(buildPDOL(subTLVs)); // if (rsp.isOkey()) // BerTLV.extractPrimitives(subTLVs, rsp); /*--------------------------------------------------------------*/ // 遍历目录下31个文件,山寨途径,微暴力,不知会对卡片折寿多少 // 相对于GPO不停的增加ATC,这是一种折中 // (遍历过程一般不会超过15个文件就会结束) /*--------------------------------------------------------------*/ collectTLVFromRecords(tag, subTLVs); // String dump = subTLVs.toString(); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseInfo(app, subTLVs); parseLogs(app, subTLVs); card.addApplication(app); } return card.isUnknownCard() ? HINT.RESETANDGONEXT : HINT.STOP; } private static void parseInfo(Application app, BerHouse tlvs) { Object prop = parseString(tlvs, (short) 0x5A); if (prop != null) app.setProperty(SPEC.PROP.SERIAL, prop); prop = parseApplicationName(tlvs, (String) prop); if (prop != null) app.setProperty(SPEC.PROP.ID, prop); prop = parseInteger(tlvs, (short) 0x9F08); if (prop != null) app.setProperty(SPEC.PROP.VERSION, prop); prop = parseInteger(tlvs, (short) 0x9F36); if (prop != null) app.setProperty(SPEC.PROP.COUNT, prop); prop = parseValidity(tlvs, (short) 0x5F25, (short) 0x5F24); if (prop != null) app.setProperty(SPEC.PROP.DATE, prop); prop = parseCurrency(tlvs, (short) 0x9F51); if (prop != null) app.setProperty(SPEC.PROP.CURRENCY, prop); prop = parseAmount(tlvs, (short) 0x9F77); if (prop != null) app.setProperty(SPEC.PROP.DLIMIT, prop); prop = parseAmount(tlvs, (short) 0x9F78); if (prop != null) app.setProperty(SPEC.PROP.TLIMIT, prop); prop = parseAmount(tlvs, (short) 0x9F79); if (prop != null) app.setProperty(SPEC.PROP.ECASH, prop); } private ArrayList<Iso7816.ID> getApplicationIds(Iso7816.StdTag tag) throws IOException { final ArrayList<Iso7816.ID> ret = new ArrayList<Iso7816.ID>(); // try to read DDF BerTLV sfi = topTLVs.findFirst(Iso7816.BerT.CLASS_SFI); if (sfi != null && sfi.length() == 1) { final int SFI = sfi.v.toInt(); Iso7816.Response r = tag.readRecord(SFI, 1); for (int p = 2; r.isOkey(); ++p) { BerTLV.extractPrimitives(topTLVs, r); r = tag.readRecord(SFI, p); } } // add extracted ArrayList<BerTLV> aids = topTLVs.findAll(Iso7816.BerT.CLASS_AID); if (aids != null) { for (BerTLV aid : aids) ret.add(new Iso7816.ID(aid.v.getBytes())); } // use default list if (ret.isEmpty()) { ret.add(new Iso7816.ID(AID_DEBIT)); ret.add(new Iso7816.ID(AID_CREDIT)); ret.add(new Iso7816.ID(AID_QUASI_CREDIT)); } return ret; } /** * private static void buildPDO(ByteBuffer out, int len, byte... val) { * final int n = Math.min((val != null) ? val.length : 0, len); * * int i = 0; while (i < n) out.put(val[i++]); * * while (i++ < len) out.put((byte) 0); } * * private static byte[] buildPDOL(Iso7816.BerHouse tlvs) { * * final ByteBuffer buff = ByteBuffer.allocate(64); * * buff.put((byte) 0x83).put((byte) 0x00); * * try { final byte[] pdol = tlvs.findFirst((short) 0x9F38).v.getBytes(); * * ArrayList<BerTLV> list = BerTLV.extractOptionList(pdol); for * (Iso7816.BerTLV tlv : list) { final int tag = tlv.t.toInt(); final int * len = tlv.l.toInt(); * * switch (tag) { case 0x9F66: // 终端交易属性 buildPDO(buff, len, (byte) 0x48); * break; case 0x9F02: // 授权金额 buildPDO(buff, len); break; case 0x9F03: // * 其它金额 buildPDO(buff, len); break; case 0x9F1A: // 终端国家代码 buildPDO(buff, * len, (byte) 0x01, (byte) 0x56); break; case 0x9F37: // 不可预知数 * buildPDO(buff, len); break; case 0x5F2A: // 交易货币代码 buildPDO(buff, len, * (byte) 0x01, (byte) 0x56); break; case 0x95: // 终端验证结果 buildPDO(buff, * len); break; case 0x9A: // 交易日期 buildPDO(buff, len); break; case 0x9C: // * 交易类型 buildPDO(buff, len); break; default: throw null; } } // 更新数据长度 * buff.put(1, (byte) (buff.position() - 2)); } catch (Exception e) { * buff.position(2); } * * return Arrays.copyOfRange(buff.array(), 0, buff.position()); } */ private static void collectTLVFromGlobalTags(Iso7816.StdTag tag, BerHouse tlvs) throws IOException { for (short t : TAG_GLOBAL) { Iso7816.Response r = tag.getData(t); if (r.isOkey()) tlvs.add(BerTLV.read(r)); } } private static void collectTLVFromRecords(Iso7816.StdTag tag, BerHouse tlvs) throws IOException { // info files for (int sfi = 1; sfi <= 10; ++sfi) { Iso7816.Response r = tag.readRecord(sfi, 1); for (int idx = 2; r.isOkey() && idx <= 10; ++idx) { BerTLV.extractPrimitives(tlvs, r); r = tag.readRecord(sfi, idx); } } // check if already get sfi of log file BerTLV logEntry = tlvs.findFirst((short) 0x9F4D); final int S, E; if (logEntry != null && logEntry.length() == 2) { S = E = logEntry.v.getBytes()[0] & 0x000000FF; } else { S = 11; E = 31; } // log files for (int sfi = S; sfi <= E; ++sfi) { Iso7816.Response r = tag.readRecord(sfi, 1); boolean findOne = r.isOkey(); for (int idx = 2; r.isOkey() && idx <= 10; ++idx) { tlvs.add(MARK_LOG, r); r = tag.readRecord(sfi, idx); } if (findOne) break; } } private static SPEC.APP parseApplicationName(BerHouse tlvs, String serial) { String f = parseString(tlvs, (short) 0x84); if (f != null) { if (f.endsWith("010101")) return SPEC.APP.DEBIT; if (f.endsWith("010102")) return SPEC.APP.CREDIT; if (f.endsWith("010103")) return SPEC.APP.QCREDIT; } return SPEC.APP.UNKNOWN; } private static SPEC.CUR parseCurrency(BerHouse tlvs, short tag) { return SPEC.CUR.CNY; } private static String parseValidity(BerHouse tlvs, short from, short to) { final byte[] f = BerTLV.getValue(tlvs.findFirst(from)); final byte[] t = BerTLV.getValue(tlvs.findFirst(to)); if (t == null || t.length != 3 || t[0] == 0 || t[0] == (byte) 0xFF) return null; if (f == null || f.length != 3 || f[0] == 0 || f[0] == (byte) 0xFF) return String.format("? - 20%02x.%02x.%02x", t[0], t[1], t[2]); return String.format("20%02x.%02x.%02x - 20%02x.%02x.%02x", f[0], f[1], f[2], t[0], t[1], t[2]); } private static String parseString(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.toHexString(v) : null; } private static Float parseAmount(BerHouse tlvs, short tag) { Integer v = parseIntegerBCD(tlvs, tag); return (v != null) ? v / 100.0f : null; } private static Integer parseInteger(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.toInt(v) : null; } private static Integer parseIntegerBCD(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.BCDtoInt(v) : null; } private static void parseLogs(Application app, BerHouse tlvs) { final byte[] rawTemp = BerTLV.getValue(tlvs.findFirst((short) 0x9F4F)); if (rawTemp == null) return; final ArrayList<BerTLV> temp = BerTLV.extractOptionList(rawTemp); if (temp == null || temp.isEmpty()) return; final ArrayList<BerTLV> logs = tlvs.findAll(MARK_LOG); final ArrayList<String> ret = new ArrayList<String>(logs.size()); for (BerTLV log : logs) { String l = parseLog(temp, log.v.getBytes()); if (l != null) ret.add(l); } if (!ret.isEmpty()) app.setProperty(SPEC.PROP.TRANSLOG, ret.toArray(new String[ret.size()])); } private static String parseLog(ArrayList<BerTLV> temp, byte[] data) { try { int date = -1, time = -1; int amount = 0, type = -1; int cursor = 0; for (BerTLV f : temp) { final int n = f.length(); switch (f.t.toInt()) { case 0x9A: // 交易日期 date = Util.BCDtoInt(data, cursor, n); break; case 0x9F21: // 交易时间 time = Util.BCDtoInt(data, cursor, n); break; case 0x9F02: // 授权金额 amount = Util.BCDtoInt(data, cursor, n); break; case 0x9C: // 交易类型 type = Util.BCDtoInt(data, cursor, n); break; case 0x9F03: // 其它金额 case 0x9F1A: // 终端国家代码 case 0x5F2A: // 交易货币代码 case 0x9F4E: // 商户名称 case 0x9F36: // 应用交易计数器(ATC) default: break; } cursor += n; } if (amount <= 0) return null; final char sign; switch (type) { case 0: // 刷卡消费 case 1: // 取现 case 8: // 转账 case 9: // 支付 case 20: // 退款 case 40: // 持卡人账户转账 sign = '-'; break; default: sign = '+'; break; } String sd = (date <= 0) ? "****.**.**" : String.format( "20%02d.%02d.%02d", (date / 10000) % 100, (date / 100) % 100, date % 100); String st = (time <= 0) ? "**:**" : String.format("%02d:%02d", (time / 10000) % 100, (time / 100) % 100); final StringBuilder ret = new StringBuilder(); ret.append(String.format("%s %s %c%.2f", sd, st, sign, amount / 100f)); return ret.toString(); } catch (Exception e) { return null; } } private final BerHouse topTLVs = new BerHouse(); }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; final class BeijingMunicipal extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.BEIJINGMUNICIPAL; } @SuppressWarnings("unchecked") @Override protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { Iso7816.Response INFO, CNT, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (4) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA_LOG); if (!INFO.isOkey()) return HINT.GONEXT; /*--------------------------------------------------------------*/ // read card operation file, binary (5) /*--------------------------------------------------------------*/ CNT = tag.readBinary(SFI_EXTRA_CNT); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!tag.selectByID(DFI_EP).isOkey()) return HINT.RESETANDGONEXT; BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo4(app, INFO, CNT); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } private final static int SFI_EXTRA_LOG = 4; private final static int SFI_EXTRA_CNT = 5; private void parseInfo4(Application app, Iso7816.Response info, Iso7816.Response cnt) { if (!info.isOkey() || info.size() < 32) { return; } final byte[] d = info.getBytes(); app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 0, 8)); app.setProperty(SPEC.PROP.VERSION, String.format("%02X.%02X%02X", d[8], d[9], d[10])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24], d[25], d[26], d[27], d[28], d[29], d[30], d[31])); if (cnt != null && cnt.isOkey() && cnt.size() > 4) { byte[] e = cnt.getBytes(); final int n = Util.toInt(e, 1, 4); if (e[0] == 0) app.setProperty(SPEC.PROP.COUNT, String.format("%d", n)); else app.setProperty(SPEC.PROP.COUNT, String.format("%d*", n)); } } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import java.io.IOException; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.FeliCa; import android.nfc.tech.NfcF; final class FelicaReader { static void readCard(NfcF tech, Card card) throws IOException { final FeliCa.Tag tag = new FeliCa.Tag(tech); tag.connect(); /* * FeliCa.SystemCode systems[] = tag.getSystemCodeList(); if (systems.length == 0) { systems = new FeliCa.SystemCode[] { new FeliCa.SystemCode( tag.getSystemCodeByte()) }; } for (final FeliCa.SystemCode sys : systems) card.addApplication(readApplication(tag, sys.toInt())); */ // better old card compatibility card.addApplication(readApplication(tag, SYS_OCTOPUS)); try { card.addApplication(readApplication(tag, SYS_SZT)); } catch (IOException e) { // for early version of OCTOPUS which will throw shit } tag.close(); } private static final int SYS_SZT = 0x8005; private static final int SYS_OCTOPUS = 0x8008; private static final int SRV_SZT = 0x0118; private static final int SRV_OCTOPUS = 0x0117; private static Application readApplication(FeliCa.Tag tag, int system) throws IOException { final FeliCa.ServiceCode scode; final Application app; if (system == SYS_OCTOPUS) { app = new Application(); app.setProperty(SPEC.PROP.ID, SPEC.APP.OCTOPUS); app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.HKD); scode = new FeliCa.ServiceCode(SRV_OCTOPUS); } else if (system == SYS_SZT) { app = new Application(); app.setProperty(SPEC.PROP.ID, SPEC.APP.SHENZHENTONG); app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.CNY); scode = new FeliCa.ServiceCode(SRV_SZT); } else { return null; } app.setProperty(SPEC.PROP.SERIAL, tag.getIDm().toString()); app.setProperty(SPEC.PROP.PARAM, tag.getPMm().toString()); tag.polling(system); final float[] data = new float[] { 0, 0, 0 }; int p = 0; for (byte i = 0; p < data.length; ++i) { final FeliCa.ReadResponse r = tag.readWithoutEncryption(scode, i); if (!r.isOkey()) break; data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f; } if (p != 0) app.setProperty(SPEC.PROP.BALANCE, parseBalance(data)); else app.setProperty(SPEC.PROP.BALANCE, Float.NaN); return app; } private static float parseBalance(float[] value) { float balance = 0f; for (float v : value) balance += v; return balance; } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import java.lang.Thread.UncaughtExceptionHandler; import com.sinpo.xnfc.R; import android.app.Application; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.widget.Toast; public final class ThisApplication extends Application implements UncaughtExceptionHandler { private static ThisApplication instance; @Override public void uncaughtException(Thread thread, Throwable ex) { System.exit(0); } @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(this); instance = this; } public static String name() { return getStringResource(R.string.app_name); } public static String version() { try { return instance.getPackageManager().getPackageInfo( instance.getPackageName(), 0).versionName; } catch (Exception e) { return "1.0"; } } public static void showMessage(int fmt, CharSequence... msgs) { String msg = String.format(getStringResource(fmt), msgs); Toast.makeText(instance, msg, Toast.LENGTH_LONG).show(); } public static Typeface getFontResource(int pathId) { String path = getStringResource(pathId); return Typeface.createFromAsset(instance.getAssets(), path); } public static int getDimensionResourcePixelSize(int resId) { return instance.getResources().getDimensionPixelSize(resId); } public static int getColorResource(int resId) { return instance.getResources().getColor(resId); } public static String getStringResource(int resId) { return instance.getString(resId); } public static Drawable getDrawableResource(int resId) { return instance.getResources().getDrawable(resId); } public static DisplayMetrics getDisplayMetrics() { return instance.getResources().getDisplayMetrics(); } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.app.Activity; import android.content.Intent; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class AboutPage { private static final String TAG = "ABOUTPAGE_ACTION"; public static CharSequence getContent(Activity activity) { String tip = ThisApplication .getStringResource(R.string.info_main_about); tip = tip.replace("<app />", ThisApplication.name()); tip = tip.replace("<version />", ThisApplication.version()); return new SpanFormatter(null).toSpanned(tip); } public static boolean isSendByMe(Intent intent) { return intent != null && TAG.equals(intent.getAction()); } static SpanFormatter.ActionHandler getActionHandler(Activity activity) { return new Handler(activity); } private static final class Handler implements SpanFormatter.ActionHandler { private final Activity activity; Handler(Activity activity) { this.activity = activity; } @Override public void handleAction(CharSequence name) { activity.setIntent(new Intent(TAG)); } } private AboutPage() { } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.animation.LayoutTransition; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.text.ClipboardManager; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class Toolbar { final ViewGroup toolbar; @SuppressLint("NewApi") public Toolbar(ViewGroup toolbar) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) toolbar.setLayoutTransition(new LayoutTransition()); this.toolbar = toolbar; } public void copyPageContent(TextView textArea) { final CharSequence text = textArea.getText(); if (text != null) { ((ClipboardManager) textArea.getContext().getSystemService( Context.CLIPBOARD_SERVICE)).setText(text); ThisApplication.showMessage(R.string.info_main_copied); } } public void show(int... buttons) { hide(); showDelayed(1000, buttons); } private void hide() { final int n = toolbar.getChildCount(); for (int i = 0; i < n; ++i) toolbar.getChildAt(i).setVisibility(View.GONE); } private void showDelayed(int delay, int... buttons) { toolbar.postDelayed(new Helper(buttons), delay); } private final class Helper implements Runnable { private final int[] buttons; Helper(int... buttons) { this.buttons = buttons; } @Override public void run() { final int n = toolbar.getChildCount(); for (int i = 0; i < n; ++i) { final View view = toolbar.getChildAt(i); int visibility = View.GONE; if (buttons != null) { final int id = view.getId(); for (int btn : buttons) { if (btn == id) { visibility = View.VISIBLE; break; } } } view.setVisibility(visibility); } } } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import java.lang.ref.WeakReference; import org.xml.sax.XMLReader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.Typeface; import android.text.Editable; import android.text.Html; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.LineHeightSpan; import android.text.style.MetricAffectingSpan; import android.text.style.ReplacementSpan; import android.util.DisplayMetrics; import android.view.View; import com.sinpo.xnfc.R; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.ThisApplication; public final class SpanFormatter implements Html.TagHandler { public interface ActionHandler { void handleAction(CharSequence name); } private final ActionHandler handler; public SpanFormatter(ActionHandler handler) { this.handler = handler; } public CharSequence toSpanned(String html) { return Html.fromHtml(html, null, this); } private static final class ActionSpan extends ClickableSpan { private final String action; private final ActionHandler handler; private final int color; ActionSpan(String action, ActionHandler handler, int color) { this.action = action; this.handler = handler; this.color = color; } @Override public void onClick(View widget) { if (handler != null) handler.handleAction(action); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(color); } } private static final class FontSpan extends MetricAffectingSpan { final int color; final float size; final Typeface face; final boolean bold; FontSpan(int color, float size, Typeface face) { this.color = color; this.size = size; if (face == Typeface.DEFAULT) { this.face = null; this.bold = false; } else if (face == Typeface.DEFAULT_BOLD) { this.face = null; this.bold = true; } else { this.face = face; this.bold = false; } } @Override public void updateDrawState(TextPaint ds) { ds.setTextSize(size); ds.setColor(color); if (face != null) { ds.setTypeface(face); } else if (bold) { Typeface tf = ds.getTypeface(); if (tf != null) { int style = tf.getStyle() | Typeface.BOLD; tf = Typeface.create(tf, style); ds.setTypeface(tf); style &= ~tf.getStyle(); if ((style & Typeface.BOLD) != 0) { ds.setFakeBoldText(true); } } } } @Override public void updateMeasureState(TextPaint p) { updateDrawState(p); } } private static final class ParagSpan implements LineHeightSpan { private final int linespaceDelta; ParagSpan(int linespaceDelta) { this.linespaceDelta = linespaceDelta; } @Override public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, FontMetricsInt fm) { fm.bottom += linespaceDelta; fm.descent += linespaceDelta; } } private static final class SplitterSpan extends ReplacementSpan { private final int color; private final int width; private final int height; SplitterSpan(int color, int width, int height) { this.color = color; this.width = width; this.height = height; } @Override public void updateDrawState(TextPaint ds) { ds.setTextSize(1); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { return 0; } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { canvas.save(); canvas.translate(x, (bottom + top) / 2 - height); final int c = paint.getColor(); paint.setColor(color); canvas.drawRect(x, 0, x + width, height, paint); paint.setColor(c); canvas.restore(); } } @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { final int len = output.length(); if (opening) { if (SPEC.TAG_TEXT.equals(tag)) { markFontSpan(output, len, R.color.tag_text, R.dimen.tag_text, Typeface.DEFAULT); } else if (SPEC.TAG_TIP.equals(tag)) { markParagSpan(output, len, R.dimen.tag_parag); markFontSpan(output, len, R.color.tag_tip, R.dimen.tag_tip, getTipFont()); } else if (SPEC.TAG_LAB.equals(tag)) { markFontSpan(output, len, R.color.tag_lab, R.dimen.tag_lab, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_ITEM.equals(tag)) { markFontSpan(output, len, R.color.tag_item, R.dimen.tag_item, Typeface.DEFAULT); } else if (SPEC.TAG_H1.equals(tag)) { markFontSpan(output, len, R.color.tag_h1, R.dimen.tag_h1, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_H2.equals(tag)) { markFontSpan(output, len, R.color.tag_h2, R.dimen.tag_h2, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_H3.equals(tag)) { markFontSpan(output, len, R.color.tag_h3, R.dimen.tag_h3, Typeface.SERIF); } else if (tag.startsWith(SPEC.TAG_ACT)) { markActionSpan(output, len, tag, R.color.tag_action); } else if (SPEC.TAG_PARAG.equals(tag)) { markParagSpan(output, len, R.dimen.tag_parag); } else if (SPEC.TAG_SP.equals(tag)) { markSpliterSpan(output, len, R.color.tag_action, R.dimen.tag_spliter); } } else { if (SPEC.TAG_TEXT.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_TIP.equals(tag)) { setSpan(output, len, FontSpan.class); setSpan(output, len, ParagSpan.class); } else if (SPEC.TAG_LAB.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_ITEM.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H1.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H2.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H3.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (tag.startsWith(SPEC.TAG_ACT)) { setSpan(output, len, ActionSpan.class); } else if (SPEC.TAG_PARAG.equals(tag)) { setSpan(output, len, ParagSpan.class); } } } private static void markSpliterSpan(Editable out, int pos, int colorId, int heightId) { DisplayMetrics dm = ThisApplication.getDisplayMetrics(); int color = ThisApplication.getColorResource(colorId); int height = ThisApplication.getDimensionResourcePixelSize(heightId); out.append("-------------------").setSpan( new SplitterSpan(color, dm.widthPixels, height), pos, out.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } private static void markFontSpan(Editable out, int pos, int colorId, int sizeId, Typeface face) { int color = ThisApplication.getColorResource(colorId); float size = ThisApplication.getDimensionResourcePixelSize(sizeId); FontSpan span = new FontSpan(color, size, face); out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK); } private static void markParagSpan(Editable out, int pos, int linespaceId) { int linespace = ThisApplication .getDimensionResourcePixelSize(linespaceId); ParagSpan span = new ParagSpan(linespace); out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK); } private void markActionSpan(Editable out, int pos, String tag, int colorId) { int color = ThisApplication.getColorResource(colorId); out.setSpan(new ActionSpan(tag, handler, color), pos, pos, Spannable.SPAN_MARK_MARK); } private static void setSpan(Editable out, int pos, Class<?> kind) { Object span = getLastMarkSpan(out, kind); out.setSpan(span, out.getSpanStart(span), pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } private static Object getLastMarkSpan(Spanned text, Class<?> kind) { Object[] objs = text.getSpans(0, text.length(), kind); if (objs.length == 0) { return null; } else { return objs[objs.length - 1]; } } private static Typeface getTipFont() { Typeface ret = null; WeakReference<Typeface> wr = TIPFONT; if (wr != null) ret = wr.get(); if (ret == null) { ret = ThisApplication.getFontResource(R.string.font_oem3); TIPFONT = new WeakReference<Typeface>(ret); } return ret; } private static WeakReference<Typeface> TIPFONT; }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; import com.sinpo.xnfc.SPEC.EVENT; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.reader.ReaderListener; public final class NfcPage implements ReaderListener { private static final String TAG = "READCARD_ACTION"; private static final String RET = "READCARD_RESULT"; private static final String STA = "READCARD_STATUS"; private final Activity activity; public NfcPage(Activity activity) { this.activity = activity; } public static boolean isSendByMe(Intent intent) { return intent != null && TAG.equals(intent.getAction()); } public static boolean isNormalInfo(Intent intent) { return intent != null && intent.hasExtra(STA); } public static CharSequence getContent(Activity activity, Intent intent) { String info = intent.getStringExtra(RET); if (info == null || info.length() == 0) return null; return new SpanFormatter(AboutPage.getActionHandler(activity)) .toSpanned(info); } @Override public void onReadEvent(EVENT event, Object... objs) { if (event == EVENT.IDLE) { showProgressBar(); } else if (event == EVENT.FINISHED) { hideProgressBar(); final Card card; if (objs != null && objs.length > 0) card = (Card) objs[0]; else card = null; activity.setIntent(buildResult(card)); } } private Intent buildResult(Card card) { final Intent ret = new Intent(TAG); if (card != null && !card.hasReadingException()) { if (card.isUnknownCard()) { ret.putExtra(RET, ThisApplication .getStringResource(R.string.info_nfc_unknown)); } else { ret.putExtra(RET, card.toHtml()); ret.putExtra(STA, 1); } } else { ret.putExtra(RET, ThisApplication.getStringResource(R.string.info_nfc_error)); } return ret; } private void showProgressBar() { Dialog d = progressBar; if (d == null) { d = new Dialog(activity, R.style.progressBar); d.setCancelable(false); d.setContentView(R.layout.progress); progressBar = d; } if (!d.isShowing()) d.show(); } private void hideProgressBar() { final Dialog d = progressBar; if (d != null && d.isShowing()) d.cancel(); } private Dialog progressBar; }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import static android.provider.Settings.ACTION_SETTINGS; import android.app.Activity; import android.content.Intent; import android.nfc.NfcAdapter; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class MainPage { public static CharSequence getContent(Activity activity) { final NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity); final int resid; if (nfc == null) resid = R.string.info_nfc_notsupport; else if (!nfc.isEnabled()) resid = R.string.info_nfc_disabled; else resid = R.string.info_nfc_nocard; String tip = ThisApplication.getStringResource(resid); return new SpanFormatter(new Handler(activity)).toSpanned(tip); } private static final class Handler implements SpanFormatter.ActionHandler { private final Activity activity; Handler(Activity activity) { this.activity = activity; } @Override public void handleAction(CharSequence name) { startNfcSettingsActivity(); } private void startNfcSettingsActivity() { activity.startActivityForResult(new Intent(ACTION_SETTINGS), 0); } } private MainPage() { } }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import com.sinpo.xnfc.R; public final class SPEC { public enum PAGE { DEFAULT, INFO, ABOUT, } public enum EVENT { IDLE, ERROR, READING, FINISHED, } public enum PROP { ID(R.string.spec_prop_id), SERIAL(R.string.spec_prop_serial), PARAM(R.string.spec_prop_param), VERSION(R.string.spec_prop_version), DATE(R.string.spec_prop_date), COUNT(R.string.spec_prop_count), CURRENCY(R.string.spec_prop_currency), TLIMIT(R.string.spec_prop_tlimit), DLIMIT(R.string.spec_prop_dlimit), ECASH(R.string.spec_prop_ecash), BALANCE(R.string.spec_prop_balance), TRANSLOG(R.string.spec_prop_translog), ACCESS(R.string.spec_prop_access), EXCEPTION(R.string.spec_prop_exception); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private PROP(int resId) { this.resId = resId; } } public enum APP { UNKNOWN(R.string.spec_app_unknown), SHENZHENTONG(R.string.spec_app_shenzhentong), QUICKPASS(R.string.spec_app_quickpass), OCTOPUS(R.string.spec_app_octopus_hk), BEIJINGMUNICIPAL(R.string.spec_app_beijing), WUHANTONG(R.string.spec_app_wuhantong), CHANGANTONG(R.string.spec_app_changantong), SHANGHAIGJ(R.string.spec_app_shanghai), DEBIT(R.string.spec_app_debit), CREDIT(R.string.spec_app_credit), QCREDIT(R.string.spec_app_qcredit); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private APP(int resId) { this.resId = resId; } } public enum CUR { UNKNOWN(R.string.spec_cur_unknown), USD(R.string.spec_cur_usd), CNY(R.string.spec_cur_cny), HKD(R.string.spec_cur_hkd); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private CUR(int resId) { this.resId = resId; } } public static final String TAG_BLK = "div"; public static final String TAG_TIP = "t_tip"; public static final String TAG_ACT = "t_action"; public static final String TAG_EM = "t_em"; public static final String TAG_H1 = "t_head1"; public static final String TAG_H2 = "t_head2"; public static final String TAG_H3 = "t_head3"; public static final String TAG_SP = "t_splitter"; public static final String TAG_TEXT = "t_text"; public static final String TAG_ITEM = "t_item"; public static final String TAG_LAB = "t_label"; public static final String TAG_PARAG = "t_parag"; }
Java
/* NFCard is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. NFCard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.ViewSwitcher; import com.sinpo.xnfc.R; import com.sinpo.xnfc.nfc.NfcManager; import com.sinpo.xnfc.ui.AboutPage; import com.sinpo.xnfc.ui.MainPage; import com.sinpo.xnfc.ui.NfcPage; import com.sinpo.xnfc.ui.Toolbar; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); nfc = new NfcManager(this); onNewIntent(getIntent()); } @Override public void onBackPressed() { if (isCurrentPage(SPEC.PAGE.ABOUT)) loadDefaultPage(); else if (safeExit) super.onBackPressed(); } @Override public void setIntent(Intent intent) { if (NfcPage.isSendByMe(intent)) loadNfcPage(intent); else if (AboutPage.isSendByMe(intent)) loadAboutPage(); else super.setIntent(intent); } @Override protected void onPause() { super.onPause(); nfc.onPause(); } @Override protected void onResume() { super.onResume(); nfc.onResume(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) { if (nfc.updateStatus()) loadDefaultPage(); // 有些ROM将关闭系统状态下拉面板的BACK事件发给最顶层窗口 // 这里加入一个延迟避免意外退出 board.postDelayed(new Runnable() { public void run() { safeExit = true; } }, 800); } else { safeExit = false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { loadDefaultPage(); } @Override protected void onNewIntent(Intent intent) { if (!nfc.readCard(intent, new NfcPage(this))) loadDefaultPage(); } public void onSwitch2DefaultPage(View view) { if (!isCurrentPage(SPEC.PAGE.DEFAULT)) loadDefaultPage(); } public void onSwitch2AboutPage(View view) { if (!isCurrentPage(SPEC.PAGE.ABOUT)) loadAboutPage(); } public void onCopyPageContent(View view) { toolbar.copyPageContent(getFrontPage()); } private void loadDefaultPage() { toolbar.show(null); TextView ta = getBackPage(); resetTextArea(ta, SPEC.PAGE.DEFAULT, Gravity.CENTER); ta.setText(MainPage.getContent(this)); board.showNext(); } private void loadAboutPage() { toolbar.show(R.id.btnBack); TextView ta = getBackPage(); resetTextArea(ta, SPEC.PAGE.ABOUT, Gravity.LEFT); ta.setText(AboutPage.getContent(this)); board.showNext(); } private void loadNfcPage(Intent intent) { final CharSequence info = NfcPage.getContent(this, intent); TextView ta = getBackPage(); if (NfcPage.isNormalInfo(intent)) { toolbar.show(R.id.btnCopy, R.id.btnReset); resetTextArea(ta, SPEC.PAGE.INFO, Gravity.LEFT); } else { toolbar.show(R.id.btnBack); resetTextArea(ta, SPEC.PAGE.INFO, Gravity.CENTER); } ta.setText(info); board.showNext(); } private boolean isCurrentPage(SPEC.PAGE which) { Object obj = getFrontPage().getTag(); if (obj == null) return which.equals(SPEC.PAGE.DEFAULT); return which.equals(obj); } private void resetTextArea(TextView textArea, SPEC.PAGE type, int gravity) { ((View) textArea.getParent()).scrollTo(0, 0); textArea.setTag(type); textArea.setGravity(gravity); } private TextView getFrontPage() { return (TextView) ((ViewGroup) board.getCurrentView()).getChildAt(0); } private TextView getBackPage() { return (TextView) ((ViewGroup) board.getNextView()).getChildAt(0); } private void initViews() { board = (ViewSwitcher) findViewById(R.id.switcher); Typeface tf = ThisApplication.getFontResource(R.string.font_oem1); TextView tv = (TextView) findViewById(R.id.txtAppName); tv.setTypeface(tf); tf = ThisApplication.getFontResource(R.string.font_oem2); tv = getFrontPage(); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setTypeface(tf); tv = getBackPage(); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setTypeface(tf); toolbar = new Toolbar((ViewGroup) findViewById(R.id.toolbar)); } private ViewSwitcher board; private Toolbar toolbar; private NfcManager nfc; private boolean safeExit; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ExternalStorage.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.commons; import android.os.Environment; /** * The class Geometry contains external storage functions. * * @author Pierre Malarme * @version 1.O * */ public class ExternalStorage { // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * @return True if the external storage is available. * False otherwise. */ public static boolean checkAvailable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if available if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } /** * @return True if the external storage is writable. * False otherwise. */ public static boolean checkWritable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if writable if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMViewer.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.1 * */ package be.ac.ulb.lisa.idot.android.dicomviewer; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import be.ac.ulb.lisa.idot.android.commons.ExternalStorage; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; import be.ac.ulb.lisa.idot.android.dicomviewer.thread.DICOMImageCacher; import be.ac.ulb.lisa.idot.android.dicomviewer.thread.ThreadState; import be.ac.ulb.lisa.idot.android.dicomviewer.view.DICOMImageView; import be.ac.ulb.lisa.idot.android.dicomviewer.view.GrayscaleWindowView; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.file.DICOMFileFilter; import be.ac.ulb.lisa.idot.dicom.file.DICOMImageReader; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitReader; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitWriter; /** * DicomViewer activity that shows an image. * * @author Pierre Malarme * @version 1.1 * */ public class DICOMViewer extends Activity implements SeekBar.OnSeekBarChangeListener { // --------------------------------------------------------------- // - <static> VARIABLES // --------------------------------------------------------------- // DIALOG /** * Define the progress dialog id for the loading of a DICOM image. */ private static final short PROGRESS_DIALOG_LOAD = 0; /** * Define the progress dialog id for the caching of * DICOM image. */ private static final short PROGRESS_DIALOG_CACHE = 1; // SAVED INSTANCE STATE KEY /** * Define the key for savedInstanceState */ private static final String FILE_NAME = "file_name"; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- // UI VARIABLES /** * The image view. */ private DICOMImageView mImageView; /** * The tool bar linear layout. */ private LinearLayout mToolBar; /** * Set if the tool bar is locked or not. */ private boolean mLockToolBar = false; /** * The button to set the mToolMode to * ToolMode.DIMENSION. */ private Button mDimensionToolButton; /** * The button to set the mToolMode to * ToolMode.GRAYSCALE. */ private Button mGrayscaleToolButton; /** * Normal CLUT button. */ private Button mCLUTNormalButton; /** * Inverse CLUT button. */ private Button mCLUTInverseButton; /** * Rainbow CLUT button. */ private Button mCLUTRainbowButton; /** * Lock/unlock tool bar button. */ private Button mLockUnlockToolBar; /** * Current tool button. */ private Button mCurrentToolButton; /** * The grayscale window (ImageView). */ private GrayscaleWindowView mGrayscaleWindow; /** * Previous button. */ private Button mPreviousButton; /** * Next button. */ private Button mNextButton; /** * Image index TextView. */ private TextView mIndexTextView; /** * Series seek bar. */ private SeekBar mIndexSeekBar; /** * Layout representing the series * navigation bar. */ private LinearLayout mNavigationBar; /** * Row orientation TextView. */ private TextView mRowOrientation; /** * Column orientation TextView. */ private TextView mColumnOrientation; // MENU VARIABLE /** * DICOM Viewer menu. */ private Menu mMenu; // DICOM FILE LOADER THREAD /** * File loader thread. */ private DICOMFileLoader mDICOMFileLoader = null; // WAIT VARIABLE /** * Progress dialog for file loading. */ private ProgressDialog loadingDialog; /** * Progress dialog for file caching. */ private ProgressDialog cachingDialog; /** * Set if the activity is busy (true) or not (false). * When a DICOM image is parsed or a LISA 16-Bit grayscale * image is loaded, the activity is in waiting mode * => busy = true. */ private boolean mBusy = false; // TODO needed ? or wait for the end of the loading thread // is enough ? // FILE VARIABLE /** * The array of DICOM image in the * folder. */ private File[] mFileArray = null; /** * The LISA 16-Bit image. */ private LISAImageGray16Bit mImage = null; /** * The index of the current file. */ private int mCurrentFileIndex; // INITIALIZATION VARIABLE /** * Set if the DICOM Viewer is initialized or not. */ private boolean mIsInitialized = false; // DATA VARIABLE /** * DICOM Viewer data. */ private DICOMViewerData mDICOMViewerData = null; // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content view setContentView(R.layout.dicom_viewer); // Declare the UI variables mImageView = (DICOMImageView) findViewById(R.id.imageView); mToolBar = (LinearLayout) findViewById(R.id.toolBar); mDimensionToolButton = (Button) findViewById(R.id.dimensionMode); mGrayscaleToolButton = (Button) findViewById(R.id.grayscaleMode); mCLUTNormalButton = (Button) findViewById(R.id.clutNormal); mCLUTInverseButton = (Button) findViewById(R.id.clutInverse); mCLUTRainbowButton = (Button) findViewById(R.id.clutRainbow); mLockUnlockToolBar = (Button) findViewById(R.id.lockUnlockToolbar); mCurrentToolButton = (Button) findViewById(R.id.currentToolButton); mGrayscaleWindow = (GrayscaleWindowView) findViewById(R.id.grayscaleImageView); mPreviousButton = (Button) findViewById(R.id.previousImageButton); mNextButton = (Button) findViewById(R.id.nextImageButton); mIndexTextView = (TextView) findViewById(R.id.imageIndexView); mIndexSeekBar = (SeekBar) findViewById(R.id.serieSeekBar); mNavigationBar = (LinearLayout) findViewById(R.id.navigationToolbar); mRowOrientation = (TextView) findViewById(R.id.rowTextView); mColumnOrientation = (TextView) findViewById(R.id.columnTextView); // Get the file name from the savedInstanceState or from the intent String fileName = null; // If the saved instance state is not null get the file name if (savedInstanceState != null) { fileName = savedInstanceState.getString(FILE_NAME); // Get the intent } else { Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); fileName = extras == null ? null : extras.getString("DICOMFileName"); } } // If the file name is null, alert the user and close // the activity if (fileName == null) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "Cannot retrieve its name."); // Load the file } else { // Get the File object for the current file File currentFile = new File(fileName); // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, currentFile); mDICOMFileLoader.start(); mBusy = true; // Get the files array = get the files contained // in the parent of the current file mFileArray = currentFile.getParentFile().listFiles(new DICOMFileFilter()); // Sort the files array Arrays.sort(mFileArray); // If the files array is null or its length is less than 1, // there is an error because it must at least contain 1 file: // the current file if (mFileArray == null || mFileArray.length < 1) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "The directory containing normally the file contains" + " no DICOM files."); } else { // Get the file index in the array mCurrentFileIndex = getIndex(currentFile); // If the current file index is negative // or greater or equal to the files array // length there is an error if (mCurrentFileIndex < 0 || mCurrentFileIndex >= mFileArray.length) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "The file is not in the directory."); // Else initialize views and navigation bar } else { // Check if the seek bar must be shown or not if (mFileArray.length == 1) { mNavigationBar.setVisibility(View.INVISIBLE); } else { // Display the current file index mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); // Display the files count and set the seek bar maximum TextView countTextView = (TextView) findViewById(R.id.imageCountView); countTextView.setText(String.valueOf(mFileArray.length)); mIndexSeekBar.setMax(mFileArray.length - 1); mIndexSeekBar.setProgress(mCurrentFileIndex); // Set the visibility of the previous button if (mCurrentFileIndex == 0) { mPreviousButton.setVisibility(View.INVISIBLE); } else if (mCurrentFileIndex == (mFileArray.length - 1)) { mNextButton.setVisibility(View.INVISIBLE); } } } } } // Set the seek bar change index listener mIndexSeekBar.setOnSeekBarChangeListener(this); // Set onLongClickListener mIndexSeekBar.setOnLongClickListener(onLongClickListener); mNavigationBar.setOnLongClickListener(onLongClickListener); mPreviousButton.setOnLongClickListener(onLongClickListener); mNextButton.setOnLongClickListener(onLongClickListener); mToolBar.setOnLongClickListener(onLongClickListener); mGrayscaleWindow.setOnLongClickListener(onLongClickListener); // Create the DICOMViewerData and set // the tool mode to dimension mDICOMViewerData = new DICOMViewerData(); mDICOMViewerData.setToolMode(ToolMode.DIMENSION); mDimensionToolButton.setBackgroundResource(R.drawable.ruler_select); mCurrentToolButton.setBackgroundResource(R.drawable.ruler_select); mCLUTNormalButton.setVisibility(View.GONE); mCLUTNormalButton.setBackgroundResource(R.drawable.clut_normal_select); mCLUTInverseButton.setVisibility(View.GONE); mCLUTRainbowButton.setVisibility(View.GONE); mToolBar.setVisibility(View.GONE); // Set the tool mode too the DICOMImageView and // the GrayscaleWindow mImageView.setDICOMViewerData(mDICOMViewerData); mGrayscaleWindow.setDICOMViewerData(mDICOMViewerData); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // If there is no external storage available, quit the application if (!ExternalStorage.checkAvailable()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("There is no external storage.\n" + "1) There is no external storage : add one.\n" + "2) Your external storage is used by a computer:" + " Disconnect the it from the computer.") .setTitle("[ERROR] No External Storage") .setCancelable(false) .setPositiveButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DICOMViewer.this.finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } super.onResume(); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { // We wait until the end of the loading thread // before putting the activity in pause mode if (mDICOMFileLoader != null) { // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } } super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mImage = null; mDICOMViewerData = null; mFileArray = null; mDICOMFileLoader = null; // Free the drawable callback if (mImageView != null) { Drawable drawable = mImageView.getDrawable(); if (drawable != null) drawable.setCallback(null); } } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the current file name String currentFileName = mFileArray[mCurrentFileIndex].getAbsolutePath(); outState.putString(FILE_NAME, currentFileName); } @Override protected Dialog onCreateDialog(int id) { // TODO : cancelable dialog ? switch(id) { // Create image cache dialog case PROGRESS_DIALOG_CACHE: cachingDialog = new ProgressDialog(this); cachingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); cachingDialog.setMessage("Caching image..."); cachingDialog.setCancelable(false); return cachingDialog; // Create image load dialog case PROGRESS_DIALOG_LOAD: loadingDialog = new ProgressDialog(this); loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); loadingDialog.setMessage("Loading image..."); loadingDialog.setCancelable(false); return loadingDialog; default: return null; } } // --------------------------------------------------------------- // + <override> FUNCTIONS // --------------------------------------------------------------- @Override public void onLowMemory() { // Hint the garbage collector System.gc(); // Show the exit alert dialog showExitAlertDialog("[ERROR] LowMemory", "[ERROR] LowMemory"); super.onLowMemory(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // It's safer to hold the menu (cf. Android // documentation) mMenu = menu; // Inflate the currently selected menu XML resource. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dicom_viewer_menu, menu); // Set the show/hide grayscale window state MenuItem grayscaleShowHide = menu.findItem(R.id.showHide_grayscaleWindow); if (mGrayscaleWindow.getVisibility() == View.INVISIBLE) grayscaleShowHide.setChecked(false); else grayscaleShowHide.setChecked(true); // Set the show/hide series navigation bar MenuItem serieNavigationBar = menu.findItem(R.id.showHide_serieSeekBar); if (mNavigationBar.getVisibility() == View.INVISIBLE) serieNavigationBar.setChecked(false); else serieNavigationBar.setChecked(true); // If there is at most one file if (mFileArray.length <= 1) serieNavigationBar.setEnabled(false); else serieNavigationBar.setEnabled(true); // Set the show/hide tool bar MenuItem toolBar = menu.findItem(R.id.showHide_toolbar); if (mToolBar.getVisibility() == View.GONE && mCurrentToolButton.getVisibility() == View.INVISIBLE) toolBar.setChecked(false); else toolBar.setChecked(true); // Set the CLUT mode switch (mDICOMViewerData.getCLUTMode()) { case CLUTMode.NORMAL: MenuItem clutMode = menu.findItem(R.id.show_normalLUT); clutMode.setChecked(true); break; case CLUTMode.INVERSE: clutMode = menu.findItem(R.id.show_inverseLUT); clutMode.setChecked(true); break; case CLUTMode.RAINBOW: clutMode = menu.findItem(R.id.show_rainbowCLUT); clutMode.setChecked(true); break; } // Set the lock/unlock tool bar menu time MenuItem lockUnlockToolBar = menu.findItem(R.id.lock_toolbar); if (mLockToolBar) lockUnlockToolBar.setChecked(true); else lockUnlockToolBar.setChecked(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // SHOW/HIDE case R.id.showHide_grayscaleWindow: if (mGrayscaleWindow.getVisibility() == View.INVISIBLE) { item.setChecked(true); mGrayscaleWindow.setVisibility(View.VISIBLE); } else { item.setChecked(false); mGrayscaleWindow.setVisibility(View.INVISIBLE); } return true; case R.id.showHide_serieSeekBar: if(mNavigationBar.getVisibility() == View.INVISIBLE) { item.setChecked(true); mNavigationBar.setVisibility(View.VISIBLE); } else { item.setChecked(false); mNavigationBar.setVisibility(View.INVISIBLE); } return true; case R.id.showHide_toolbar: if(mToolBar.getVisibility() == View.VISIBLE || mCurrentToolButton.getVisibility() == View.VISIBLE) { item.setChecked(false); hideToolBar(null); mCurrentToolButton.setVisibility(View.INVISIBLE); } else { item.setChecked(false); if (mLockToolBar) showToolBar(null); else mCurrentToolButton.setVisibility(View.VISIBLE); } return true; case R.id.lock_toolbar: if (mLockToolBar) { item.setChecked(false); mLockToolBar = false; mLockUnlockToolBar.setBackgroundResource(R.drawable.unlock); hideToolBar(null); } else { item.setChecked(true); mLockToolBar = true; mLockUnlockToolBar.setBackgroundResource(R.drawable.lock); showToolBar(null); } return true; // LUT/CLUT case R.id.show_normalLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal_select); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.NORMAL); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; case R.id.show_inverseLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse_select); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.INVERSE); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; case R.id.show_rainbowCLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow_select); mDICOMViewerData.setCLUTMode(CLUTMode.RAINBOW); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; // GRAYSCALE WINDOW case R.id.grayscaleWindow_CTBone: mDICOMViewerData.setWindowWidth(1500); mDICOMViewerData.setWindowCenter(300 + 1024); mImageView.draw(); return true; case R.id.grayscaleWindow_CTCrane: mDICOMViewerData.setWindowWidth(100); mDICOMViewerData.setWindowCenter(50 + 1024); mImageView.draw(); return true; case R.id.grayscaleWindow_CTLung: mDICOMViewerData.setWindowWidth(1400); mDICOMViewerData.setWindowCenter(1024 - 400); mImageView.draw(); return true; case R.id.grayscaleWindow_CTAbdomen: mDICOMViewerData.setWindowWidth(350); mDICOMViewerData.setWindowCenter(40 + 1024); mImageView.draw(); return true; // IMAGE SCALE MODE case R.id.fit_to_screen: item.setChecked(true); mDICOMViewerData.setScaleMode(ScaleMode.FITIN); mImageView.resetSize(); return true; case R.id.real_size: item.setChecked(true); mDICOMViewerData.setScaleMode(ScaleMode.REALSIZE); mImageView.resetSize(); return true; // CACHE ALL IMAGES case R.id.ddv_CacheAllImage: cacheImages(); return true; // ABOUT DIALOG case R.id.ddv_DialogAbout: Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.dialog_about); dialog.setTitle("Droid Dicom Viewer: About"); dialog.show(); return true; } return super.onOptionsItemSelected(item); } // --------------------------------------------------------------- // + <implements> FUNCTION // --------------------------------------------------------------- /* (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onProgressChanged(android.widget.SeekBar, int, boolean) */ public synchronized void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { try { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // Set the current file index mCurrentFileIndex = progress; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); // Set the visibility of the previous button if (mCurrentFileIndex == 0) { mPreviousButton.setVisibility(View.INVISIBLE); mNextButton.setVisibility(View.VISIBLE); } else if (mCurrentFileIndex == (mFileArray.length - 1)) { mNextButton.setVisibility(View.INVISIBLE); mPreviousButton.setVisibility(View.VISIBLE); } else { mPreviousButton.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.VISIBLE); } } catch (OutOfMemoryError ex) { System.gc(); showExitAlertDialog("[ERROR] Out Of Memory", "This series contains images that are too big" + " and that cause out of memory error. The best is to don't" + " use the series seek bar. If the error occurs again" + " it is because this series is not adapted to your" + " Android(TM) device."); } } // Needed to implement the SeekBar.OnSeekBarChangeListener public void onStartTrackingTouch(SeekBar seekBar) { // Do nothing. } // Needed to implement the SeekBar.OnSeekBarChangeListener public void onStopTrackingTouch(SeekBar seekBar) { System.gc(); // TODO needed ? // Do nothing. } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Set mToolMode to ToolMode.DIMENSION. * * @param view The view that call the handler. Can be null */ public void dimensionMode(View view) { if (mDICOMViewerData.getToolMode() != ToolMode.DIMENSION) { mDICOMViewerData.setToolMode(ToolMode.DIMENSION); mDimensionToolButton.setBackgroundResource(R.drawable.ruler_select); mCurrentToolButton.setBackgroundResource(R.drawable.ruler_select); mGrayscaleToolButton.setBackgroundResource(R.drawable.grayscale); mCLUTNormalButton.setVisibility(View.GONE); mCLUTInverseButton.setVisibility(View.GONE); mCLUTRainbowButton.setVisibility(View.GONE); } if (!mLockToolBar) hideToolBar(view); } /** * Set mToolMode to ToolMode.GRAYSCALE. * * @param view The view that call the handler. Can be null */ public void grayscaleMode(View view) { if (mDICOMViewerData.getToolMode() != ToolMode.GRAYSCALE) { mDICOMViewerData.setToolMode(ToolMode.GRAYSCALE); mGrayscaleToolButton.setBackgroundResource(R.drawable.grayscale_select); mCurrentToolButton.setBackgroundResource(R.drawable.grayscale_select); mDimensionToolButton.setBackgroundResource(R.drawable.ruler); mCLUTNormalButton.setVisibility(View.VISIBLE); mCLUTInverseButton.setVisibility(View.VISIBLE); mCLUTRainbowButton.setVisibility(View.VISIBLE); } if (!mLockToolBar) hideToolBar(view); } // --------------------------------------------------------------- // + <synchronized> FUNCTIONS // --------------------------------------------------------------- /** * Handle touch on the previousButton. * @param view */ public synchronized void previousImage(View view) { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // If the current file index is 0, there is // no previous file in the files array // We add the less or equal to zero because it is // safer if (mCurrentFileIndex <= 0) { // Not necessary but safer, because we don't know // how the code will be used in the future mCurrentFileIndex = 0; // If for a unknown reason the previous button is // visible => hide it if (mPreviousButton.getVisibility() == View.VISIBLE) mPreviousButton.setVisibility(View.INVISIBLE); mBusy = false; return; } // Decrease the file index mCurrentFileIndex--; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); mIndexSeekBar.setProgress(mCurrentFileIndex); if (mCurrentFileIndex == 0) mPreviousButton.setVisibility(View.INVISIBLE); // The next button is automatically set to visible // because if there is a previous image, there is // a next image mNextButton.setVisibility(View.VISIBLE); } /** * Handle touch on next button. * @param view */ public synchronized void nextImage(View view) { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // If the current file index is the last file index, // there is no next file in the files array // We add the greater or equal to (mFileArray.length - 1) // because it is safer if (mCurrentFileIndex >= (mFileArray.length - 1)) { // Not necessary but safer, because we don't know // how the code will be used in the future mCurrentFileIndex = (mFileArray.length - 1); // If for a unknown reason the previous button is // visible => hide it if (mNextButton.getVisibility() == View.VISIBLE) mNextButton.setVisibility(View.INVISIBLE); mBusy = false; return; } // Increase the file index mCurrentFileIndex++; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); mIndexSeekBar.setProgress(mCurrentFileIndex); if (mCurrentFileIndex == (mFileArray.length - 1)) mNextButton.setVisibility(View.INVISIBLE); // The previous button is automatically set to visible // because if there is a next image, there is // a previous image mPreviousButton.setVisibility(View.VISIBLE); } /** * Hide navigation tool bar if it is visible. * @param view */ public void hideNavigationBar(View view) { if (mNavigationBar.getVisibility() == View.VISIBLE) { mNavigationBar.setVisibility(View.INVISIBLE); if (mMenu != null) { MenuItem showHideNavigationBar = mMenu.findItem(R.id.showHide_serieSeekBar); if (showHideNavigationBar != null) { showHideNavigationBar.setChecked(false); } } } } /** * Hide navigation tool bar if it is visible. * @param view */ public void hideGrayscaleWindow(View view) { if (mGrayscaleWindow.getVisibility() == View.VISIBLE) { mGrayscaleWindow.setVisibility(View.INVISIBLE); if (mMenu != null) { MenuItem showHideGrayscaleWindow = mMenu.findItem(R.id.showHide_grayscaleWindow); if (showHideGrayscaleWindow != null) { showHideGrayscaleWindow.setChecked(false); } } } } /** * Hide tool bar if it is visible. * @param view */ public void hideToolBar(View view) { if (mToolBar.getVisibility() == View.VISIBLE) { mToolBar.setVisibility(View.GONE); // If the tool bar is locked then the current icon // is invisible too if (!mLockToolBar) { mCurrentToolButton.setVisibility(View.VISIBLE); } else { if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.showHide_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(false); } } } } } /** * Hide tool bar if it is visible. * @param view */ public void showToolBar(View view) { if (mToolBar.getVisibility() == View.GONE) { mCurrentToolButton.setVisibility(View.INVISIBLE); mToolBar.setVisibility(View.VISIBLE); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.showHide_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } } } /** * Set the CLUT mode. * @param view */ public synchronized void setCLUTMode(View view) { if (view == null) return; switch (view.getId()) { case R.id.clutNormal: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal_select); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.NORMAL); // Update the menu if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_normalLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; case R.id.clutInverse: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse_select); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.INVERSE); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_inverseLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; case R.id.clutRainbow: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow_select); mDICOMViewerData.setCLUTMode(CLUTMode.RAINBOW); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_rainbowCLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; } mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); if (!mLockToolBar) hideToolBar(null); } /** * Lock/unlock the tool bar. * @param view */ public void lockUnlockToolBar(View view) { if (mLockToolBar) { mLockToolBar = false; mLockUnlockToolBar.setBackgroundResource(R.drawable.unlock); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.lock_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(false); } } hideToolBar(view); } else { mLockToolBar = true; mLockUnlockToolBar.setBackgroundResource(R.drawable.lock); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.lock_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } } } // --------------------------------------------------------------- // - FUNCTIONS // --------------------------------------------------------------- /** * Get the index of the file in the files array. * @param file * @return Index of the file in the files array * or -1 if the files is not in the list. */ private int getIndex(File file) { if (mFileArray == null) throw new NullPointerException("The files array is null."); for (int i = 0; i < mFileArray.length; i++) { if (mFileArray[i].getName().equals(file.getName())) return i; } return -1; } /** * Set the currentImage * * @param image */ private void setImage(LISAImageGray16Bit image) { if (image == null) throw new NullPointerException("The LISA 16-Bit grayscale image " + "is null"); try { // Set the image mImage = null; mImage = image; mImageView.setImage(mImage); mGrayscaleWindow.setImage(mImage); setImageOrientation(); // If it is not initialized, set the window width and center // as the value set in the LISA 16-Bit grayscale image // that comes from the DICOM image file. if (!mIsInitialized) { mIsInitialized = true; mDICOMViewerData.setWindowWidth(mImage.getWindowWidth()); mDICOMViewerData.setWindowCenter(mImage.getWindowCenter()); mImageView.draw(); mImageView.fitIn(); } else { mImageView.draw(); } mBusy = false; } catch (OutOfMemoryError ex) { System.gc(); showExitAlertDialog("[ERROR] Out Of Memory", "This series contains images that are too big" + " and that cause out of memory error. The best is to don't" + " use the series seek bar. If the error occurs again" + " it is because this series is not adapted to your" + " Android(TM) device."); } catch (ArrayIndexOutOfBoundsException ex) { showExitAlertDialog("[ERROR] Image drawing", "An uncatchable error occurs while " + "drawing the DICOM image."); } } /** * Set the image orientation TextViews. */ private void setImageOrientation() { float[] imageOrientation = mImage.getImageOrientation(); if (imageOrientation == null || imageOrientation.length != 6 || imageOrientation.equals(new float[6])) // equal to a float with 6 zeros return; // Displaying the row orientation mRowOrientation.setText(getImageOrientationString(imageOrientation, 0)); // Displaying the column orientation mColumnOrientation.setText(getImageOrientationString(imageOrientation, 3)); } /** * Get the image orientation String for a 3D vector of float * that is related to a direction cosine. * * @param imageOrientation * @param offset * @return */ private String getImageOrientationString(float[] imageOrientation, int offset) { String orientation = ""; // The threshold is 0.25 // If abs(ImageOrientation.X) < threshold // and ImageOrientation.X > 0 => orientation: RL if (imageOrientation[0 + offset] >= 0.25) { orientation += "R"; // If abs(ImageOrientation.X) < threshold // and ImageOrientation.X < 0 => orientation: LR } else if (imageOrientation[0 + offset] <= -0.25) { orientation += "L"; } // If abs(ImageOrientation.Y) < threshold // and ImageOrientation.Y > 0 => orientation: AP if (imageOrientation[1 + offset] >= 0.25) { orientation += "A"; // If abs(ImageOrientation.Y) < threshold // and ImageOrientation.Y < 0 => orientation: PA } else if (imageOrientation[1 + offset] <= -0.25) { orientation += "P"; } // If abs(ImageOrientation.Z) < threshold // and ImageOrientation.Z > 0 => orientation: FH if (imageOrientation[2 + offset] >= 0.25) { orientation += "F"; // If abs(ImageOrientation.Z) < threshold // and ImageOrientation.Z < 0 => orientation: HF } else if (imageOrientation[2 + offset] <= -0.25) { orientation += "H"; } return orientation; } /** * Cache of the image in the files array */ private void cacheImages() { try { // The handler is inside the function because // normally this function is called once. final Handler cacheHandler = new Handler() { public void handleMessage(Message message) { switch (message.what) { case ThreadState.STARTED: cachingDialog.setMax(message.arg1); break; case ThreadState.PROGRESSION_UPDATE: cachingDialog.setProgress(message.arg1); break; case ThreadState.FINISHED: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } break; case ThreadState.CATCHABLE_ERROR_OCCURRED: cachingDialog.setProgress(message.arg1); Toast.makeText(DICOMViewer.this, "[Error]: file (" + (String) message.obj + ") cannot be cached.", Toast.LENGTH_SHORT).show(); break; case ThreadState.UNCATCHABLE_ERROR_OCCURRED: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } AlertDialog.Builder builder = new AlertDialog.Builder(DICOMViewer.this); builder.setMessage("Unknown error: An unknown error occurred during" + " images caching.") .setTitle("[ERROR] Caching file") .setCancelable(false) .setPositiveButton("Close", null); AlertDialog alertDialog = builder.create(); alertDialog.show(); break; case ThreadState.OUT_OF_MEMORY: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } builder = new AlertDialog.Builder(DICOMViewer.this); builder.setMessage("OutOfMemoryError: During the caching of series files," + " an out of memory error occurred.\n\n" + "Your file(s) is (are) too large for your Android system. You can" + " try again in the file chooser. If the error occured again," + " then the image cannot be displayed on your device.\n" + "Try to use the Droid Dicom Viewer desktop file cacher software" + " (not available yet).") .setTitle("[ERROR] Caching file") .setCancelable(false) .setPositiveButton("Close", null); alertDialog = builder.create(); alertDialog.show(); break; }; } }; // Show the progress dialog for caching image showDialog(PROGRESS_DIALOG_CACHE); // Start the caching thread DICOMImageCacher dicomImageCacher = new DICOMImageCacher(cacheHandler, mFileArray[mCurrentFileIndex].getParent()); dicomImageCacher.start(); } catch (FileNotFoundException e) { // TODO display an error ? } } /** * Show an alert dialog (AlertDialog) to inform * the user that the activity must finish. * @param title Title of the AlertDialog. * @param message Message of the AlertDialog. */ private void showExitAlertDialog(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message) .setTitle(title) .setCancelable(false) .setPositiveButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DICOMViewer.this.finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } // --------------------------------------------------------------- // - <final> Class // --------------------------------------------------------------- /** * The OnLongClickListener. */ private final View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() { public boolean onLongClick(View view) { if (view == null) return false; switch(view.getId()) { case R.id.toolBar: hideToolBar(view); return true; case R.id.grayscaleImageView: hideGrayscaleWindow(view); return true; case R.id.navigationToolbar: case R.id.previousImageButton: case R.id.nextImageButton: case R.id.serieSeekBar: hideNavigationBar(view); return true; default: return false; } } }; private final Handler loadingHandler = new Handler() { public void handleMessage(Message message) { switch (message.what) { case ThreadState.STARTED: showDialog(PROGRESS_DIALOG_LOAD); break; case ThreadState.FINISHED: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Set the loaded image if (message.obj instanceof LISAImageGray16Bit) { setImage((LISAImageGray16Bit) message.obj); } break; case ThreadState.UNCATCHABLE_ERROR_OCCURRED: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Get the error message String errorMessage; if (message.obj instanceof String) errorMessage = (String) message.obj; else errorMessage = "Unknown error"; // Show an alert dialog showExitAlertDialog("[ERROR] Loading file", "An error occured during the file loading.\n\n" + errorMessage); break; case ThreadState.OUT_OF_MEMORY: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Show an alert dialog showExitAlertDialog("[ERROR] Loading file", "OutOfMemoryError: During the loading of image (" + mFileArray[mCurrentFileIndex].getName() + "), an out of memory error occurred.\n\n" + "Your file is too large for your Android system. You can" + " try to cache the image in the file chooser." + " If the error occured again, then the image cannot be displayed" + " on your device.\n" + "Try to use the Droid Dicom Viewer desktop file cacher software" + " (not available yet)."); break; } } }; // --------------------------------------------------------------- // - <static> CLASS // --------------------------------------------------------------- private static final class DICOMFileLoader extends Thread { // The handler to send message to the parent thread private final Handler mHandler; // The file to load private final File mFile; public DICOMFileLoader(Handler handler, File file) { if (handler == null) throw new NullPointerException("The handler is null while" + " calling the loading thread."); mHandler = handler; if (file == null) throw new NullPointerException("The file is null while" + " calling the loading thread."); mFile = file; } public void run() { // If the image data is null, do nothing. if (!mFile.exists()) { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = "The file doesn't exist."; mHandler.sendMessage(message); return; } // If image exists show image try { LISAImageGray16BitReader reader = new LISAImageGray16BitReader(mFile + ".lisa"); LISAImageGray16Bit image = reader.parseImage(); reader.close(); // Send the LISA 16-Bit grayscale image Message message = mHandler.obtainMessage(); message.what = ThreadState.FINISHED; message.obj = image; mHandler.sendMessage(message); return; } catch (Exception ex) { // Do nothing and create a LISA image } // Create a LISA image and ask to show the // progress dialog in spinner mode mHandler.sendEmptyMessage(ThreadState.STARTED); try { DICOMImageReader dicomFileReader = new DICOMImageReader(mFile); DICOMImage dicomImage = dicomFileReader.parse(); dicomFileReader.close(); // If the image is uncompressed, show it and cached it. if (dicomImage.isUncompressed()) { LISAImageGray16BitWriter out = new LISAImageGray16BitWriter(mFile + ".lisa"); out.write(dicomImage.getImage()); out.flush(); out.close(); Message message = mHandler.obtainMessage(); message.what = ThreadState.FINISHED; message.obj = dicomImage.getImage(); mHandler.sendMessage(message); // Hint the garbage collector System.gc(); } else { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = "The file is compressed. Compressed format are not" + " supported yet."; mHandler.sendMessage(message); } } catch (OutOfMemoryError ex) { Message message = mHandler.obtainMessage(); message.what = ThreadState.OUT_OF_MEMORY; message.obj = ex.getMessage(); mHandler.sendMessage(message); } catch (Exception ex) { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = ex.getMessage(); mHandler.sendMessage(message); } } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMViewerData.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.data; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; /** * Class containing the data specific * to the DICOM Viewer. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMViewerData { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The tool mode. */ private short mToolMode = ToolMode.DIMENSION; /** * CLUT mode. */ private short mCLUTMode = CLUTMode.NORMAL; /** * The scale mode: fit in or real size. */ private short mScaleMode = ScaleMode.FITIN; /** * Grayscale window width. */ private int mWindowWidth = -1; /** * Grayscale window center */ private int mWindowCenter = -1; /** * @return the mToolMode */ public short getToolMode() { return mToolMode; } /** * @return the mCLUTMode */ public short getCLUTMode() { return mCLUTMode; } /** * @return the mScaleMode */ public short getScaleMode() { return mScaleMode; } /** * @return the mWindowWidth */ public int getWindowWidth() { return mWindowWidth; } /** * @return the mWindowCenter */ public int getWindowCenter() { return mWindowCenter; } /** * @param mToolMode the mToolMode to set */ public void setToolMode(short mToolMode) { this.mToolMode = mToolMode; } /** * @param mCLUTMode the mCLUTMode to set */ public void setCLUTMode(short mCLUTMode) { this.mCLUTMode = mCLUTMode; } /** * @param mScaleMode the mScaleMode to set */ public void setScaleMode(short mScaleMode) { this.mScaleMode = mScaleMode; } /** * @param mWindowWidth the mWindowWidth to set */ public void setWindowWidth(int mWindowWidth) { // The minimum window width is 1 // cf. DICOM documentation if (mWindowWidth <= 0) this.mWindowWidth = 1; else this.mWindowWidth = mWindowWidth; } /** * @param mWindowCenter the mWindowCenter to set */ public void setWindowCenter(int mWindowCenter) { this.mWindowCenter = mWindowCenter; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageView.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.1 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.PointF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import be.ac.ulb.lisa.idot.android.dicomviewer.DICOMViewer; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.TouchMode; import be.ac.ulb.lisa.idot.commons.Geometry; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Dicom ImageView that extends Android ImageView objects and * implements onTouchListener. * * The DICOMViewerData must be set at the creation of the activity * that contains this View. * * @author Pierre Malarme * @version 1.1 * */ public class DICOMImageView extends ImageView implements OnTouchListener { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- // IMAGE VARIABLES /** * The LISA 16-Bit Grayscale Image. */ private LISAImageGray16Bit mImage = null; /** * The transformation matrix. */ private Matrix mMatrix; /** * The scale factor. */ private float mScaleFactor; // TOUCH EVENT VARIABLES /** * The touch mode. */ private short mTouchMode; /** * The transformation matrix saved when a touch down * dimension event is caught. */ private Matrix mSavedMatrix; /** * The time of the first touch down. */ private long mTouchTime; /** * The point where the touch start. */ private PointF mTouchStartPoint; /** * The mid point of the touch event. */ private PointF mTouchMidPoint; /** * The distance between the two point * for a TWO_FINGERS touch event. */ private float mTouchOldDist; /** * The old scaleFactor. */ private float mTouchOldScaleFactor; // INITIALIZATION VARIABLE /** * Set if the view is initialized or not. */ private boolean mIsInit = false; // DICOMVIEWER DATA /** * DICOMViewer data. */ private DICOMViewerData mDICOMViewerData = null; // CONTEXT /** * Context. */ private Context mContext; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageView(Context context) { super(context); mContext = context; init(); } public DICOMImageView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } public DICOMImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; init(); } // --------------------------------------------------------------- // + <override> FUNCTIONS // --------------------------------------------------------------- /* (non-Javadoc) * @see android.widget.ImageView#setScaleType(android.widget.ImageView.ScaleType) */ @Override public void setScaleType(ImageView.ScaleType scaleType) { // Do nothing because we accept only the matrix scale type } // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- // This function is override to fit the image in the // ImageView at initialization. Because when this method // is called, the size of the ImageView is set. // The override of the onDraw method lead to a slower // display of the image. It is for that we override // this method. /* (non-Javadoc) * @see android.widget.ImageView#drawableStateChanged() */ @Override protected void drawableStateChanged() { if (mIsInit == false) { mIsInit = true; if (mImage != null) fitIn(); } super.drawableStateChanged(); } // This function is override to center the image // when the size of the screen change /* (non-Javadoc) * @see android.view.View#onSizeChanged(int, int, int, int) */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { // If the image is not null, center it if (mImage != null) center(); super.onSizeChanged(w, h, oldw, oldh); } // --------------------------------------------------------------- // + <implement> FUNCTIONS // --------------------------------------------------------------- public boolean onTouch(View v, MotionEvent event) { if (mImage == null || mDICOMViewerData == null) return false; // Get the tool mode short toolMode = mDICOMViewerData.getToolMode(); // Handle touch event switch(event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // Double tap if ((System.currentTimeMillis() - mTouchTime) < 450) { // The touch mode is set to none mTouchMode = TouchMode.NONE; mTouchTime = 0; // If toolMode is DIMENSION, fit the image // in the screen. if (toolMode == ToolMode.DIMENSION) { if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) fitIn(); else realSize(); } else if (toolMode == ToolMode.GRAYSCALE) { mDICOMViewerData.setWindowWidth(mImage.getWindowWidth()); mDICOMViewerData.setWindowCenter(mImage.getWindowCenter()); draw(); } return true; // Single tap } else if (mTouchMode == TouchMode.NONE) { // Set the touch time mTouchTime = System.currentTimeMillis(); // Set the touch mode to ONE_FINGER mTouchMode = TouchMode.ONE_FINGER; // Set the mSavedMatrix mSavedMatrix.set(mMatrix); // Set the mTouchStartPoint value mTouchStartPoint.set(event.getX(), event.getY()); } else { mTouchTime = 0; } break; case MotionEvent.ACTION_POINTER_DOWN: // Check if there is two pointers if (event.getPointerCount() == 2) { // Set mTouchMode to TouchMode.TWO_FINGERS mTouchMode = TouchMode.TWO_FINGERS; // Reset mTouchTime mTouchTime = 0; // DIMENSION MODE if (toolMode == ToolMode.DIMENSION) { // Compute the olf dist between the two pointer. mTouchOldDist = Geometry.euclidianDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); // Compute the old scale factor as the mScaleFactor // at the begining of the touch event. mTouchOldScaleFactor = mScaleFactor; // Compute the midPoint if ((mImage.getWidth() * mScaleFactor) <= getMeasuredWidth() || (mImage.getHeight() * mScaleFactor) <= getMeasuredHeight()) { mTouchMidPoint = new PointF(getMeasuredWidth() / 2f, getMeasuredHeight() / 2f); } else { mTouchMidPoint = Geometry.midPoint(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); } } } else if (event.getPointerCount() == 3) { // Set the touch mode to three fingers mTouchMode = TouchMode.THREE_FINGERS; // Reset the mTouchTime mTouchTime = 0; // The start point is the average of the three fingers // just for the x coordinate mTouchStartPoint.set( (event.getX(0) + event.getX(1) + event.getX(2)) / 3f, 0f); } break; case MotionEvent.ACTION_MOVE: // If this is a ONE_FINGER touch mode if (mTouchMode == TouchMode.ONE_FINGER) { // Switch on toolMode switch(toolMode) { case ToolMode.DIMENSION: // Set the matrix mMatrix.set(mSavedMatrix); // Variable declaration float dx = 0; float dy = 0; // Compute the translation dx = event.getX() - mTouchStartPoint.x; dy = event.getY() - mTouchStartPoint.y; // TODO center the image if width or height > this size // Set the translation mMatrix.postTranslate(dx, dy); // Set the transformation matrix setImageMatrix(mMatrix); break; case ToolMode.GRAYSCALE: // Compute the grayscale window center int center = (getMeasuredHeight() - 10 - (int) event.getY()) * /*grayscaleWindow.getGrayLevel()*/mImage.getDataMax() / (getMeasuredHeight()); // Compute the grayscale window width int width = (int) event.getX() * /*grayscaleWindow.getGrayLevel()*/mImage.getDataMax() / (getMeasuredWidth()); // Set the grayscale window attributes mDICOMViewerData.setWindowWidth(width); mDICOMViewerData.setWindowCenter(center); // Compute the RGB image draw(); break; }; } else if (mTouchMode == TouchMode.TWO_FINGERS && toolMode == ToolMode.DIMENSION) { // Compute the distance between the two finger float newDist = Geometry.euclidianDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); // TODO necessary ? //if (newDist > 3f) { if (newDist != mTouchOldDist) { // Set the matrix mMatrix.set(mSavedMatrix); // Scale factor float scaleFactor = newDist / mTouchOldDist; // Compute the global scale factor mScaleFactor = mTouchOldScaleFactor * scaleFactor; // Set the scale center at the mid point of the event mMatrix.postScale(scaleFactor, scaleFactor, mTouchMidPoint.x, mTouchMidPoint.y); // Set the transformation matrix setImageMatrix(mMatrix); } } else if (mTouchMode == TouchMode.THREE_FINGERS) { // Get the current event average (3 fingers) x coordinate float eventAverageX = event.getX(0) + event.getX(1) + event.getX(2) / 3f; // If the distance is greater than 40% of the ImageView width, change // image. if (Geometry.euclidianDistance(eventAverageX, 0, mTouchStartPoint.x, 0) >= (0.4f * (float) getMeasuredWidth())) { // Get the direction of the touch event float directionX = eventAverageX - mTouchStartPoint.x; // Show next or previous image if (directionX < 0) ((DICOMViewer) mContext).nextImage(null); else ((DICOMViewer) mContext).previousImage(null); // Set the touchmode to none mTouchMode = TouchMode.NONE; } } return true; // Draw case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: // Set that this is the end of the touch event mTouchMode = TouchMode.NONE; // Check the dimension if (toolMode == ToolMode.DIMENSION) { // Compute mImageView width and height and the image // or the image size if is in ScaleMode real size // scaled width and height float imageWidth, imageHeight; // Check the scale mode to see if the image size is // smaller than the required size if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) { imageWidth = getMeasuredWidth(); imageHeight = getMeasuredHeight(); } else { imageWidth = mImage.getWidth(); imageHeight = mImage.getHeight(); } float scaledImageWidth = (float) mImage.getWidth() * mScaleFactor; float scaledImageHeight = (float) mImage.getHeight() * mScaleFactor; // If the image fit int the window => fit in the window if (scaledImageWidth <= imageWidth && scaledImageHeight <= imageHeight) { if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) fitIn(); else realSize(); } else { // The ImageView size is needed imageWidth = getMeasuredWidth(); imageHeight = getMeasuredHeight(); // Get the matrix for the transformation mMatrix.set(getImageMatrix()); // Set the source and destination rect points that correpond // to the upper left corner and the bottom right corner float[] srcRectPoints = { 0f, 0f, mImage.getWidth(), mImage.getHeight()}; float[] dstRectPoints = new float[4]; // Apply the image matrix transformation on these points mMatrix.mapPoints(dstRectPoints, srcRectPoints); // Init transalation variables float dx = 0f; float dy = 0f; // If the scaled image width is greater than the mImageView width if (scaledImageWidth > imageWidth) { // If there is black at the left of the screen if (dstRectPoints[0] > 0f) { dx = (-1f) * dstRectPoints[0]; // Else if there is black at the right of the screen } else if (dstRectPoints[2] < imageWidth) { dx = imageWidth - dstRectPoints[2]; } } else { // Compute the left border and the right border // to center the image float lx = (imageWidth - scaledImageWidth) / 2f; float rx = (imageWidth + scaledImageWidth) / 2f; // If the image is more left than the left border if (dstRectPoints[0] < lx) { dx = (-1f) * dstRectPoints[0] + lx; // Else if the image is more right than the right border } else if (dstRectPoints[2] > rx) { dx = rx - dstRectPoints[2]; } } // If the scaled image height is greater than the mImageView height if (scaledImageHeight > imageHeight) { // If there is black at the top of the screen if (dstRectPoints[1] > 0f) { dy = (-1f) * dstRectPoints[1]; // Else if there is black at the bottom of the screen } else if (dstRectPoints[3] < imageHeight) { dy = imageHeight - dstRectPoints[3]; } } else { // Compute the top border and the bottom border // to center the image float ty = (imageHeight - scaledImageHeight) / 2f; float by = (imageHeight + scaledImageHeight) / 2f; // If the image is upper the top border if (dstRectPoints[1] < 0f) { dy = (-1f) * dstRectPoints[1] + ty; // Else if the image is under the bottom border } else if (dstRectPoints[3] > imageHeight) { dy = by - dstRectPoints[3]; } } // If there is translation to compute if (dx != 0f || dy != 0f) { // Add the translation mMatrix.postTranslate(dx, dy); // Set the image matrix setImageMatrix(mMatrix); } } } break; }; return true; // Do not draw } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Draw the image. */ public void draw() { // Declaration output pixels vector int[] outputPixels = new int[mImage.getDataLength()]; // Get the gray scale window width int windowWidth = mDICOMViewerData.getWindowWidth(); // Compute the window offset x the number of gray levels (256) int windowOffset = ((2 * mDICOMViewerData.getWindowCenter() - windowWidth)) / 2; switch(mDICOMViewerData.getCLUTMode()) { case CLUTMode.NORMAL: computeGrayscaleRGBImage(windowWidth, windowOffset, outputPixels); break; case CLUTMode.INVERSE: computeInverseGrayscaleRGBImage(windowWidth, windowOffset, outputPixels); break; case CLUTMode.RAINBOW: computeRainbowRGBImage(windowWidth, windowOffset, outputPixels); break; }; // Create the bitmap Bitmap imageBitmap = Bitmap.createBitmap(outputPixels, mImage.getWidth(), mImage.getHeight(), Bitmap.Config.ARGB_8888); // Set the image setImageBitmap(imageBitmap); } /** * Reset size and position of the image regarding * mScaleMode variable. */ public void resetSize() { switch(mDICOMViewerData.getScaleMode()) { case ScaleMode.FITIN: fitIn(); break; case ScaleMode.REALSIZE: realSize(); break; }; } /** * Fit the image in the screen */ public void fitIn() { // Get the image width and height int imageWidth = mImage.getWidth(); int imageHeight = mImage.getHeight(); // Variable declaration float dx = 0f; float dy = 0f; // Get the image matrix mMatrix.set(getImageMatrix()); // If the width of the ImageView is smaller than the // height, the image width is set to the ImageView width. if (getMeasuredWidth() <= getMeasuredHeight()) { float measuredWidth = getMeasuredWidth(); mScaleFactor = measuredWidth / imageWidth; // Translate to center the image. dy = ((float) getMeasuredHeight() - imageHeight * mScaleFactor) / 2f; // Else the image height is set to the ImageView height. } else { float measuredHeight = getMeasuredHeight(); mScaleFactor = measuredHeight / imageHeight; // Translate to center the image. dx = ((float) getMeasuredWidth() - imageWidth * mScaleFactor) / 2f; } // Set the transformation mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } /** * Display the real size of the image. */ public void realSize() { // Get the image width and height int imageWidth = mImage.getWidth(); int imageHeight = mImage.getHeight(); // Compute the translation float dx = ((float) getMeasuredWidth() - imageWidth) / 2f; float dy = ((float) getMeasuredHeight() - imageHeight) / 2f; mScaleFactor = 1f; mMatrix.set(getImageMatrix()); // Set the transformation mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } /** * Center the image in X and/or Y regarding * the dimension of the scaled image and the dimension * of the ImageView. */ public void center() { // Scaled image sizes. float scaledImageWidth = (float) mImage.getWidth() * mScaleFactor; float scaledImageHeight = (float) mImage.getHeight() * mScaleFactor; if (scaledImageWidth <= getMeasuredWidth() && scaledImageHeight <= getMeasuredHeight()) { // Compute the translation float dx = ((float) getMeasuredWidth() - scaledImageWidth) / 2f; float dy = ((float) getMeasuredHeight() - scaledImageHeight) / 2f; mMatrix.set(getImageMatrix()); mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } } /** * Set the LISA 16-Bit grayscale image. * * @param image */ public void setImage(LISAImageGray16Bit image) { mImage = image; } /** * Get the LISA 16-Bit grayscale image. * * @param image */ public LISAImageGray16Bit getImage() { return mImage; } /** * Get the image scaled width. * * @return Image scaled width. */ public float getScaledImageWidth() { return mImage.getWidth() * mScaleFactor; } /** * Get the image scaled height. * * @return Image scaled height. */ public float getScaledImageHeight() { return mImage.getHeight() * mScaleFactor; } /** * @return Transformation matrix. */ public Matrix getMatrix() { return mMatrix; } /** * Get the scale factor. * * @return Scale factor. */ public float getScaleFactor() { return mScaleFactor; } /** * Set the scale factor and apply * it on the image. */ public void setScaleFactor(float scaleFactor) { mScaleFactor = scaleFactor; } /** * Set the DICOMViewer data. * @param data */ public void setDICOMViewerData(DICOMViewerData data) { mDICOMViewerData = data; } // --------------------------------------------------------------- // - FUNCTIONS // --------------------------------------------------------------- /** * Init this object. */ private void init() { // Set the transformation attribute super.setScaleType(ImageView.ScaleType.MATRIX); mMatrix = new Matrix(); mScaleFactor = 1f; // TOUCH mTouchMode = TouchMode.NONE; mSavedMatrix = new Matrix(); mTouchTime = 0; mTouchStartPoint = new PointF(); mTouchMidPoint = new PointF(); mTouchOldDist = 1f; // Set the onTouchListener as this object setOnTouchListener(this); } /** * Compute the RGB image using a grayscale LUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeGrayscaleRGBImage(int windowWidth, int windowOffset, int[] outputPixels) { // The gray level of the current pixel int pixelGrayLevel = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { pixelGrayLevel = (256 * (mImageData[i] - windowOffset) / windowWidth); pixelGrayLevel = (pixelGrayLevel > 255) ? 255 : ((pixelGrayLevel < 0) ? 0 : pixelGrayLevel); outputPixels[i] = (0xFF << 24) | // alpha (pixelGrayLevel << 16) | // red (pixelGrayLevel << 8) | // green pixelGrayLevel; // blue } } /** * Compute the RGB image using an inverse grayscale LUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeInverseGrayscaleRGBImage(int windowWidth, int windowOffset, int[] outputPixels) { // The gray level of the current pixel int pixelGrayLevel = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { pixelGrayLevel = 255 - (256 * (mImageData[i] - windowOffset) / windowWidth); pixelGrayLevel = (pixelGrayLevel > 255) ? 255 : ((pixelGrayLevel < 0) ? 0 : pixelGrayLevel); outputPixels[i] = (0xFF << 24) | // alpha (pixelGrayLevel << 16) | // red (pixelGrayLevel << 8) | // green pixelGrayLevel; // blue } } /** * Compute the RGB image using a rainbow CLUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeRainbowRGBImage(int windowWidth, int windowMin, int[] outputPixels) { float[] pixelHSV = new float[3]; pixelHSV[0] = 0f; pixelHSV[1] = 240f; pixelHSV[2] = 1f; float mult = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { mult = (mImageData[i] - windowMin) / (float) windowWidth; mult = (mult > 1f) ? 1f : ((mult < 0f) ? 0f : mult); pixelHSV[0] = 300f - 360f * mult; pixelHSV[0] = (pixelHSV[0] > 300f) ? 300f : (pixelHSV[0] < -60f) ? 360-60f : pixelHSV[0]; pixelHSV[2] = 4f * mult; outputPixels[i] = Color.HSVToColor(0xFF, pixelHSV); } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <GrayScaleWindowView.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.view; import be.ac.ulb.lisa.idot.android.dicomviewer.R; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.ImageView; public class GrayscaleWindowView extends ImageView { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The LISA 16-Bit grayscale image. */ private LISAImageGray16Bit mImage = null; /** * DICOMViewer data. */ private DICOMViewerData mDICOMViewerData = null; /** * The window drawable int. */ private int mWindowDrawable = R.drawable.gradient_bar; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public GrayscaleWindowView(Context context) { super(context); } public GrayscaleWindowView(Context context, AttributeSet attrs) { super(context, attrs); } public GrayscaleWindowView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- @Override protected void onDraw(Canvas canvas) { if (mImage == null || mDICOMViewerData == null) return; int imageDataMax = mImage.getDataMax() + 1; imageDataMax = (imageDataMax) == 1 ? mImage.getGrayLevel() : imageDataMax; int windowWidth = mDICOMViewerData.getWindowWidth(); int windowCenter = mDICOMViewerData.getWindowCenter(); // TO CONFIGURE int stepLength = 20; int graduationSizeBig = 10; int graduationSizeNormal = 5; int fontSize = 10; // --------------------------------------- // VARIABLE DECLARATION // --------------------------------------- // ImageView size int width = getMeasuredWidth(); int height = getMeasuredHeight(); // ImageView half size int halfWidth = width / 2; int halfHeight = height / 2; // The half height of the scroll bar int scaleBarHalfHeight = height / 4; // TO have step of the length of stepLength scaleBarHalfHeight -= scaleBarHalfHeight % stepLength; // The coordinate of the scale bar int topScaleBar = halfHeight - scaleBarHalfHeight; int middleScaleBar = halfHeight; // TODO not necessary int bottomScaleBar = halfHeight + scaleBarHalfHeight; // The size of the graduations int endGraduationBig = halfWidth + graduationSizeBig; int endGraduationNormal = halfWidth + graduationSizeNormal; // The number of graduation int countGraduation = scaleBarHalfHeight / stepLength; // The fontsize offset to center the text int fontSizeOffset = fontSize / 2 - 1; // The half size of the grays scale window int windowHalfWidth = windowWidth * (2 * scaleBarHalfHeight) / imageDataMax/*mGrayLevel*/ /2; // The window center in ImageView int windowCenterCoordinate = bottomScaleBar - (2 * scaleBarHalfHeight) * windowCenter / imageDataMax/*mGrayLevel*/; // The grayscale window bounds int topWindowBounds = windowCenterCoordinate - windowHalfWidth; int bottomWindowBounds = windowCenterCoordinate + windowHalfWidth; // Paint Paint paint = new Paint(); // TODO we can do different paint object but we do not need it paint.setColor(0xaaff0000); paint.setAntiAlias(true); // --------------------------------------- // HISTOGRAM // --------------------------------------- int[] imageHistogram = mImage.getHistogramData(); int max = mImage.getHistogramMax(); max = max > 0 ? max : 1; if (imageHistogram != null) { int imgHistLength = imageDataMax < imageHistogram.length ? imageDataMax : imageHistogram.length; int step = imgHistLength / scaleBarHalfHeight / 2; int upperBounds = (2 * scaleBarHalfHeight) - 1; for (int i = 0; i <= upperBounds; i++) { int count = 0; int upperStep = (i == upperBounds) ? (imgHistLength - i * step) : step; for (int j=0; j < upperStep; j++) { int index = (i * step) + j; if (index < imgHistLength) count += imageHistogram[index]; } long histBarWidth = (long) halfWidth + (long) graduationSizeBig * 50 * (long) count / (long) max; canvas.drawLine(halfWidth, bottomScaleBar - i, histBarWidth, bottomScaleBar - i, paint); } } paint.setColor(0xff77c1fb); // --------------------------------------- // GRAYSCALE WINDOW // --------------------------------------- // Set the paint to a stroke paint type paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); // Get the grayscale bitmap Bitmap grayscaleBitmap = BitmapFactory.decodeResource(this.getResources(), mWindowDrawable); // Compute the destination rect for the bitmap Rect destRect = new Rect( halfWidth - 15, topWindowBounds, halfWidth - 5, bottomWindowBounds); // Draw the bitmap and a rect around canvas.drawBitmap(grayscaleBitmap, null, destRect, null); canvas.drawRect(destRect, paint); // Set the paint to a fill paint with // a text align right and its size set to fontSize paint.setStrokeWidth(0); paint.setStyle(Paint.Style.FILL); paint.setTextAlign(Align.RIGHT); paint.setTextSize(fontSize); // Draw the upper value canvas.drawText(String.valueOf(windowCenter + windowWidth / 2 - 1024), halfWidth - 5, topWindowBounds - 5, paint); // Draw the bottom value canvas.drawText(String.valueOf(windowCenter - windowWidth / 2 - 1024), halfWidth - 5, bottomWindowBounds + 5 + fontSize, paint); // Draw the center arrow canvas.drawText(">", halfWidth - 15 - 5, windowCenterCoordinate + fontSizeOffset, paint); // Change text align to left paint.setTextAlign(Align.LEFT); // Change the center value canvas.drawText(String.valueOf(windowCenter - 1024), endGraduationBig + 5, windowCenterCoordinate + fontSizeOffset, paint); // --------------------------------------- // GRAYSCALE SCALE // --------------------------------------- // Draw the vertical line canvas.drawLine(halfWidth, topScaleBar, halfWidth, bottomScaleBar, paint); // Draw topScaleBar graduation and text canvas.drawLine(halfWidth, topScaleBar, endGraduationBig, topScaleBar, paint); canvas.drawText(String.valueOf(/*mGrayLevel*/imageDataMax - 1 - 1024), endGraduationBig + 5, topScaleBar + fontSizeOffset, paint); // Draw intermediate graduations for (int i = 1; i < countGraduation; i++) { // The middle graduation'll be drawn => < and not <= countGraduation int yCoordinate = topScaleBar + i * stepLength; canvas.drawLine(halfWidth, yCoordinate, endGraduationNormal, yCoordinate, paint); } // Draw middle graduation canvas.drawLine(halfWidth, middleScaleBar, endGraduationBig, middleScaleBar, paint); // Draw intermediate graduations for (int i = 1; i < countGraduation; i++) { // The bottom graduation'll be drawn => < and not <= countGraduation int yCoordinate = middleScaleBar + i * stepLength; canvas.drawLine(halfWidth, yCoordinate, endGraduationNormal, yCoordinate, paint); } // Draw bottomScaleBar graduation and text canvas.drawLine(halfWidth, bottomScaleBar, endGraduationBig, bottomScaleBar, paint); canvas.drawText("-1024", endGraduationBig + 5, bottomScaleBar + fontSizeOffset, paint); } /** * Set the LISA 16-Bit grayscale image. * * @param image */ public void setImage(LISAImageGray16Bit image) { mImage = image; } /** * Set the DICOMViewer data. * * @param data */ public void setDICOMViewerData(DICOMViewerData data) { mDICOMViewerData = data; } /** * Set the CLUT Mode. * * This must be set each time, the CLUT mode is changed. * * @param clutMode */ public void updateCLUTMode() { if (mDICOMViewerData == null) return; switch(mDICOMViewerData.getCLUTMode()) { default: case CLUTMode.NORMAL: mWindowDrawable = R.drawable.gradient_bar; break; case CLUTMode.INVERSE: mWindowDrawable = R.drawable.gradient_inverse_bar; break; case CLUTMode.RAINBOW: mWindowDrawable = R.drawable.gradient_color_bar; break; }; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageCacher.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.thread; import java.io.File; import java.io.FileNotFoundException; import android.os.Handler; import android.os.Message; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.file.DICOMFileFilter; import be.ac.ulb.lisa.idot.dicom.file.DICOMImageReader; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitWriter; /** * DICOM image cacher that cached DICOM image in LISA * 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public final class DICOMImageCacher extends Thread { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The handler to send message to. */ private final Handler mHandler; /** * The directory containing the DICOM image files. */ private final File mTopDirectory; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageCacher(Handler handler, String topDirectoryName) throws FileNotFoundException { // Set the handler if (handler == null) throw new NullPointerException("The handler is null"); mHandler = handler; // Set the top directory mTopDirectory = new File(topDirectoryName); if (!mTopDirectory.exists()) throw new FileNotFoundException("The directory (" + topDirectoryName + ") doesn't exist."); } public DICOMImageCacher(Handler handler, File topDirectory) throws FileNotFoundException { // Set the handler if (handler == null) throw new NullPointerException("The handler is null"); mHandler = handler; // Set the top directory if (!topDirectory.exists()) throw new FileNotFoundException("The directory (" + topDirectory.getPath() + ") doesn't exist."); mTopDirectory = topDirectory; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- public void run() { // Get the Files' list for the mTopDirectory File[] children = mTopDirectory.listFiles(new DICOMFileFilter()); // If the children array is null if (children == null) { mHandler.sendEmptyMessage(ThreadState.UNCATCHABLE_ERROR_OCCURRED); return; } // Get the message from the handler and send // the children list length Message message = mHandler.obtainMessage(); message.what = ThreadState.STARTED; message.arg1 = children.length; mHandler.sendMessage(message); try { for (int i = 0; i < children.length; i++) { // Load the children if (loadImage(children[i])) { // Send a progression update message message = mHandler.obtainMessage(); message.what = ThreadState.PROGRESSION_UPDATE; message.arg1 = i + 1; mHandler.sendMessage(message); } else { // Send a catchable error occurred message = mHandler.obtainMessage(); message.what = ThreadState.CATCHABLE_ERROR_OCCURRED; message.arg1 = i + 1; message.obj = children[i].getName(); mHandler.sendMessage(message); } // Hint the garbage collector System.gc(); } } catch (OutOfMemoryError ex) { // If the image can be loaded because an out of // memory error occurred, display it System.gc(); mHandler.sendEmptyMessage(ThreadState.OUT_OF_MEMORY); } // Send that the thread is finished mHandler.sendEmptyMessage(ThreadState.FINISHED); // Hint the garbage collector a last time System.gc(); } // --------------------------------------------------------------- // - <static> FUNCTIONS // --------------------------------------------------------------- /** * Load an image. * * @param currentFile * @return True if the image is cached, false otherwise. */ private static boolean loadImage(File currentFile) { // If the file doesn't exist return false if (!currentFile.exists()) return false; // Set the current LISA 16-Bit grayscale image File currentLISAFile = new File(currentFile + ".lisa"); // If current LISA 16-Bit grayscale image exists, // don't create it if (currentLISAFile.exists()) return true; // Else write it try { DICOMImageReader dicomFileReader = new DICOMImageReader(currentFile); DICOMImage dicomImage = dicomFileReader.parse(); dicomFileReader.close(); // Compressed file are not supported => do not cached it. if (dicomImage.isUncompressed()) { // Write the image LISAImageGray16BitWriter out = new LISAImageGray16BitWriter(currentFile + ".lisa"); out.write(dicomImage.getImage()); out.flush(); out.close(); } dicomImage = null; return true; } catch (Exception ex) { return false; } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ThreadState.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.thread; /** * Encapsulate thread states that correspond to the wath of * the Handler. * * @author Pierre Malarme * @version 1.0 * */ public class ThreadState { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- /** * Thread has catch a OutOfMemoryError exception. */ public static final short OUT_OF_MEMORY = 0; /** * The thread is started. */ public static final short STARTED = 1; /** * The thread is finished. */ public static final short FINISHED = 2; /** * The thread progression update. */ public static final short PROGRESSION_UPDATE = 3; /** * An error occurred while the thread running that cannot * be managed. */ public static final short UNCATCHABLE_ERROR_OCCURRED = 4; /** * An error occurred while the thread running that can be * managed or ignored. */ public static final short CATCHABLE_ERROR_OCCURRED = 5; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ScaleMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class ScaleMode contains the image scale modes. * * @author Pierre Malarme * @version 1.0 * */ public final class ScaleMode { /** * Fit in. */ public static final short FITIN = 0; /** * Image real size (1:1). */ public static final short REALSIZE = 1; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ToolMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class ToolMode contains the tool modes. * * @author Pierre Malarme * @version 1.0 * */ public final class ToolMode { /** * Change the size and the position of the image. */ public static final short DIMENSION = 0; /** * Change the grayscale window center and position. */ public static final short GRAYSCALE = 1; /** * Rotate the image. */ public static final short ROTATION = 2; /** * Crop the image. */ public static final short CROP = 3; /** * Make measurement on the image. */ public static final short MEASURE = 4; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <CLUTMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class CLUTMode contains the LUT/CLUT modes. * * @author Pierre Malarme * @version 1.0 * */ public final class CLUTMode { /** * Normal grayscale LUT. */ public static final short NORMAL = 0; /** * Inverse LUT. */ public static final short INVERSE = 1; /** * Color rainbow CLUT. */ public static final short RAINBOW = 2; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <TouchMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class TouchMode contains the touch modes. * * @author Pierre Malarme * @version 1.0 * */ public final class TouchMode { /** * No touch mode. */ public static final short NONE = 0; /** * One finger mode. */ public static final short ONE_FINGER = 1; /** * Two fingers mode. */ public static final short TWO_FINGERS = 2; /** * Three fingers mode. */ public static final short THREE_FINGERS = 3; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <GrayscaleWindowPreset.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.preset; /** * The class WindowPreset contains the image window presets. * * @author Pierre Malarme * @version 1.0 * */ public final class GrayscaleWindowPreset { /** * Set the window window to the CT Bone preset. */ public static final short CT_BONE = 1; /** * Set the window window to the CT Crane preset. */ public static final short CT_CRANE = 2; /** * Set the window window to the CT Lung preset. */ public static final short CT_LUNG = 3; /** * Set the window window to the CT Abdomen preset. */ public static final short CT_ABDOMEN = 4; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <Geometry.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.commons; import android.graphics.PointF; import android.util.FloatMath; /** * The class Geometry contains geometry functions. * * @author Pierre Malarme * * @version 1.0 * */ public class Geometry { // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * Get the euclidian distance between P1 (x1, y1) and P2 (x2, y2). * * @param x1 The x-coordinate of the P1. * @param y1 The y-coordinate of the P1. * @param x2 The x-coordinate of the P2. * @param y2 The y-coordinate of the P2. * @return The euclidian distance between (x1, y1) and (x2, y2). */ public static final float euclidianDistance(float x1, float y1, float x2, float y2) { // Compute coordinate subtraction float x = x2 - x1; float y = y2 - y1; // Compute the euclidian distance return FloatMath.sqrt(x * x + y * y); } /** * Get the middle point between P1 (x1, y1) and P2 (x2, y2). * * @param x1 The x-coordinate of the P1. * @param y1 The y-coordinate of the P1. * @param x2 The x-coordinate of the P2. * @param y2 The y-coordinate of the P2. * @return The middle point between (x1, y1) and (x2, y2). */ public static final PointF midPoint(float x1, float y1, float x2, float y2) { // Compute coordinate addition float x = x1 + x2; float y = y1 + y2; return new PointF(x / 2f, y / 2f); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <Memory.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.commons; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * Implements functions useful to check * Memory usage. * * @author Pierre Malarme * @version 1.0 * */ public class Memory { // --------------------------------------------------------------- // + <static> FUNCTION // --------------------------------------------------------------- /** * Function that get the size of an object. * * @param object * @return Size in bytes of the object or -1 if the object * is null. * @throws IOException */ public static final int sizeOf(Object object) throws IOException { if (object == null) return -1; // Special output stream use to write the content // of an output stream to an internal byte array. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Output stream that can write object ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // Write object and close the output stream objectOutputStream.writeObject(object); objectOutputStream.flush(); objectOutputStream.close(); // Get the byte array byte[] byteArray = byteArrayOutputStream.toByteArray(); // TODO can the toByteArray() method return a // null array ? return byteArray == null ? 0 : byteArray.length; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16Bit.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.data; /** * LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.O * */ public class LISAImageGray16Bit { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Image width that correspond to * the number of column. */ protected short mWidth = 0; /** * Image height that correspond to * the number of row. */ protected short mHeight = 0; /** * Image data. */ protected int[] mData = null; /** * Maximum value of the data. */ protected int mDataMax = 0; /** * The histogram data. */ protected int[] mHistogramData = null; /** * Maximum value of the Histogram. */ protected int mHistogramMax = 0; /** * The total number of gray level. */ protected int mGrayLevel = 4096; /** * Window width. */ protected int mWindowWidth = -1; /** * Window center */ protected int mWindowCenter = -1; /** * Image orientation. */ protected float[] mImageOrientation = new float[6]; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public LISAImageGray16Bit() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return Image width. */ public short getWidth() { return mWidth; } /** * @return Image height. */ public short getHeight() { return mHeight; } /** * @return Image data. */ public int[] getData() { return mData; } /** * @return Image data length. */ public int getDataLength() { return mData == null ? 0 : mData.length; } /** * @return Maximum data value. */ public int getDataMax() { return mDataMax; } /** * @return Histogram data. */ public int[] getHistogramData() { return mHistogramData; } /** * @return Histogram length. */ public int getHistogramLength() { return mHistogramData == null ? 0 : mHistogramData.length; } /** * @return Histogram max value. */ public int getHistogramMax() { return mHistogramMax; } /** * @return The number of gray level. */ public int getGrayLevel() { return mGrayLevel; } /** * @return Window width. */ public int getWindowWidth() { return mWindowWidth; } /** * @return Window Center */ public int getWindowCenter() { return mWindowCenter; } /** * @return Window offset. */ public int getWindowOffset() { return ((2 * mWindowCenter - mWindowWidth)) / 2; } /** * @return Image orientation. */ public float[] getImageOrientation() { return mImageOrientation; } /** * @param width The width to set. */ public void setWidth(short width) { mWidth = width; } /** * @param height The height to set. */ public void setHeight(short height) { mHeight = height; } /** * @param data The data to set. */ public void setData(int[] data) { mData = data; } /** * @param dataMax The dataMax to set. */ public void setDataMax(int dataMax) { mDataMax = dataMax; } /** * @param histogramData The histogram data to set. */ public void setHistogramData(int[] histogramData) { mHistogramData = histogramData; } /** * @param histogramMax The histogram max value to set. */ public void setHistogramMax(int histogramMax) { mHistogramMax = histogramMax; } /** * @param grayLevel The maximum number of gray level to set. */ public void setGrayLevel(int grayLevel) { mGrayLevel = grayLevel; } /** * @param windowWidth The window width to set. */ public void setWindowWidth(int windowWidth) { mWindowWidth = windowWidth; } /** * @param windowCenter The window center to set. */ public void setWindowCenter(int windowCenter) { mWindowCenter = windowCenter; } /** * @param imageOrientation The image orientation array. */ public void setImageOrientation(float[] imageOrientation) { if (imageOrientation == null) return; if (imageOrientation.length == 6) mImageOrientation = imageOrientation; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16BitWriter.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.file; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Writer for LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public class LISAImageGray16BitWriter extends FileOutputStream { // --------------------------------------------------------------- // - <static> VARIABLE // --------------------------------------------------------------- protected static final String PREFIX = "LISAGRAY0016"; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public LISAImageGray16BitWriter(File file) throws FileNotFoundException { super(file); } public LISAImageGray16BitWriter(FileDescriptor fd) { super(fd); } public LISAImageGray16BitWriter(String filename) throws FileNotFoundException { super(filename); } // --------------------------------------------------------------- // # CONSTRUCTORS // --------------------------------------------------------------- /** * Function private to forbid its use. * * @param file * @param append * @throws FileNotFoundException */ private LISAImageGray16BitWriter(File file, boolean append) throws FileNotFoundException { super(file, append); } /** * Function private to forbid its use. * * @param filename * @param append * @throws FileNotFoundException */ private LISAImageGray16BitWriter(String filename, boolean append) throws FileNotFoundException { super(filename, append); } // --------------------------------------------------------------- // + FUNCTION // --------------------------------------------------------------- /** * Write a LISA 16-Bit grayscale image. * @param image A LISA 16-bit grayscale image. * @throws IOException */ public void write(LISAImageGray16Bit image) throws IOException { if (image == null) throw new NullPointerException("Image is null"); try { // PREFIX // Write the prefix write(PREFIX.getBytes()); // IMAGE SIZE // Write width writeInt16(image.getWidth()); // Write height writeInt16(image.getHeight()); // GRAY LEVELS AND WINDOW // Write the gray levels writeLong32(image.getGrayLevel()); // Write window width writeInt16(image.getWindowWidth()); // Write window center writeInt16(image.getWindowCenter()); // Write the image orientation writeImageOrientation(image); // Write image length writeLong32(image.getDataLength()); // Write the image data writeInt16Array(image.getData()); } catch (IOException e) { throw new IOException("Cannot open write LISA image.\n" + e.getMessage()); } } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Write an integer on 2 bytes. * @param value Integer value. * @throws IOException */ protected final void writeInt16(int value) throws IOException { byte[] int16Bytes = new byte[2]; int16Bytes[0] = (byte) ((value >> 8) & 0xff); int16Bytes[1] = (byte) ((value) & 0xff); super.write(int16Bytes); } /** * Write a long on 4 bytes. * * If the value correspond to the image length the maximum value * must be set as Integer.MAX_VALUE due to java array limitation: * the maximum length is the maximum integer value. * * @param value Long value. * @throws IOException */ protected final void writeLong32(long value) throws IOException { byte[] long32Bytes = new byte[4]; long32Bytes[0] = (byte) ((value >> 24) & 0xff); long32Bytes[1] = (byte) ((value >> 16) & 0xff); long32Bytes[2] = (byte) ((value >> 8) & 0xff); long32Bytes[3] = (byte) ((value) & 0xff); super.write(long32Bytes); } /** * Write an array of integer. * * Each integer value is coded in 2 bytes. * * @param intArray Array of integer values. * @throws IOException */ protected final void writeInt16Array(int[] intArray) throws IOException { byte[] intArrayBytes = new byte[intArray.length * 2]; for (int i = 0; i < intArray.length; i ++) { intArrayBytes[(2 * i) + 0] = (byte) ((intArray[i] >> 8) & 0xff); intArrayBytes[(2 * i) + 1] = (byte) ((intArray[i]) & 0xff); } super.write(intArrayBytes); } /** * Write an array of float values. * * @param floatArray * @throws IOException */ protected final void writeFloatArray(float[] floatArray) throws IOException { for (int i = 0; i < floatArray.length; i++) { int binaryValue = Float.floatToRawIntBits(floatArray[i]); writeLong32(binaryValue); } } /** * Write the image orientation float array. * * @param image * @throws IOException */ protected final void writeImageOrientation(LISAImageGray16Bit image) throws IOException { float[] imageOrientation = image.getImageOrientation(); // Check if the array is null or not null imageOrientation = (imageOrientation == null) ? new float[6] : imageOrientation; writeFloatArray(imageOrientation); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16BitReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.file; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Reader for LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public class LISAImageGray16BitReader extends FileInputStream { // --------------------------------------------------------------- // - <static> VARIABLE // --------------------------------------------------------------- protected static final String PREFIX = "LISAGRAY0016"; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public LISAImageGray16BitReader(File file) throws FileNotFoundException { super(file); } public LISAImageGray16BitReader(FileDescriptor fd) { super(fd); } public LISAImageGray16BitReader(String fileName) throws FileNotFoundException { super(fileName); } // --------------------------------------------------------------- // + FUCTIONS // --------------------------------------------------------------- public synchronized LISAImageGray16Bit parseImage() throws IOException, EOFException { // Check the prefix if (!PREFIX.equals(readASCII(PREFIX.length()))) throw new IOException("This is not a LISA 16-Bit" + "grayscale image"); try { byte[] buffer = new byte[available()]; read(buffer); // Create the image LISAImageGray16Bit image = new LISAImageGray16Bit(); // Get the image attributes int byteOffset = 0; // Image Width image.setWidth((short) ((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Image Height image.setHeight((short) ((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Image gray levels count int grayLevel = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; image.setGrayLevel(grayLevel); // Window width image.setWindowWidth(((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Window Height image.setWindowCenter(((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff)));; byteOffset += 2; // Image orientation float[] imageOrientation = new float[6]; for (int i = 0; i < 6; i++) { int binaryValue = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; imageOrientation[i] = Float.intBitsToFloat(binaryValue); } image.setImageOrientation(imageOrientation); // Data length int dataLength = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; // Compute the histogram data and max // and the image data and max int[] imageData = new int[dataLength]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; for (int i = 0; i < dataLength; i ++) { imageData[i] = (buffer[byteOffset] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff); byteOffset += 2; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } image.setData(imageData); image.setDataMax(imageDataMax); image.setHistogramData(imageHistogram); image.setHistogramMax(imageHistogramMax); return image; } catch (EOFException ex) { throw new EOFException("Reached the end of the file before " + "reading all data. \n" + ex.getMessage()); } catch (IOException ex) { throw new IOException("Cannot parse the LISA Image " + "grayscale 16-Bit. \n" + ex.getMessage()); } } // --------------------------------------------------------------- // # FUNCTION // --------------------------------------------------------------- /** * Read byte[length] as ASCII. * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected synchronized final String readASCII(int length) throws IOException, EOFException { byte[] ASCIIbyte = new byte[length]; if (read(ASCIIbyte) == -1) throw new IOException(); // To avoid the null char : ASCII(0) String toReturnString = new String(ASCIIbyte, "ASCII"); for (int i = 0; i < length; i++) if (ASCIIbyte[i] == 0x00) return toReturnString.substring(0, i); return toReturnString; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMItem.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM item. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMItem extends DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * The map of DICOMElement children. */ protected Map<Integer, DICOMElement> mChildrenMap; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMItem() { super(DICOMTag.createDICOMTag(0xfffee000), null); mChildrenMap = new HashMap<Integer, DICOMElement>(); } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Add a DICOMElement child to the map. * * @param tag * @param element */ public void addChild(int tag, DICOMElement element) { mChildrenMap.put(tag, element); } /** * Get a DICOMElement from the map. * * @param tag The tag integer value of the child. * @return DICOMElement or null if it does * not exist. */ public DICOMElement getChild(int tag) { return mChildrenMap.get(tag); } /** * @return DICOMElement children map. */ public Map<Integer, DICOMElement> getChildrenMap() { return mChildrenMap; } /** * @return Number of DICOMElement children. */ public int getChildrenCount() { return mChildrenMap.size(); } /** * @param tag * @return True if there is a child with is DICOMTag * integer value set as tag. False otherwise. */ public boolean containsChild(int tag) { return mChildrenMap.containsKey(tag); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMFile.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file containing a meta information object (DICOMMetaInformation) * and a DICOM body object (DICOMBody). * * @author Pierre Malarme * @version 1.0 * */ public class DICOMFile { // --------------------------------------------------------------- // - <final> VARIABLES // --------------------------------------------------------------- /** * DICOM meta information. */ protected final DICOMMetaInformation mMetaInformation; /** * DICOM body. */ protected final DICOMBody mBody; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMFile(DICOMMetaInformation metaInformation, DICOMBody body) { mMetaInformation = metaInformation; mBody = body; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return DICOM meta information. */ public DICOMMetaInformation getMetaInformation() { return mMetaInformation; } /** * @return DICOM body. */ public DICOMBody getBody() { return mBody; } /** * @return True if the file has DICOM meta information. * False otherwise. */ public boolean hasMetaInformation() { return mMetaInformation != null; } /** * @return True if the file has DICOM body. * False otherwise. */ public boolean hasBody() { return mBody != null; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMMetaInformation.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file meta informations. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMMetaInformation { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Length of the meta information. */ private long mGroupLength = -1; /** * SOP Class UID. */ private String mSOPClassUID = ""; /** * SOP Instance UID. */ private String mSOPInstanceUID = ""; /** * Transfer syntax UID. * */ private String mTransferSyntaxUID = ""; /** * Implementation Class UID. */ private String mImplementationClassUID = ""; /** * Implementation version name. */ private String mImplementationVersionName = ""; /** * Application Entity Title. */ private String mAET = ""; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMMetaInformation() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- // Methods generated by Eclipse. /** * @return the mGroupLength */ public long getGroupLength() { return mGroupLength; } /** * @return the mSOPClassUID */ public String getSOPClassUID() { return mSOPClassUID; } /** * @return the mSOPInstanceUID */ public String getSOPInstanceUID() { return mSOPInstanceUID; } /** * @return the mTransferSyntaxUID */ public String getTransferSyntaxUID() { return mTransferSyntaxUID; } /** * @return the mImplementationClassUID */ public String getImplementationClassUID() { return mImplementationClassUID; } /** * @return the mImplementationVersionName */ public String getImplementationVersionName() { return mImplementationVersionName; } /** * @return the mAET */ public String getAET() { return mAET; } /** * @param mGroupLength the mGroupLength to set */ public void setGroupLength(long mGroupLength) { this.mGroupLength = mGroupLength; } /** * @param mSOPClassUID the mSOPClassUID to set */ public void setSOPClassUID(String mSOPClassUID) { this.mSOPClassUID = mSOPClassUID; } /** * @param mSOPInstanceUID the mSOPInstanceUID to set */ public void setSOPInstanceUID(String mSOPInstanceUID) { this.mSOPInstanceUID = mSOPInstanceUID; } /** * @param mTransferSyntaxUID the mTransferSyntaxUID to set */ public void setTransferSyntaxUID(String mTransferSyntaxUID) { this.mTransferSyntaxUID = mTransferSyntaxUID; } /** * @param mImplementationClassUID the mImplementationClassUID to set */ public void setImplementationClassUID(String mImplementationClassUID) { this.mImplementationClassUID = mImplementationClassUID; } /** * @param mImplementationVersionName the mImplementationVersionName to set */ public void setImplementationVersionName(String mImplementationVersionName) { this.mImplementationVersionName = mImplementationVersionName; } /** * @param mAET the mAET to set */ public void setAET(String mAET) { this.mAET = mAET; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImage.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * DICOM image containing a compression status, a meta information * object (DICOMMetaInformation), a DICOM body object (DICOMBody) * and a LISA 16-Bit grayscale image (LISAImageGray16Bit). * * @author Pierre Malarme * @version 1.0 * */ public class DICOMImage extends DICOMFile { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- /** * Unknown image status. */ public static final short UNKNOWN_STATUS = 0; /** * Uncompressed image status. */ public static final short UNCOMPRESSED = 1; /** * Compressed image status. */ public static final short COMPRESSED = 2; // --------------------------------------------------------------- // - <final> VARIABLES // --------------------------------------------------------------- /** * LISA 16-Bit grayscale image. */ private final LISAImageGray16Bit mImage; /** * The compression status. */ private final short mCompressionStatus; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMImage(DICOMMetaInformation metaInformation, DICOMBody body, LISAImageGray16Bit image, short compressionStatus) { super(metaInformation, body); mImage = image; mCompressionStatus = compressionStatus; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return DICOM image. */ public LISAImageGray16Bit getImage() { return mImage; } /** * @return Compression status. */ public short getCompressionStatus() { return mCompressionStatus; } /** * @return Check if the image is uncompressed. */ public boolean isUncompressed() { return mCompressionStatus == UNCOMPRESSED; } /** * @return Check if the image as data. */ public boolean hasImageData() { if (mImage == null) return false; return mImage.getData() != null; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMBody.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file meta informations. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMBody { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Specific character set. */ private String mSpecificCharset = "ASCII"; /** * Image type. */ private String mImageType = ""; /** * Date of the study. */ private String mStudyDate = ""; /** * Time of the study. */ private String mStudyTime = ""; /** * Modality. */ private String mModality = ""; /** * Manufacturer. */ private String mManufacturer = ""; /** * Institution name. */ private String mInstitutionName = ""; /** * Referring physician name. */ private String mReferringPhysicianName = ""; /** * Station name. */ private String mStationName = ""; /** * Study description. */ private String mStudyDescription = ""; /** * Department name. */ private String mDepartmenName = ""; /** * Manufacturer model name. */ private String mManufacturerModelName = ""; /** * Patient name. */ private String mPatientName = ""; /** * Patient ID. */ private String mPatientId = ""; /** * Protocol name. */ private String mProtocolName = ""; /** * Patient position. */ private String mPatientPosition = ""; /** * Study ID. */ private int mStudyId = -1; /** * Series number. */ private int mSeriesNumber = -1; /** * Instance number. */ private int mInstanceNumber = -1; /** * Sample per pixel. */ private int mSamplesPerPixel = 1; /** * Photometric interpretation. */ private String mPhotometricInterpretation = "MONOCHROME2"; /** * Bits allocated. */ private int mBitsAllocated = 0; /** * Bits stored; */ private int mBitsStored = 0; /** * High bit. */ private int mHightBit = 0; /** * Pixel representation. * * 0 = unsigned, 1 = signed. * */ private int mPixelRepresentation = 1; /** * Requesting physician. */ private String mRequestingPhysician = ""; /** * Requested procedure. */ private String mRequestedProcedureDescription = ""; /** * Scheduled procedure step description. */ private String mScheduledProcedureStepDescription = ""; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMBody() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- // Methods generated by Eclipse. /** * @return the mSpecificCharset */ public String getSpecificCharset() { return mSpecificCharset; } /** * @return the mImageType */ public String getImageType() { return mImageType; } /** * @return the mStudyDate */ public String getStudyDate() { return mStudyDate; } /** * @return the mStudyTime */ public String getStudyTime() { return mStudyTime; } /** * @return the mModality */ public String getModality() { return mModality; } /** * @return the mManufacturer */ public String getManufacturer() { return mManufacturer; } /** * @return the mInstitutionName */ public String getInstitutionName() { return mInstitutionName; } /** * @return the mReferringPhysicianName */ public String getReferringPhysicianName() { return mReferringPhysicianName; } /** * @return the mStationName */ public String getStationName() { return mStationName; } /** * @return the mStudyDescription */ public String getStudyDescription() { return mStudyDescription; } /** * @return the mDepartmenName */ public String getDepartmenName() { return mDepartmenName; } /** * @return the mManufacturerModelName */ public String getManufacturerModelName() { return mManufacturerModelName; } /** * @return the mPatientName */ public String getPatientName() { return mPatientName; } /** * @return the mPatientID */ public String getPatientId() { return mPatientId; } /** * @return the mProtocolName */ public String getProtocolName() { return mProtocolName; } /** * @return the mPatientPosition */ public String getPatientPosition() { return mPatientPosition; } /** * @return the mStudyId */ public int getStudyId() { return mStudyId; } /** * @return the mSeriesNumber */ public int getSeriesNumber() { return mSeriesNumber; } /** * @return the mInstanceNumber */ public int getInstanceNumber() { return mInstanceNumber; } /** * @return the mSamplePerPixel */ public int getSamplesPerPixel() { return mSamplesPerPixel; } /** * @return the mPhotometricInterpretation */ public String getPhotometricInterpretation() { return mPhotometricInterpretation; } /** * @return the mBitsAllocated */ public int getBitsAllocated() { return mBitsAllocated; } /** * @return the mBitsStored */ public int getBitsStored() { return mBitsStored; } /** * @return the mHightBit */ public int getHightBit() { return mHightBit; } /** * @return the mPixelRepresentation */ public int getPixelRepresentation() { return mPixelRepresentation; } /** * @return the mRequestingPhysician */ public String getRequestingPhysician() { return mRequestingPhysician; } /** * @return the mRequestedProcedureDescription */ public String getRequestedProcedureDescription() { return mRequestedProcedureDescription; } /** * @return the mScheduledProcedureStepDescription */ public String getScheduledProcedureStepDescription() { return mScheduledProcedureStepDescription; } /** * @param mSpecificCharset the mSpecificCharset to set */ public void setSpecificCharset(String mSpecificCharset) { this.mSpecificCharset = mSpecificCharset; } /** * @param mImageType the mImageType to set */ public void setImageType(String mImageType) { this.mImageType = mImageType; } /** * @param mStudyDate the mStudyDate to set */ public void setStudyDate(String mStudyDate) { this.mStudyDate = mStudyDate; } /** * @param mStudyTime the mStudyTime to set */ public void setStudyTime(String mStudyTime) { this.mStudyTime = mStudyTime; } /** * @param mModality the mModality to set */ public void setModality(String mModality) { this.mModality = mModality; } /** * @param mManufacturer the mManufacturer to set */ public void setManufacturer(String mManufacturer) { this.mManufacturer = mManufacturer; } /** * @param mInstitutionName the mInstitutionName to set */ public void setInstitutionName(String mInstitutionName) { this.mInstitutionName = mInstitutionName; } /** * @param mReferingPhysicianName the mReferingPhysicianName to set */ public void setReferringPhysicianName(String mReferringPhysicianName) { this.mReferringPhysicianName = mReferringPhysicianName; } /** * @param mStationName the mStationName to set */ public void setStationName(String mStationName) { this.mStationName = mStationName; } /** * @param mStudyDescription the mStudyDescription to set */ public void setStudyDescription(String mStudyDescription) { this.mStudyDescription = mStudyDescription; } /** * @param mDepartmenName the mDepartmenName to set */ public void setDepartmenName(String mDepartmenName) { this.mDepartmenName = mDepartmenName; } /** * @param mManufacturerModelName the mManufacturerModelName to set */ public void setManufacturerModelName(String mManufacturerModelName) { this.mManufacturerModelName = mManufacturerModelName; } /** * @param mPatientName the mPatientName to set */ public void setPatientName(String mPatientName) { this.mPatientName = mPatientName; } /** * @param mPatientID the mPatientID to set */ public void setPatientId(String mPatientId) { this.mPatientId = mPatientId; } /** * @param mProtocolName the mProtocolName to set */ public void setProtocolName(String mProtocolName) { this.mProtocolName = mProtocolName; } /** * @param mPatientPosition the mPatientPosition to set */ public void setPatientPosition(String mPatientPosition) { this.mPatientPosition = mPatientPosition; } /** * @param mStudyId the mStudyId to set */ public void setStudyId(int mStudyId) { this.mStudyId = mStudyId; } /** * @param mSeriesNumber the mSeriesNumber to set */ public void setSeriesNumber(int mSeriesNumber) { this.mSeriesNumber = mSeriesNumber; } /** * @param mInstanceNumber the mInstanceNumber to set */ public void setInstanceNumber(int mInstanceNumber) { this.mInstanceNumber = mInstanceNumber; } /** * @param mSamplePerPixel the mSamplePerPixel to set */ public void setSamplesPerPixel(int mSamplesPerPixel) { this.mSamplesPerPixel = mSamplesPerPixel; } /** * @param mPhotometricInterpretation the mPhotometricInterpretation to set */ public void setPhotometricInterpretation(String mPhotometricInterpretation) { this.mPhotometricInterpretation = mPhotometricInterpretation; } /** * @param mBitsAllocated the mBitsAllocated to set */ public void setBitsAllocated(int mBitsAllocated) { this.mBitsAllocated = mBitsAllocated; } /** * @param mBitsStored the mBitsStored to set */ public void setBitsStored(int mBitsStored) { this.mBitsStored = mBitsStored; } /** * @param mHightBit the mHightBit to set */ public void setHightBit(int mHightBit) { this.mHightBit = mHightBit; } /** * @param mPixelRepresentation the mPixelRepresentation to set */ public void setPixelRepresentation(int mPixelRepresentation) { this.mPixelRepresentation = mPixelRepresentation; } /** * @param mRequestingPhysician the mRequestingPhysician to set */ public void setRequestingPhysician(String mRequestingPhysician) { this.mRequestingPhysician = mRequestingPhysician; } /** * @param mRequestedProcedureDescription the mRequestedProcedureDescription to set */ public void setRequestedProcedureDescription( String mRequestedProcedureDescription) { this.mRequestedProcedureDescription = mRequestedProcedureDescription; } /** * @param mScheduledProcedureStepDescription the mScheduledProcedureStepDescription to set */ public void setScheduledProcedureStepDescription( String mScheduledProcedureStepDescription) { this.mScheduledProcedureStepDescription = mScheduledProcedureStepDescription; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMBufferedInputStream.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.BinaryInputStream // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.BufferedInputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * DICOM BufferedInputStream needed to read a DICOM file. * * It implements protected read methods for the * DICOMImageReader. * * @author Pierre Malarme * @version 1.O * */ public class DICOMBufferedInputStream extends BufferedInputStream { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- public static final short LITTLE_ENDIAN = 0; public static final short BIG_ENDIAN = 1; // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- protected short mByteOrder = LITTLE_ENDIAN; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMBufferedInputStream(File file) throws FileNotFoundException { super(new FileInputStream(file), 8192); } public DICOMBufferedInputStream(FileDescriptor fd) throws FileNotFoundException { super(new FileInputStream(fd), 8192); } public DICOMBufferedInputStream(String fileName) throws FileNotFoundException { super(new FileInputStream(fileName), 8192); } public DICOMBufferedInputStream(InputStream inputStream) { super(inputStream, 8192); } public DICOMBufferedInputStream(InputStream inputStream, int bufferSize) { super(inputStream, bufferSize); } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Read an unsigned short that is coded on 2 bytes. * * @return Unsigned short value. * @throws IOException */ protected final int readUnsignedShort() throws IOException { return readUnsignedInt16(); } /** * Read an unsigned integer of 16-Bit. * * @return Int16 value. * @throws IOException */ protected final int readUnsignedInt16() throws IOException { byte[] unsignedInt16 = new byte[2]; if (read(unsignedInt16) != 2) throw new IOException("Cannot read an unsigned int 16-Bit."); if (mByteOrder == LITTLE_ENDIAN) return (unsignedInt16[1] & 0xff) << 8 | (unsignedInt16[0] & 0xff); else return (unsignedInt16[0] & 0xff) << 8 | (unsignedInt16[1] & 0xff); } /** * Read an unsigned long coded on 4 bytes. * * @return Unsigned long 32-Bit value. * @throws IOException */ protected final long readUnsignedLong() throws IOException { byte[] unsignedLong = new byte[4]; if (read(unsignedLong) != 4) throw new IOException("Cannot read an unsigned long 32-Bit."); if (mByteOrder == LITTLE_ENDIAN) return ((long) unsignedLong[3] & 0xff) << 24 | ((long) unsignedLong[2] & 0xFF) << 16 | ((long) unsignedLong[1] & 0xFF) << 8 | ((long) unsignedLong[0] & 0xff); else return ((long) unsignedLong[0] & 0xff) << 24 | ((long) unsignedLong[1] & 0xFF) << 16 | ((long) unsignedLong[2] & 0xFF) << 8 | ((long) unsignedLong[3] & 0xff); } /** * Read an unsigned long coded on 8 bytes. * * @return Unsigned long 64-Bit value. * @throws IOException */ protected final long readUnsignedLong64() throws IOException { byte[] unsignedLong64 = new byte[8]; if (read(unsignedLong64) != 8) throw new IOException("Cannot read an unsigned long 64-Bit."); if (mByteOrder == LITTLE_ENDIAN) return (((long) unsignedLong64[7] & 0xff) << 56) | (((long) unsignedLong64[6] & 0xff) << 48) | (((long) unsignedLong64[5] & 0xff) << 40) | (((long) unsignedLong64[4] & 0xff) << 32) | (((long) unsignedLong64[3] & 0xff) << 24) | (((long) unsignedLong64[2] & 0xff) << 16) | (((long) unsignedLong64[1] & 0xff) << 8) | ((long) unsignedLong64[0] & 0xff); else return (((long) unsignedLong64[0] & 0xff) << 56) | (((long) unsignedLong64[1] & 0xff) << 48) | (((long) unsignedLong64[2] & 0xff) << 40) | (((long) unsignedLong64[3] & 0xff) << 32) | (((long) unsignedLong64[4] & 0xff) << 24) | (((long) unsignedLong64[5] & 0xff) << 16) | (((long) unsignedLong64[6] & 0xff) << 8) | ((long) unsignedLong64[7] & 0xff); } /** * Read a signed long coded on 4 bytes. * * @return Signed long 32-Bit (= Java int) value. * @throws IOException */ protected final int readSignedLong() throws IOException { byte[] signedLong = new byte[4]; if (read(signedLong) != 4) throw new IOException("Cannot read a signed long 32-Bit."); if (mByteOrder == LITTLE_ENDIAN) return ((signedLong[3] & 0xFF) << 24) | ((signedLong[2] & 0xff) << 16) | ((signedLong[1] & 0xff) << 8) | (signedLong[0] & 0xff); else return ((signedLong[0] & 0xFF) << 24) | ((signedLong[1] & 0xff) << 16) | ((signedLong[2] & 0xff) << 8) | (signedLong[3] & 0xff); } /** * Read a signed short coded on 2 bytes. * * @return Signed Short 16-Bit value. * @throws IOException */ protected final short readSignedShort() throws IOException { byte[] signedShort = new byte[2]; if (read(signedShort) != 2) throw new IOException("Cannot read a signed short 16-bit"); short s1 = (short) (signedShort[0] & 0xff); short s2 = (short) (signedShort[1] & 0xff); if (mByteOrder == LITTLE_ENDIAN) return (short) (s2 << 8 | s1); else return (short) (s1 << 8 | s2); } /** * Read a float single. * * @return Float single value. * @throws IOException */ protected final float readFloatSingle() throws IOException { int intBits = (int) readUnsignedLong(); return Float.intBitsToFloat(intBits); } /** * Read float double. * * @return Float double value. * @throws IOException */ protected final double readFloatDouble() throws IOException { long longBits = readUnsignedLong64(); return Double.longBitsToDouble(longBits); } /** * Read a tag and coded on 32 bit. * * @return Tag coded on 32 bit and stored as an integer. * @throws IOException */ protected final int readTag() throws IOException { int group = readUnsignedInt16(); int element = readUnsignedInt16(); return ((group & 0xffff) << 16 | (element & 0xffff)); } /** * Read byte[length] as ASCII. * * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected final String readASCII(int length) throws IOException { byte[] ASCIIbyte = new byte[length]; read(ASCIIbyte); // To avoid the null char : ASCII(0) String toReturnString = new String(ASCIIbyte, "ASCII"); for (int i = 0; i < length; i++) if (ASCIIbyte[i] == 0x00) return toReturnString.substring(0, i); return toReturnString; } /** * Read byte[length] as ASCII. * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected final String readString(int length, String charset) throws IOException { byte[] stringIbyte = new byte[length]; if (read(stringIbyte) != length) throw new IOException("readString: Size mismatch"); // To avoid the null char : ASCII(0) String toReturnString; try { toReturnString = new String(stringIbyte, charset); } catch (UnsupportedEncodingException ex) { toReturnString = new String(stringIbyte, "ASCII"); } for (int i = 0; i < length; i++) if (stringIbyte[i] == 0x00) if (i == (length - 1)) return toReturnString.substring(0,length - 1); return toReturnString; } /** * @return Byte order. */ protected short getByteOrder() { return mByteOrder; } /** * @param mByteOrder Byte order to set */ protected void setByteOrder(short byteOrder) { this.mByteOrder = byteOrder; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMFileFilter.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.file; import java.io.File; import java.io.FileFilter; /** * Filter the file on the basis of their extension. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMFileFilter implements FileFilter { // --------------------------------------------------------------- // + FUNCTION // --------------------------------------------------------------- // TODO check the DICOM meta information ? // This can lead to out of memory issue or // be very slow. /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept(File pathname) { if (pathname.isFile() && !pathname.isHidden()) { // Get the file name String fileName = pathname.getName(); // If the file is a DICOMDIR return false if (fileName.equals("DICOMDIR")) return false; // Get the dot index int dotIndex = fileName.lastIndexOf("."); // If the dotIndex is equal to -1 this is // a file without extension has are the DICOM // files if (dotIndex == -1) return true; // Check the file extension String fileExtension = fileName.substring(dotIndex + 1); if (fileExtension.equalsIgnoreCase("dcm")) return true; } return false; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.DicomReader // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMItem; import be.ac.ulb.lisa.idot.dicom.DICOMSequence; import be.ac.ulb.lisa.idot.dicom.DICOMTag; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; import be.ac.ulb.lisa.idot.dicom.data.DICOMMetaInformation; /** * DICOM file reader that can read meta information of * DICOM file. * * @author Pierre Malarme * @version 1.O * */ public class DICOMReader extends DICOMBufferedInputStream { // --------------------------------------------------------------- // - <static> VARIABLES // --------------------------------------------------------------- /** * Length of the preamble. */ private static final int PREAMBLE_LENGTH = 128; /** * Prefix of DICOM file. */ private static final String PREFIX = "DICM"; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Byte offset. */ protected long mByteOffset = 0; /** * Specific charset set in the body of the DICOM file. */ protected String mSpecificCharset = "ASCII"; /** * File size. */ protected long mFileSize = 0; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMReader(File file) throws FileNotFoundException { super(file); mFileSize = file.length(); mark(Integer.MAX_VALUE); } public DICOMReader(String fileName) throws FileNotFoundException { super(fileName); File file = new File(fileName); mFileSize = file.length(); mark(Integer.MAX_VALUE); } // --------------------------------------------------------------- // - CONSTRUCTORS // --------------------------------------------------------------- /** * Can have the file size and the BufferedInputStream do not throw * a EOFException at the end of the file (test). * * @param fd * @throws FileNotFoundException */ private DICOMReader(FileDescriptor fd) throws FileNotFoundException { super(fd); mark(Integer.MAX_VALUE); } // --------------------------------------------------------------- // + <final> FUNCTIONS // --------------------------------------------------------------- /** * @return True if the file is a DICOM file and has meta information * false otherwise. * @throws IOException */ public final boolean hasMetaInformation() throws IOException { // Reset the BufferedInputStream if (mByteOffset > 0) { reset(); mark(Integer.MAX_VALUE); } // If the file is smaller than the preamble and prefix // length there is no meta information if (available() < (PREAMBLE_LENGTH + PREFIX.length())) return false; // Skip the preamble skip(PREAMBLE_LENGTH); // Get the prefix String prefix = readASCII(PREFIX.length()); // Check the prefix boolean toReturn = prefix.equals(PREFIX); // Reset the BufferedInputStream reset(); mark(Integer.MAX_VALUE); // Skip the byte offset (mByteOffset) if (mByteOffset > 0) skip(mByteOffset); return toReturn; } /** * Parse meta information. * * @throws IOException * @throws EOFException * @throws DICOMException */ public final DICOMMetaInformation parseMetaInformation() throws IOException, EOFException, DICOMException { // Reset the BufferedInputStream if (mByteOffset > 0) { reset(); mark(Integer.MAX_VALUE); mByteOffset = 0; } try { // Skip the preamble skip(PREAMBLE_LENGTH); mByteOffset += PREAMBLE_LENGTH; // Check the prefix if (!PREFIX.equals(readASCII(4))) throw new DICOMException("This is not a DICOM file"); mByteOffset += 4; // Create a DICOM meta information object DICOMMetaInformation metaInformation = new DICOMMetaInformation(); // Tag File Meta group length = the length of // the meta of the dicom file int tag = readTag(); mByteOffset += 4; // If this is not this tag => error because the // DICOM 7.1 (3.5-2009) tags must be ordered by increasing // data element if (tag != 0x00020000) throw new DICOMException("Meta Information has now length"); // Skip 4 byte because we now that it is an UL skip(4); mByteOffset += 4; // Get the FileMeta group length long groupLength = readUnsignedLong(); mByteOffset+= 4; // Set the group length (meta information length) metaInformation.setGroupLength(groupLength); DICOMMetaInformationReaderFunctions dicomReaderFunctions = new DICOMMetaInformationReaderFunctions(metaInformation); // Fast parsing of the header with skiping sequences parse(null, groupLength, true, dicomReaderFunctions, true); // Return the meta information return metaInformation; } catch (EOFException ex) { throw new EOFException( "Cannot read the Meta Information of the DICOM file\n\n" +ex.getMessage()); } catch (IOException ex) { throw new IOException( "Cannot read the Meta Information of the DICOM file\n\n" +ex.getMessage()); } } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Parse the DICOM file. * * @param parentElement If a sequence is parsed. * @param length The length to parse. 0xffffffffL is * the undefined length. * @param isExplicit Set if the content of the BufferedInputStream * has explicit (true) or implicit (false) value representation. * @param dicomReaderFunctions Implementation of the DICOMReaderFunctions * interface. * @param skipSequence Set if the sequence must be skipped (true) * or not (false). * @throws IOException * @throws EOFException If the end of the file is reached before * the end of the parsing. * @throws DICOMException */ protected void parse(DICOMItem parentElement, long length, boolean isExplicit, DICOMReaderFunctions dicomReaderFunctions, boolean skipSequence) throws IOException, EOFException, DICOMException { // Set if the the length of the element to parse is defined boolean isLengthUndefined = length == 0xffffffffL; try { // Variable declaration and initialization DICOMTag dicomTag = null; DICOMValueRepresentation VR = null; long valueLength = 0; int tag = 0; length = length & 0xffffffffL; long lastByteOffset = isLengthUndefined ? 0xffffffffL : mByteOffset + length - 1; // Loop while the length is undefined or // while the byte offset is smaller than // the last byte offset while (((isLengthUndefined) || (mByteOffset < lastByteOffset)) && (mByteOffset < mFileSize)) { DICOMElement element = null; // Read the tag tag = readTag(); mByteOffset += 4; if (tag == 0) { reset(); mark(Integer.MAX_VALUE); skip(mByteOffset - 4); tag = readTag(); } // If the tag is an item delimitation // skip 4 bytes because there are // 4 null bytes after the item delimitation tag if (tag == 0xfffee00d) { skip(4); mByteOffset += 4; return; } // If the tag is an Item, ignore it // and skip 4 bytes because there are // 4 null bytes after the item delimitation tag if (tag == 0xfffee000) { skip(4); mByteOffset += 4; continue; } // Get the value representation and length // and create the DICOMTag. if (isExplicit) { // Get the DICOM value representation code/abreviation String VRAbbreviation = readASCII(2); mByteOffset += 2; VR = DICOMValueRepresentation.c.get(VRAbbreviation); VR = (VR == null) ? DICOMValueRepresentation.c.get("UN") : VR; dicomTag = DICOMTag.createDICOMTag(tag, VR); // If the value is on 2 bytes if (hasValueLengthOn2Bytes(VR.getVR())) { valueLength = readUnsignedInt16(); mByteOffset += 2; } else { skip(2); // Because VR abbreviation is coded // on 2 bytes valueLength = readUnsignedLong(); mByteOffset += 6; // 2 for the skip and 4 for the unsigned long } } else { dicomTag = DICOMTag.createDICOMTag(tag); VR = dicomTag.getValueRepresentation(); VR = (VR == null) ? DICOMValueRepresentation.c.get("UN") : VR; // If the value lengths are implicit, the length of the value // comes directly after the tag valueLength = readUnsignedLong(); mByteOffset += 4; } valueLength = valueLength & 0xffffffffL; // Get the value // If it is a sequence, read a new sequence if (VR.equals("SQ") || VR.equals("UN") && valueLength == 0xffffffffL) { // If the attribute has undefined value length // and/or do not skip sequence if (!skipSequence || valueLength == 0xffffffffL) { // Parse the sequence element = new DICOMSequence(dicomTag); parseSequence((DICOMSequence) element, valueLength, isExplicit, dicomReaderFunctions, skipSequence); } else { // Skip the value length skip(valueLength); mByteOffset += valueLength; continue; } // Else if tag is PixelData } else if (tag == 0x7fe00010) { dicomReaderFunctions.computeImage(parentElement, VR, valueLength); continue; // Return to the while begin } else if ( valueLength != 0xffffffffL) { // If it's not a required element, skip it if (parentElement != null || !dicomReaderFunctions.isRequiredElement(tag)) { skip(valueLength); mByteOffset += valueLength; continue; } Object value = null; if (VR.equals("UL")) { if (valueLength == 4) { value = readUnsignedLong(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); long[] values = new long[size]; for (int i = 0; i < size; i++) { values[i] = readUnsignedLong(); mByteOffset += 4; } value = values; } } else if (VR.equals("AT")) { value = readTag(); mByteOffset += 4; } else if (VR.equals("OB") || VR.equals("OF") || VR.equals("OW")) { String valueString = new String(); for (int i = 0; i < valueLength; i++) { valueString += (i == 0) ? "" : "\\"; valueString += String.valueOf(read()); mByteOffset++; } value = valueString; } else if (VR.equals("FL")) { // if the value length is greater // than 4 it is an array of float if (valueLength == 4) { value = readFloatSingle(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); float[] values = new float[size]; for (int i = 0; i < size; i++) { values[i] = readFloatSingle(); mByteOffset += 4; } value = values; } } else if (VR.equals("FD")) { // if the value length is greater // than 8 it is an array of double if (valueLength == 8) { value = readFloatDouble(); mByteOffset += 8; } else { int size = (int) (valueLength / 8); double[] values = new double[size]; for (int i = 0; i < size; i++) { values[i] = readFloatDouble(); mByteOffset += 8; } value = values; } } else if (VR.equals("SL")) { // if the value length is greater // than 4 it is an array of int if (valueLength == 4) { value = readSignedLong(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = readSignedLong(); mByteOffset += 4; } value = values; } } else if (VR.equals("SS")) { // if the value length is greater // than 2 it is an array of short if (valueLength == 2) { value = readSignedShort(); mByteOffset += 2; } else { int size = (int) (valueLength / 2); short[] values = new short[size]; for (int i = 0; i < size; i++) { values[i] = readSignedShort(); mByteOffset += 2; } value = values; } } else if (VR.equals("US")) { // if the value length is greater // than 2 it is an array of int if (valueLength == 2) { value = readUnsignedShort(); mByteOffset += 2; } else { int size = (int) (valueLength / 2); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = readUnsignedShort(); mByteOffset += 2; } value = values; } } else if (VR.equals("LO") || VR.equals("LT") || VR.equals("PN") || VR.equals("SH") || VR.equals("ST") || VR.equals("UT")) { value = readString((int) valueLength, mSpecificCharset); mByteOffset += valueLength; // Else interpreted as ASCII String } else { value = readASCII((int) valueLength); mByteOffset += valueLength; } // Create the element element = new DICOMElement(dicomTag, valueLength, value); } if (element != null) { // Add the DICOM element dicomReaderFunctions.addDICOMElement(parentElement, element); } } // end of the while // End of the stream exception } catch (EOFException e) { if (!isLengthUndefined) throw new EOFException(); // I/O Exception } catch (IOException e) { if (!isLengthUndefined) throw new IOException(); } } /** * Parse a DICOM sequence. * * @param sequence DICOM sequence to parse. * @param length Length of DICOM sequence. * @param isExplicit Set if the content of the BufferedInputStream * has explicit (true) or implicit (false) value representation. * @param dicomReaderFunctions Implementation of the DICOMReaderFunctions * interface. * @param skipSequence Set if the sequence must be skipped (true) * or not (false). * @throws IOException * @throws DICOMException * @throws EOFException If the end of the file is reached before * the end of the parsing. */ protected void parseSequence(DICOMSequence sequence, long length, boolean isExplicit, DICOMReaderFunctions dicomReaderFunctions, boolean skipSequence) throws IOException, EOFException, DICOMException { if (sequence == null) { throw new NullPointerException("Null Sequence"); } length = length & 0xffffffffL; boolean isLengthUndefined = length == 0xffffffffL; try { long lastByteOffset = isLengthUndefined ? 0xffffffffL : mByteOffset + length - 1; // Loop on all the items while (isLengthUndefined || mByteOffset < lastByteOffset) { // Get the tag int tag = readTag(); mByteOffset += 4; long valueLength = readUnsignedLong(); mByteOffset += 4; // If the tag is an Item if (tag == 0xfffee0dd) { break; } else if (tag == 0xfffee000) { DICOMItem item = new DICOMItem(); parse(item, valueLength, isExplicit, dicomReaderFunctions, skipSequence); sequence.addChild(item); // else if the tag is different that end // of sequence, this is not a sequence item } else { throw new DICOMException("Error Sequence: unknown tag" + (tag >> 16) + (tag & 0xffff)); } } } catch (EOFException e) { if (!isLengthUndefined) throw new EOFException(); } catch (IOException ex) { if (!isLengthUndefined) throw new IOException(ex.getMessage()); } } /** * Check if the value representation is on 2 bytes. * * @param VR DICOM value representation code on 2 bytes (character). * @return */ protected static final boolean hasValueLengthOn2Bytes(String VR) { return VR.equals("AR") || VR.equals("AE") || VR.equals("AS") || VR.equals("AT") || VR.equals("CS") || VR.equals("DA") || VR.equals("DS") || VR.equals("DT") || VR.equals("FD") || VR.equals("FL") || VR.equals("IS") || VR.equals("LO") || VR.equals("LT") || VR.equals("PN") || VR.equals("SH") || VR.equals("SL") || VR.equals("SL") || VR.equals("SS") || VR.equals("ST") || VR.equals("TM") || VR.equals("UI") || VR.equals("UL") || VR.equals("US"); } // --------------------------------------------------------------- // # CLASS // --------------------------------------------------------------- /** * Implementation of the DICOMReaderFunctions for * meta information. * * @author Pierre Malarme * @version 1.O * */ protected class DICOMMetaInformationReaderFunctions implements DICOMReaderFunctions { private DICOMMetaInformation mMetaInformation; public DICOMMetaInformationReaderFunctions() { mMetaInformation = new DICOMMetaInformation(); } public DICOMMetaInformationReaderFunctions(DICOMMetaInformation metaInformation) { mMetaInformation = metaInformation; } public void addDICOMElement(DICOMElement parent, DICOMElement element) { // If this is a sequence, do nothing if (parent != null) return; int tag = element.getDICOMTag().getTag(); // SOP Class UID if (tag == 0x00020002) { mMetaInformation.setSOPClassUID(element.getValueString()); // SOP Instance UID } else if (tag == 0x00020003) { mMetaInformation.setSOPInstanceUID(element.getValueString()); // Transfer syntax UID } else if (tag == 0x00020010) { mMetaInformation.setTransferSyntaxUID(element.getValueString()); // Implementation Class UID } else if (tag == 0x00020012) { mMetaInformation.setImplementationClassUID(element.getValueString()); // Implementation version name } else if (tag == 0x00020013) { mMetaInformation.setImplementationVersionName(element.getValueString()); // Implementation Application Entity Title } else if (tag == 0x00020016) { mMetaInformation.setAET(element.getValueString()); } } public boolean isRequiredElement(int tag) { return (tag == 0x00020002) || (tag == 0x00020003) || (tag == 0x00020010) || (tag == 0x00020012) || (tag == 0x00020013) || (tag == 0x00020016); } public void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long length) throws IOException, EOFException, DICOMException { throw new IOException("PixelData in Meta Information."); } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.DicomReader // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; import be.ac.ulb.lisa.idot.dicom.data.DICOMBody; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.data.DICOMMetaInformation; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * DICOM image file reader that read only grayscale image * with the bits allocated maximum value: 16 bits. * It does not support also compressed file format. * * For RGB image or compressed image, it parse just the meta * information and the body. * * @author Pierre Malarme * @version 1.O * */ public class DICOMImageReader extends DICOMReader { // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageReader(File file) throws FileNotFoundException { super(file); } public DICOMImageReader(String fileName) throws FileNotFoundException { super(fileName); } // --------------------------------------------------------------- // + <final> FUNCTIONS // --------------------------------------------------------------- /** * Parse the image DICOM file. * * @throws IOException * @throws EOFException * @throws DICOMException */ public final DICOMImage parse() throws IOException, EOFException, DICOMException { // Variables declaration DICOMMetaInformation metaInformation; boolean isExplicit; short compressionStatus = DICOMImage.UNKNOWN_STATUS; // Parse meta information if (hasMetaInformation()) { metaInformation = parseMetaInformation(); String transferSyntaxUID = metaInformation.getTransferSyntaxUID(); if (transferSyntaxUID.equals("1.2.840.10008.1.2")) { isExplicit = false; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else if (transferSyntaxUID.equals("1.2.840.10008.1.2.1")) { isExplicit = true; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else if (transferSyntaxUID.equals("1.2.840.10008.1.2.2")) { isExplicit = true; setByteOrder(BIG_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else { isExplicit = true; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.COMPRESSED; // Compressed image are not supported yet // => throw a exception throw new DICOMException("The image is compressed." + " This is not supported yet."); } } else { metaInformation = null; isExplicit = false; setByteOrder(LITTLE_ENDIAN); } // Parse the body DICOMImageReaderFunctions dicomReaderFunctions = new DICOMImageReaderFunctions(isExplicit, compressionStatus); parse(null, 0xffffffffL, isExplicit, dicomReaderFunctions, true); DICOMImage dicomImage = new DICOMImage(metaInformation, dicomReaderFunctions.getBody(), dicomReaderFunctions.getImage(), compressionStatus); return dicomImage; } // --------------------------------------------------------------- // # CLASS // --------------------------------------------------------------- protected class DICOMImageReaderFunctions implements DICOMReaderFunctions { // TODO support encapsulated PixelData ? or throw an error DICOMBody mBody; LISAImageGray16Bit mImage; boolean mIsExplicit; short mCompressionStatus; public DICOMImageReaderFunctions(boolean isExplicit, short compressionStatus) { mBody = new DICOMBody(); mImage = new LISAImageGray16Bit(); mIsExplicit = isExplicit; mCompressionStatus = compressionStatus; } public void addDICOMElement(DICOMElement parent, DICOMElement element) { // If this is a sequence, do nothing if (parent != null) return; int tag = element.getDICOMTag().getTag(); // Specific character set if (tag == 0x00080005) { mBody.setSpecificCharset(element.getValueString()); // Set the specific character set mSpecificCharset = mBody.getSpecificCharset(); // If tag == image type } else if (tag == 0x00080008) { mBody.setImageType(element.getValueString()); // If tag == image orientation } else if (tag == 0x00200037) { mImage.setImageOrientation(getImageOrientation(element)); // If tag == samples per pixel } else if (tag == 0x00280002) { mBody.setSamplesPerPixel(element.getValueInt()); // If tag == rows } else if (tag == 0x00280010) { mImage.setHeight((short) element.getValueInt()); // If tags == columns } else if (tag == 0x00280011) { mImage.setWidth((short) element.getValueInt()); // If tag == bits allocated } else if (tag == 0x00280100) { mBody.setBitsAllocated(element.getValueInt()); // If tag == bits stored } else if (tag == 0x00280101) { mBody.setBitsStored(element.getValueInt()); // Set the image gray level mImage.setGrayLevel((int) Math.pow(2, mBody.getBitsStored())); // If tag == high bit } else if (tag == 0x00280102) { mBody.setHightBit(element.getValueInt()); // If tag == pixel representation } else if (tag == 0x00280103) { mBody.setPixelRepresentation(element.getValueInt()); // If tag == window center } else if (tag == 0x00281050) { mImage.setWindowCenter(getIntFromStringArray(element)); // If tag == window width } else if (tag == 0x00281051) { mImage.setWindowWidth(getIntFromStringArray(element)); } } public boolean isRequiredElement(int tag) { return (tag == 0x00080005) || (tag == 0x00080008) || (tag == 0x00200037) || (tag == 0x00280002) || (tag == 0x00280010) || (tag == 0x00280011) || (tag == 0x00280100) || (tag == 0x00280101) || (tag == 0x00280102) || (tag == 0x00280103) || (tag == 0x00281050) || (tag == 0x00281051); } public void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long valueLength) throws IOException, EOFException, DICOMException { // If the image is compressed, or if the compression status // is unknown or if the parent exists or if the bits // allocated is not defined, skip it if (mCompressionStatus == DICOMImage.UNKNOWN_STATUS || mCompressionStatus == DICOMImage.COMPRESSED || mBody.getBitsAllocated() == 0 || parent != null) { if (valueLength == 0xffffffffL) { throw new DICOMException("Cannot skip the PixelData" + " because the length is undefined"); } else { skip(valueLength); mByteOffset += valueLength; return; } } // Check the samples per pixel, just 1 is implemented yet if (mBody.getSamplesPerPixel() != 1) throw new DICOMException("The samples per pixel (" + mBody.getSamplesPerPixel() + ") is not" + " supported yet."); // For Implicit: OW and little endian if (!mIsExplicit) { computeOWImage(valueLength); // Explicit VR } else { // If it is OB return because OB is not // supported yet if (VR.equals("OB")) { skip(valueLength); mByteOffset += valueLength; return; // TODO throw an error if bits allocated > 8 // and VR == OB because PS 3.5-2009 Pg. 66-68: // If the bits allocated > 8 => OW ! // But it's not done because we do not know // if this specification of the standard is // respected and we do not implement for now // the OB reading. } else if (VR.equals("OW")) { computeOWImage(valueLength); } else { // Unknown data pixel value representation throw new DICOMException("Unknown PixelData"); } } } public DICOMBody getBody() { return mBody; } public LISAImageGray16Bit getImage() { return mImage; } /** * Compute an * * @param bitsAllocated * @param valueLength * @throws IOException * @throws EOFException * @throws DICOMException */ private void computeOWImage(long valueLength) throws IOException, EOFException, DICOMException { // Check the value length if (valueLength == 0xffffffffL) throw new DICOMException("Cannot parse PixelData " + "because the length is undefined"); // Get the bits allocated int bitsAllocated = mBody.getBitsAllocated(); // Cf. PS 3.5-2009 Pg. 66-67 if (bitsAllocated == 8) { computeOW8BitImage(valueLength); } else if (bitsAllocated == 16) { computeOW16BitImage(valueLength); } else if (bitsAllocated == 32) { /* for (int i = 0; i < mPixelData.length; i++) { mPixelData[i] = (int) readUnsignedLong(); } mByteOffset += valueLength; */ // TODO We can sample the gray level on 16 bit but // is it compatible with the DICOM standard ? throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } else if (bitsAllocated == 64) { /* for (int i = 0; i < mPixelData.length; i++) { mPixelData[i] = (int) readUnsignedLong64(); } mByteOffset += valueLength; */ // TODO We can sample the gray level on 16 bit but // is it compatible with the DICOM standard ? throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } else { throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } // Add the value length to the byte offset mByteOffset += valueLength; } private void computeOW16BitImage(long valueLength) throws IOException, EOFException, DICOMException { // Check that the value length correspond to 2 * width * height if (valueLength != (2 * mImage.getWidth() * mImage.getHeight())) throw new DICOMException("The size of the image does not " + "correspond to the size of the Pixel Data coded " + "in byte."); // Get the bit shift (e.g.: highBit = 11, bitsStored = 12 // => 11 - 12 + 1 = 0 i.e. no bit shift), (e.g.: highBit = 15, // bitsStored = 12 => 15 - 12 + 1 = 4 int bitShift = mBody.getHightBit() - mBody.getBitsStored() + 1; int grayLevel = mImage.getGrayLevel(); int[] imageData = new int[(int) (valueLength / 2)]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; if (bitShift == 0) { for (int i = 0; i < imageData.length; i++) { imageData[i] = readUnsignedInt16() & 0x0000ffff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } else { for (int i = 0; i < imageData.length; i++) { imageData[i] = (readUnsignedInt16() >> bitShift) & 0x0000ffff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } mImage.setData(imageData); mImage.setDataMax(imageDataMax); mImage.setHistogramData(imageHistogram); mImage.setHistogramMax(imageHistogramMax); } private void computeOW8BitImage(long valueLength) throws IOException, EOFException, DICOMException { // Check that the value length correspond to 2 * width * height if (valueLength != (mImage.getWidth() * mImage.getHeight())) throw new DICOMException("The size of the image does not " + "correspond to the size of the Pixel Data coded " + "in byte."); // Get the bit shift (e.g.: highBit = 4, bitsStored = 5 // => 4 - 5 + 1 = 0 i.e. no bit shift), (e.g.: highBit = 6, // bitsStored = 5 => 6 - 5 + 1 = 2 int bitShift = mBody.getHightBit() - mBody.getBitsStored() + 1; int grayLevel = mImage.getGrayLevel(); int[] imageData = new int[(int) (valueLength)]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; if (bitShift == 0) { for (int i = 0; i < imageData.length; i++) { imageData[i] = read() & 0x000000ff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } else { for (int i = 0; i < imageData.length; i++) { imageData[i] = (read() >> bitShift) & 0x000000ff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } mImage.setData(imageData); mImage.setDataMax(imageDataMax); mImage.setHistogramData(imageHistogram); mImage.setHistogramMax(imageHistogramMax); } private int getIntFromStringArray(DICOMElement element) { // Explode the string String[] values = element.getValueString().split("\\\\"); if (values.length >= 1) { try { // We do this because if the value is coded as // a float single return Math.round(Float.parseFloat(values[0])); } catch (NumberFormatException ex) { return -1; } } return -1; } private float[] getImageOrientation(DICOMElement element) { // Explode the string String[] values = element.getValueString().split("\\\\"); if (values.length != 6) return null; float[] imageOrientation = new float[6]; for (int i = 0; i < 6; i ++) { try { imageOrientation[i] = Float.parseFloat(values[i]); } catch (NumberFormatException ex) { return null; } } return imageOrientation; } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMReaderFunctions.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; /** * Interface for DICOM Reader. * * @author Pierre Malarme * @version 1.0 * */ public interface DICOMReaderFunctions { /** * Add the DICOM element to an object (e.g. DICOMBody) * or to the parent. * * @param parent Parent if it is a sequence. * @param element Element to add. */ void addDICOMElement(DICOMElement parent, DICOMElement element); /** * Check if the DICOM element is required for DICOMTag integer value * tag. * * @param tag Integer value of the DICOMTag to check. * @return */ boolean isRequiredElement(int tag); /** * Compute the image. * * @param parent Parent if it is a sequence. * @param VR DICOM value representation of the value. * @param valueLength Length of the value. */ void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long valueLength) throws IOException, EOFException, DICOMException; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMSequence.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.ArrayList; import java.util.List; /** * DICOM sequence. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMSequence extends DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * List of DICOMElement children (normally DICOMItem). */ protected List<DICOMElement> mChildrenList; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMSequence(DICOMTag dicomTag) { super(dicomTag, null); mChildrenList = new ArrayList<DICOMElement>(); } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Add a DICOMElement child to the sequence (List). * @param element */ public void addChild(DICOMElement element) { mChildrenList.add(element); } /** * Get a DICOMElement child from the List correspond to the index. * @param index Index of the child. * @return DICOMElement child. * @throws IndexOutOfBoundsException */ public DICOMElement getChild(int index) throws IndexOutOfBoundsException { return mChildrenList.get(index); } /** * @return DICOMElement children List. */ public List<DICOMElement> getChildrenList() { return mChildrenList; } /** * @return Number of children in the List. */ public int getChildrenCount() { return mChildrenList.size(); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMTag.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM tag. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMTag { // --------------------------------------------------------------- // + <static> VARIABLE // --------------------------------------------------------------- /** * Map of defined tag. */ public static final Map<Integer, DICOMTag> c = new HashMap<Integer, DICOMTag>() { /** * Eclipse generated Serial version. */ private static final long serialVersionUID = -8652499398694995133L; // To generate each time this hashmap is modified. { put(0x00020000, new DICOMTag(0x00020000, "File Meta Information Group Length", DICOMValueRepresentation.c.get("UL"))); put(0x00020001, new DICOMTag(0x00020001, "File Meta Information Group Length", DICOMValueRepresentation.c.get("OB"))); put(0x00020002, new DICOMTag(0x00020002, "Media Storage SOP Class UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020003, new DICOMTag(0x00020003, "Media Storage SOP Instance UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020010, new DICOMTag(0x00020010, "TransferSyntax UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020012, new DICOMTag(0x00020012, "Implementation Class UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020013, new DICOMTag(0x00020013, "Implementation Version Name", DICOMValueRepresentation.c.get("SH"))); put(0x00020016, new DICOMTag(0x00020016, "Source Application Entity", DICOMValueRepresentation.c.get("AE"))); put(0x00020100, new DICOMTag(0x00020100, "Private Information creator UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020102, new DICOMTag(0x00020102, "Private Information creator UID", DICOMValueRepresentation.c.get("OB"))); put(0x00280002, new DICOMTag(0x00280002, "Samples per pixel", DICOMValueRepresentation.c.get("US"))); put(0x00280010, new DICOMTag(0x00280010, "Rows", DICOMValueRepresentation.c.get("US"))); put(0x00280011, new DICOMTag(0x00280011, "Columns", DICOMValueRepresentation.c.get("US"))); put(0x00280100, new DICOMTag(0x00280100, "Bits allocated", DICOMValueRepresentation.c.get("US"))); put(0x00280101, new DICOMTag(0x00280101, "Bits stored", DICOMValueRepresentation.c.get("US"))); put(0x00280102, new DICOMTag(0x00280102, "High Bit", DICOMValueRepresentation.c.get("US"))); put(0x00280103, new DICOMTag(0x00280103, "Pixel Representation", DICOMValueRepresentation.c.get("US"))); put(0x7fe00010, new DICOMTag(0x7fe00010, "Pixel Data", DICOMValueRepresentation.c.get("UN"))); put(0xfffee000, new DICOMTag(0xfffee000, "Item", DICOMValueRepresentation.c.get("UN"))); put(0xfffee00d, new DICOMTag(0xfffee00d, "Item Delimitation Tag", DICOMValueRepresentation.c.get("UN"))); put(0xfffee0dd, new DICOMTag(0xfffee0dd, "Sequence Delimitation Tag", DICOMValueRepresentation.c.get("UN"))); }}; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Tag integer value. */ private final int mTag; /** * Tag description. */ private final String mName; /** * Tag value representation. */ private final DICOMValueRepresentation mVR; // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * Create a DICOM tag using a tag integer value. * * @param tag Tag integer value * @return */ public static final DICOMTag createDICOMTag(int tag) { // If the tag is known by Droid Dicom Viewer if (c.containsKey(tag)) { return c.get(tag); } else { int tagGroup = (tag >> 16) & 0xff; // If the tagGroup is an odd Number, the tag is // Private String name = (tagGroup % 2 == 0) ? "Unknown" : "Private"; DICOMValueRepresentation VR = DICOMValueRepresentation.c.get("UN"); return new DICOMTag(tag, name, VR); } } /** * Create a DICOM tag using a tag integer value * and a value representation. * * @param tag Tag integer value * @param VR Value representation. * @return */ public static final DICOMTag createDICOMTag(int tag, DICOMValueRepresentation VR) { String name; // If the tag is known by Droid Dicom Viewer if (c.containsKey(tag)) { // If the VR is the same as a tag in memory, return this tag if (VR.getVR().equals(c.get(tag).getValueRepresentation().getVR())) return c.get(tag); name = c.get(tag).getName(); } else { int tagGroup = (tag >> 16) & 0xff; // If the tagGroup is an odd Number, the tag is // Private name = (tagGroup % 2 == 0) ? "Unknown" : "Private"; } return new DICOMTag(tag, name, VR); } // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMTag(int tag, String name, DICOMValueRepresentation VR) { mTag = tag; mName = name; mVR = VR; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return the mTag */ public int getTag() { return mTag; } /** * @return Tag UID as a String (group + element). */ public String toString() { return getGroup() + getElement(); } /** * @return Tag group as a String. */ public String getGroup() { String toReturn = Integer.toHexString((mTag >> 16) & 0xffff); while (toReturn.length() < 4) toReturn = "0" + toReturn; return toReturn; } /** * @return Tag element as a String. */ public String getElement() { String toReturn = Integer.toHexString((mTag) & 0xffff); while (toReturn.length() < 4) toReturn = "0" + toReturn; return toReturn; } /** * @return Tag description. */ public String getName() { return mName; } /** * @return Value representation. */ public DICOMValueRepresentation getValueRepresentation() { return mVR; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMElement.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; /** * DICOM element. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * DICOM element DICOM tag. */ protected DICOMTag mDICOMTag; /** * DICOM element value. */ protected Object mValue; /** * DICOM element length in byte. */ protected long mLength; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- /** * Construct a DICOM item with a undefined length. * @param dicomTag * @param value */ public DICOMElement(DICOMTag dicomTag, Object value) { this(dicomTag, 0xffffffffL, value); } public DICOMElement(DICOMTag dicomTag, long length, Object value) { mDICOMTag = dicomTag; mLength = length; mValue = value; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return the mDICOMTag */ public DICOMTag getDICOMTag() { return mDICOMTag; } /** * @return the mValue */ public Object getValue() { return mValue; } /** * @return DICOM element length in bytes. */ public long getLength() { return mLength; } /** * @return DICOM element value as a String or null * if there is an error. */ public String getValueString() { // If there is no value return null if (mValue == null) return "NULL"; // If no tag return a null object if (mDICOMTag == null) return null; // TODO throw a DICOM Exception // Get the value representation DICOMValueRepresentation VR = mDICOMTag.getValueRepresentation(); if (mDICOMTag.getTag() == 0x7fe00010) { if (VR.equals("OW")) return "Pixel DICOM OW"; else if (VR.equals("OB")) return "Pixel DICOM OB"; } if (VR.equals("US") || VR.equals("SS")) { if (mLength > 2) return "Array of numerical values coded in 2 bits"; } else if (VR.equals("UL") || VR.equals("FL") || VR.equals("SL")) { if (mLength > 4) return "Array of numerical values coded in 4 bits"; } else if (VR.equals("FD")) { if (mLength > 8) return "Array of numerical values coded in 8 bits"; } // Get the value class from the VR @SuppressWarnings("rawtypes") Class valueClass = VR.getReturnType(); // If type match return the string representing the value if (valueClass.equals(mValue.getClass())) { String toReturn = "" + valueClass.cast(mValue); return toReturn; } else { return null; } } /** * @param dicomTag DICOMTag to set */ public void setDICOMTag(DICOMTag dicomTag) { mDICOMTag = dicomTag; } /** * @param value the value to set */ public void setValue(Object value) { mValue = value; } /** * @param length the length to set. */ public void setLength(int length) { mLength = length; } /** * @return DICOM element value as an integer. * @throws NumberFormatException If the value is not an * integer, it throws a NumberFormatException. */ public int getValueInt() throws NumberFormatException { int toReturn = 0; if (mValue instanceof String) { toReturn = Integer.parseInt((String) mValue); } else if (mValue instanceof Short) { toReturn = (int) (Short) mValue; } else if (mValue instanceof Integer) { toReturn = (Integer) mValue; } else if (mValue instanceof Long) { toReturn = ((Long) mValue).intValue(); } else { toReturn = Integer.parseInt(getValueString()); } return toReturn; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMValueRepresentation.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM tag. * * @author Pierre Malarme * @version 1.0 * */ /** * @author pmalarme * */ /** * @author pmalarme * */ public class DICOMValueRepresentation { // --------------------------------------------------------------- // + <static> VARIABLE // --------------------------------------------------------------- // The class raw types of the value representation. /** * Byte array set as String. */ @SuppressWarnings("rawtypes") public static final Class BYTE = String.class; /** * Double. */ @SuppressWarnings("rawtypes") public static final Class DOUBLE = Double.class; /** * Float. */ @SuppressWarnings("rawtypes") public static final Class FLOAT = Float.class; /** * Integer. */ @SuppressWarnings("rawtypes") public static final Class INT = Integer.class; /** * Long. */ @SuppressWarnings("rawtypes") public static final Class LONG = Long.class; /** * Object: just for sequence. */ @SuppressWarnings("rawtypes") public static final Class OBJECT = Object.class; /** * String. */ @SuppressWarnings("rawtypes") public static final Class STRING = String.class; /** * Short. */ @SuppressWarnings("rawtypes") public static final Class SHORT = Short.class; /** * Map of value representation. */ public static final Map<String, DICOMValueRepresentation> c = new HashMap<String, DICOMValueRepresentation>() { /** * Eclipse generated serial version UID. */ private static final long serialVersionUID = 4021611561632736549L; { put("AE", new DICOMValueRepresentation("AE", "Application Entity", STRING, 16, false)); put("AS", new DICOMValueRepresentation("AS", "Age String", STRING, 4, true)); put("AT", new DICOMValueRepresentation("AS", "Attribute Tag", INT, 4, true)); put("CS", new DICOMValueRepresentation("CS", "Code String", STRING, 16, true)); put("DA", new DICOMValueRepresentation("DA", "Date", STRING, 18, false)); // TODO DICOM 3.5-2009 page 25 : In the context of a Query with range matching // the length is 18 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 18 and maximum for future instead of 8 and fixed. put("DS", new DICOMValueRepresentation("DS", "Decimal String", STRING, 16, false)); put("DT", new DICOMValueRepresentation("DT", "Date Time", STRING, 54, false)); // TODO DICOM 3.5-2009 page 26 : In the context of a Query with range matching // the length is 54 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 54 and maximum for future instead of 26 and maximum. put("FL", new DICOMValueRepresentation("FL", "Floating Point Single", FLOAT, 4, true)); put("FD", new DICOMValueRepresentation("FD", "Floating Point Double", DOUBLE, 8, true)); put("IS", new DICOMValueRepresentation("IS", "Integer String", STRING, 12, false)); put("LO", new DICOMValueRepresentation("LO", "Long String", STRING, 64, false)); put("LT", new DICOMValueRepresentation("LT", "Long Text", STRING, 1024, false)); put("OB", new DICOMValueRepresentation("OB", "Other Byte String", BYTE)); put("OF", new DICOMValueRepresentation("OF", "Other Float String", STRING)); // TODO Set the max at 2^32-4 cf. pg 28 put("OW", new DICOMValueRepresentation("OW", "Other Word String", STRING)); put("PN", new DICOMValueRepresentation("PN", "Person Name", STRING)); // TODO ADD A PN OBJECT TYPE because 64-chars per component group (pg. 28) put("SH", new DICOMValueRepresentation("SH", "Short String", STRING, 16, false)); put("SL", new DICOMValueRepresentation("SL", "Signed Long", INT, 4 , true)); put("SQ", new DICOMValueRepresentation("SQ", "Sequence of Items", OBJECT)); put("SS", new DICOMValueRepresentation("SS", "Signed Short", SHORT, 2, true)); put("ST", new DICOMValueRepresentation("ST", "Short Text", STRING, 1024, false)); put("TM", new DICOMValueRepresentation("TM", "Time", STRING, 28, false)); // TODO DICOM 3.5-2009 page 31 : In the context of a Query with range matching // the length is 28 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 28 and maximum for future instead of 16 and maximum. put("UI", new DICOMValueRepresentation("UI", "Unique Identifier", STRING, 64, false)); put("UL", new DICOMValueRepresentation("UL", "Unsigned Long", LONG, 4, false)); put("UN", new DICOMValueRepresentation("UN", "Unknown", STRING)); // TODO Any length valid for any of the DICOM Value representation cf. pg 32 put("US", new DICOMValueRepresentation("US", "Unsigned Short", INT, 2, false)); // Page 32 US: vale n: 0 <= n < 2^16 put("UT", new DICOMValueRepresentation("UT", "Unlimited Text", STRING)); // TODO pg. 32: maximum length 2^32-2 }}; // --------------------------------------------------------------- // - VARIABLE // --------------------------------------------------------------- /** * Value representation code on 2 bytes (character). */ private final String mVR; /** * Value representation description. */ private final String mName; /** * Raw type of the value representation. */ @SuppressWarnings("rawtypes") private final Class mReturnType; /** * The maximum byte count. * -1 = no maximum */ private final int mMaxByteCount; /** * If the number of byte is fixed or not. If it is the case, * the mMaxByteCount is the fixed number of bytes. */ private final boolean mIsFixedByteCount; // --------------------------------------------------------------- // - CONSTRUCTORS // --------------------------------------------------------------- /** * The constructor is private because only known value representation * are accepted. If the value is unknown, it is set to UN. * * @param VR * @param name * @param returnType */ @SuppressWarnings("rawtypes") private DICOMValueRepresentation(String VR, String name, Class returnType) { this(VR, name, returnType, -1, false); } /** * The constructor is private because only known value representation * are accepted. If the value is unknown, it is set to UN. * * @param VR * @param name * @param returnType * @param maxByteCount * @param isFixedByteCount */ @SuppressWarnings("rawtypes") private DICOMValueRepresentation(String VR, String name, Class returnType, int maxByteCount, boolean isFixedByteCount) { mVR = VR; mName = name; mReturnType = returnType; mMaxByteCount = maxByteCount; mIsFixedByteCount = isFixedByteCount; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Get if this object is a value representation identical to VR. * @param VR * @return */ public boolean equals(String VR) { if (VR == null) return false; else if (mVR == VR) return true; else return false; } /** * @return Value representation code on 2 bytes (character). */ public String getVR() { return mVR; } /** * @return Value representation description. */ public String getName() { return mName; } /** * @return Raw type. */ @SuppressWarnings("rawtypes") public Class getReturnType() { return mReturnType; } /** * @return Maximum byte. */ public int getMaxByteCount() { return mMaxByteCount; } /** * @return If the number of byte is fixed or not. */ public boolean isFixedByteCount() { return mIsFixedByteCount; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMException.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer 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. * * Droid Dicom Viewer 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 Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; /** * DICOM Exception. * * DICOM exception occurs when the parsing of the DICOM file * is not possible or if the DICOM file is not supported by * the software. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMException extends Exception { /** * Generated by Eclipse */ private static final long serialVersionUID = -2837146355840633988L; public DICOMException() { super(); } public DICOMException(String msg) { super(msg); } public DICOMException(String msg, Throwable throwable) { super(msg, throwable); } public DICOMException(Throwable throwable) { super(throwable); } }
Java
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.view.Menu; import android.view.MenuItem.OnMenuItemClickListener; /** * Singleton that provides configurable functionality. * */ public class ApplicationVariantConfig { private MenuInitializer menuInitializer; private static ApplicationVariantConfig INSTANCE; private ApplicationVariantConfig() { } public static synchronized ApplicationVariantConfig getInstance() { if (INSTANCE == null) { INSTANCE = new ApplicationVariantConfig(); } return INSTANCE; } public MenuInitializer getMenuInitializer() { return menuInitializer != null ? menuInitializer : new MenuInitializer() { public OnMenuItemClickListener addMenuItems(Menu menu) { return null; } }; } public void setMenuInitializer(MenuInitializer extender) { menuInitializer = extender; } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.backport.ScaleGestureDetector; import com.google.android.apps.tvremote.backport.ScaleGestureDetectorFactory; import com.google.android.apps.tvremote.protocol.ICommandSender; import com.google.android.apps.tvremote.util.Action; import android.os.CountDownTimer; import android.view.MotionEvent; import android.view.View; /** * The touchpad logic. * */ public final class TouchHandler implements View.OnTouchListener { /** * Defines the kind of events this handler is supposed to generate. */ private final Mode mode; /** * Interface to send commands during a touch sequence. */ private final ICommandSender commands; /** * The current touch sequence. */ private Sequence state; /** * {@code true} if the touch handler is active. */ private boolean isActive; /** * Scale gesture detector. */ private final ScaleGestureDetector scaleGestureDetector; private final float zoomThreshold; /** * Max thresholds for a sequence to be considered a click. */ private static final int CLICK_DISTANCE_THRESHOLD_SQUARE = 30 * 30; private static final int CLICK_TIME_THRESHOLD = 500; private static final float SCROLLING_FACTOR = 0.2f; /** * Threshold to send a scroll event. */ private static final int SCROLL_THRESHOLD = 2; /** * Thresholds for multitouch gestures. */ private static final float MT_SCROLL_BEGIN_DIST_THRESHOLD_SQR = 20.0f * 20.0f; private static final float MT_SCROLL_BEGIN_THRESHOLD = 1.2f; private static final float MT_SCROLL_END_THRESHOLD = 1.4f; private static final float MT_ZOOM_SCALE_THRESHOLD = 1.8f; /** * Describes the way touches should be interpreted. */ public enum Mode { POINTER, POINTER_MULTITOUCH, SCROLL_VERTICAL, SCROLL_HORIZONTAL, ZOOM_VERTICAL } public TouchHandler(View view, Mode mode, ICommandSender commands) { if (Mode.POINTER_MULTITOUCH.equals(mode)) { this.scaleGestureDetector = ScaleGestureDetectorFactory .createScaleGestureDetector(view, new MultitouchHandler()); this.mode = Mode.POINTER; } else { this.scaleGestureDetector = null; this.mode = mode; } this.commands = commands; isActive = true; zoomThreshold = view.getResources().getInteger(R.integer.zoom_threshold); view.setOnTouchListener(this); } public boolean onTouch(View v, MotionEvent event) { if (!isActive) { return false; } if (scaleGestureDetector != null) { scaleGestureDetector.onTouchEvent(event); if (scaleGestureDetector.isInProgress()) { if (state != null) { state.cancelDownTimer(); state = null; } return true; } } int x = (int) event.getX(); int y = (int) event.getY(); long timestamp = event.getEventTime(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: state = new Sequence(x, y, timestamp); return true; case MotionEvent.ACTION_CANCEL: state = null; return true; case MotionEvent.ACTION_UP: boolean handled = state != null && state.handleUp(x, y, timestamp); state = null; return handled; case MotionEvent.ACTION_MOVE: return state != null && state.handleMove(x, y, timestamp); default: return false; } } /** * {@code true} activates the touch handler, {@code false} deactivates it. */ public void setActive(boolean active) { isActive = active; } /** * Stores parameters of a touch sequence, i.e. down - move(s) - up and handles * new touch events. */ private class Sequence { /** * Location of the sequence's start event. */ private final int refX, refY; /** * Location of the last touch event. */ private int lastX, lastY; private long lastTimestamp; /** * Delta Y accumulated across several touches. */ private int accuY; /** * Timer that expires when a click down has to be sent. */ private CountDownTimer clickDownTimer; /** * {@code true} if a click down has been sent. */ private boolean clickDownSent; public Sequence(int x, int y, long timestamp) { refX = x; refY = y; clickDownSent = false; setLastTouch(x, y, timestamp); if (mode == Mode.POINTER) { startClickDownTimer(); } } private void setLastTouch(int x, int y, long timestamp) { lastX = x; lastY = y; lastTimestamp = timestamp; } /** * Returns {@code true} if a sequence is a movement. */ private boolean isMove(int x, int y) { int distance = ((refX - x) * (refX - x)) + ((refY - y) * (refY - y)); return distance > CLICK_DISTANCE_THRESHOLD_SQUARE; } /** * Starts a timer that will expire after * {@link TouchHandler#CLICK_TIME_THRESHOLD} and start to send a click down * event if the touch event cannot be interpreted as a movement. */ private void startClickDownTimer() { clickDownTimer = new CountDownTimer(CLICK_TIME_THRESHOLD, CLICK_TIME_THRESHOLD) { @Override public void onTick(long arg0) { // Nothing to do. } @Override public void onFinish() { clickDown(); } }; clickDownTimer.start(); } /** * Cancels the timer, no-op if there is no timer available. * * @return {@code true} if there was a timer to cancel */ private boolean cancelDownTimer() { if (clickDownTimer != null) { clickDownTimer.cancel(); clickDownTimer = null; return true; } return false; } /** * Sends a click down message. */ private void clickDown() { Action.CLICK_DOWN.execute(commands); clickDownSent = true; } /** * Handles a touch up. * * A click will be issued if the initial touch of the sequence is close * enough both timewise and distance-wise. * * @param x an integer representing the touch's x coordinate * @param y an integer representing the touch's y coordinate * @param timestamp a long representing the touch's time * @return {@code true} if a click was issued */ public boolean handleUp(int x, int y, long timestamp) { if (mode != Mode.POINTER) { return true; } // If a click down is waiting, send it. if (cancelDownTimer()) { clickDown(); } if (clickDownSent) { Action.CLICK_UP.execute(commands); } return true; } /** * Handles a touch move. * * Depending on the initial touch of the sequence, this will result in a * pointer move or in a scrolling action. * * @param x an integer representing the touch's x coordinate * @param y an integer representing the touch's y coordinate * @param timestamp a long representing the touch's time * @return {@code true} if any action was taken */ public boolean handleMove(int x, int y, long timestamp) { if (mode == Mode.POINTER) { if (!isMove(x, y)) { // Stand still while it's not a move to avoid a movement when a click // is performed. } else { cancelDownTimer(); } } long timeDelta = timestamp - lastTimestamp; int deltaX = x - lastX; int deltaY = y - lastY; switch(mode) { case POINTER: commands.moveRelative(deltaX, deltaY); break; case SCROLL_VERTICAL: if (shouldTriggerScrollEvent(deltaY)) { commands.scroll(0, deltaY); } break; case SCROLL_HORIZONTAL: if (shouldTriggerScrollEvent(deltaX)) { commands.scroll(deltaX, 0); } break; case ZOOM_VERTICAL: accuY += deltaY; if (Math.abs(accuY) >= zoomThreshold) { if (accuY < 0) { Action.ZOOM_IN.execute(commands); } else { Action.ZOOM_OUT.execute(commands); } accuY = 0; } break; } setLastTouch(x, y, timestamp); return true; } } /** * Handles multitouch events to capture zoom and scroll events. */ private class MultitouchHandler implements ScaleGestureDetector.OnScaleGestureListener { private float lastScrollX; private float lastScrollY; private boolean isScrolling; public boolean onScale(ScaleGestureDetector detector) { float scaleFactor = detector.getScaleFactor(); float deltaX = scaleGestureDetector.getFocusX() - lastScrollX; float deltaY = scaleGestureDetector.getFocusY() - lastScrollY; toggleScrolling(scaleFactor, deltaX, deltaY); float absX = Math.abs(deltaX); float signX = Math.signum(deltaX); float absY = Math.abs(deltaY); float signY = Math.signum(deltaY); // If both translations are less than 1 // pick greater one and align to 1 if ((absX < 1) && (absY < 1)) { if (absX > absY) { deltaX = signX; deltaY = 0; } else { deltaX = 0; deltaY = signY; } } else { if (absX < 1) { deltaX = 0; } else { deltaX = ((absX - 1) * SCROLLING_FACTOR + 1) * signX; } if (absY < 1) { deltaY = 0; } else { deltaY = ((absY - 1) * SCROLLING_FACTOR + 1) * signY; } } if (isScrolling) { if (shouldTriggerScrollEvent(deltaX) || shouldTriggerScrollEvent(deltaY)) { executeScrollEvent(deltaX, deltaY); } return false; } if (!isWithinInvRange(scaleFactor, MT_ZOOM_SCALE_THRESHOLD)) { executeZoomEvent(scaleFactor); return true; } return false; } public boolean onScaleBegin(ScaleGestureDetector detector) { resetScroll(); return true; } public void onScaleEnd(ScaleGestureDetector detector) { // Do nothing } /** * Resets scrolling mode. */ private void resetScroll() { isScrolling = false; updateScroll(); } /** * Updates last scroll positions. */ private void updateScroll() { lastScrollX = scaleGestureDetector.getFocusX(); lastScrollY = scaleGestureDetector.getFocusY(); } /** * Sends zoom event. * * @param scaleFactor scale factor. */ private void executeZoomEvent(float scaleFactor) { resetScroll(); if (scaleFactor > 1.0f) { Action.ZOOM_IN.execute(commands); } else { Action.ZOOM_OUT.execute(commands); } } /** * Sends scroll event. */ private void executeScrollEvent(float deltaX, float deltaY) { commands.scroll(Math.round(deltaX), Math.round(deltaY)); updateScroll(); } /** * Enables of disables scrolling, depending on the current state, * scale factor, and distance from last registered focus position. * * mode should be enabled / disabled depending on the speed of dragging * vs. scale factor. */ private void toggleScrolling( float scaleFactor, float deltaX, float deltaY) { if (!isScrolling && isWithinInvRange(scaleFactor, MT_SCROLL_BEGIN_THRESHOLD)) { float dist = deltaX * deltaX + deltaY * deltaY; if (dist > MT_SCROLL_BEGIN_DIST_THRESHOLD_SQR) { isScrolling = true; } } else if (isScrolling && !isWithinInvRange(scaleFactor, MT_SCROLL_END_THRESHOLD)) { // Stop scrolling if zooming occurs. isScrolling = false; } } /** * Returns {@code true} if {@code (1/upperLimit) &lt; scaleFactor &lt; * upperLimit} */ private boolean isWithinInvRange(float scaleFactor, float upperLimit) { if (upperLimit < 1.0f) { throw new IllegalArgumentException("Upper limit < 1.0f: " + upperLimit); } return 1.0f / upperLimit < scaleFactor && scaleFactor < upperLimit; } } /** * Returns {@code true} if the delta measured when scrolling is enough to * trigger a scroll event. * * @param deltaScroll the amount of scroll wanted */ private static boolean shouldTriggerScrollEvent(float deltaScroll) { return Math.abs(deltaScroll) >= SCROLL_THRESHOLD; } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.util.Debug; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.method.NumberKeyListener; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * Device discovery with mDNS. */ public final class DeviceFinder extends Activity { private static final String LOG_TAG = "DeviceFinder"; /** * Request code used by wifi settings activity */ private static final int CODE_WIFI_SETTINGS = 1; private ProgressDialog progressDialog; private AlertDialog confirmationDialog; private RemoteDevice previousRemoteDevice; private List<RemoteDevice> recentlyConnectedDevices; private InetAddress broadcastAddress; private WifiManager wifiManager; private boolean active; /** * Handles used to pass data back to calling activities. */ public static final String EXTRA_REMOTE_DEVICE = "remote_device"; public static final String EXTRA_RECENTLY_CONNECTED = "recently_connected"; public DeviceFinder() { dataAdapter = new DeviceFinderListAdapter(); trackedDevices = new TrackedDevices(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.device_finder_layout); previousRemoteDevice = getIntent().getParcelableExtra(EXTRA_REMOTE_DEVICE); recentlyConnectedDevices = getIntent().getParcelableArrayListExtra(EXTRA_RECENTLY_CONNECTED); broadcastHandler = new BroadcastHandler(); wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); stbList = (ListView) findViewById(R.id.stb_list); stbList.setOnItemClickListener(selectHandler); stbList.setAdapter(dataAdapter); ((Button) findViewById(R.id.button_manual)).setOnClickListener( new View.OnClickListener() { public void onClick(View v) { buildManualIpDialog().show(); } }); } private void showOtherDevices() { broadcastHandler.removeMessages(DELAYED_MESSAGE); if (progressDialog.isShowing()) { progressDialog.dismiss(); } if (confirmationDialog != null && confirmationDialog.isShowing()) { confirmationDialog.dismiss(); } findViewById(R.id.device_finder).setVisibility(View.VISIBLE); } @Override protected void onStart() { super.onStart(); try { broadcastAddress = getBroadcastAddress(); } catch (IOException e) { Log.e(LOG_TAG, "Failed to get broadcast address"); setResult(RESULT_CANCELED, null); finish(); } startBroadcast(); } @Override protected void onPause() { active = false; broadcastHandler.removeMessages(DELAYED_MESSAGE); super.onPause(); } @Override protected void onResume() { super.onResume(); active = true; } @Override protected void onStop() { if (null != broadcastClient) { broadcastClient.stop(); broadcastClient = null; } super.onStop(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(LOG_TAG, "ActivityResult: " + requestCode + ", " + resultCode); if (requestCode == CODE_WIFI_SETTINGS) { if (!isWifiAvailable()) { buildNoWifiDialog().show(); } else { startBroadcast(); } } } private OnItemClickListener selectHandler = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { RemoteDevice remoteDevice = (RemoteDevice) parent.getItemAtPosition( position); if (remoteDevice != null) { connectToEntry(remoteDevice); } } }; /** * Connects to the chosen entry in the list. * Finishes the activity and returns the informations on the chosen box. * * @param remoteDevice the listEntry representing the box you want to connect to */ private void connectToEntry(RemoteDevice remoteDevice) { Intent resultIntent = new Intent(); resultIntent.putExtra(EXTRA_REMOTE_DEVICE, remoteDevice); setResult(RESULT_OK, resultIntent); finish(); } private void startBroadcast() { if (!isWifiAvailable()) { buildNoWifiDialog().show(); return; } broadcastClient = new BroadcastDiscoveryClient( broadcastAddress, broadcastHandler); broadcastClientThread = new Thread(broadcastClient); broadcastClientThread.start(); Message message = DelayedMessage.BROADCAST_TIMEOUT .obtainMessage(broadcastHandler); broadcastHandler.sendMessageDelayed(message, getResources().getInteger(R.integer.broadcast_timeout)); showProgressDialog(buildBroadcastProgressDialog()); } /** * Returns an intent that starts this activity. */ public static Intent createConnectIntent(Context ctx, RemoteDevice recentlyConnected, ArrayList<RemoteDevice> recentlyConnectedList) { Intent intent = new Intent(ctx, DeviceFinder.class); intent.putExtra(EXTRA_REMOTE_DEVICE, recentlyConnected); intent.putParcelableArrayListExtra(EXTRA_RECENTLY_CONNECTED, recentlyConnectedList); return intent; } private class DeviceFinderListAdapter extends BaseAdapter { public int getCount() { return getTotalSize(); } @Override public boolean hasStableIds() { return false; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return position != trackedDevices.size(); } public Object getItem(int position) { return getRemoteDevice(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ListEntryView liv; if (position == trackedDevices.size()) { return getLayoutInflater().inflate( R.layout.device_list_separator_layout, null); } if (convertView == null || !(convertView instanceof ListEntryView)) { liv = (ListEntryView) getLayoutInflater().inflate( R.layout.device_list_item_layout, null); } else { liv = (ListEntryView) convertView; } liv.setListEntry(getRemoteDevice(position)); return liv; } private int getTotalSize() { return Debug.isDebugDevices() ? trackedDevices.size() + recentlyConnectedDevices.size() + 1 : trackedDevices.size(); } private RemoteDevice getRemoteDevice(int position) { if (position < trackedDevices.size()) { return trackedDevices.get(position); } else if (Debug.isDebugDevices()) { if (position == trackedDevices.size()) { return null; } else if (position < getTotalSize()) { return recentlyConnectedDevices.get( position - trackedDevices.size() - 1); } } return null; } } private InetAddress getBroadcastAddress() throws IOException { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcp = wifi.getDhcpInfo(); int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; byte[] quads = new byte[4]; for (int k = 0; k < 4; k++) { quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); } return InetAddress.getByAddress(quads); } /** * Represents an entry in the box list. */ public static class ListEntryView extends LinearLayout { public ListEntryView(Context context, AttributeSet attrs) { super(context, attrs); myContext = context; } public ListEntryView(Context context) { super(context); myContext = context; } @Override protected void onFinishInflate() { super.onFinishInflate(); tvName = (TextView) findViewById(R.id.device_list_item_name); tvTargetAddr = (TextView) findViewById(R.id.device_list_target_addr); } private void updateContents() { if (null != tvName) { String txt = myContext.getString(R.string.unkown_tgt_name); if ((null != listEntry) && (null != listEntry.getName())) { txt = listEntry.getName(); } tvName.setText(txt); } if (null != tvTargetAddr) { String txt = myContext.getString(R.string.unkown_tgt_addr); if ((null != listEntry) && (null != listEntry.getAddress())) { txt = listEntry.getAddress().getHostAddress(); } tvTargetAddr.setText(txt); } } public RemoteDevice getListEntry() { return listEntry; } public void setListEntry(RemoteDevice listEntry) { this.listEntry = listEntry; updateContents(); } private Context myContext = null; private RemoteDevice listEntry = null; private TextView tvName = null; private TextView tvTargetAddr = null; } private final class BroadcastHandler extends Handler { /** {inheritDoc} */ @Override public void handleMessage(Message msg) { if (msg.what == DELAYED_MESSAGE) { if (!active) { return; } switch ((DelayedMessage) msg.obj) { case BROADCAST_TIMEOUT: broadcastClient.stop(); if (progressDialog.isShowing()) { progressDialog.dismiss(); } buildBroadcastTimeoutDialog().show(); break; case GTV_DEVICE_FOUND: // Check if there is previously connected remote and suggest it // for connection: RemoteDevice toConnect = null; if (previousRemoteDevice != null) { Log.d(LOG_TAG, "Previous Remote Device: " + previousRemoteDevice); toConnect = trackedDevices.findRemoteDevice(previousRemoteDevice); } if (toConnect == null) { Log.d(LOG_TAG, "No previous device found."); // No default found - suggest any device toConnect = trackedDevices.get(0); } progressDialog.dismiss(); confirmationDialog = buildConfirmationDialog(toConnect); confirmationDialog.show(); break; } } switch (msg.what) { case BROADCAST_RESPONSE: BroadcastAdvertisement advert = (BroadcastAdvertisement) msg.obj; RemoteDevice remoteDevice = new RemoteDevice(advert.getServiceName(), advert.getServiceAddress(), advert.getServicePort()); handleRemoteDeviceAdd(remoteDevice); break; } } } private void handleRemoteDeviceAdd(final RemoteDevice remoteDevice) { if (trackedDevices.add(remoteDevice)) { Log.v(LOG_TAG, "Adding new device: " + remoteDevice); // Notify data adapter and update title. dataAdapter.notifyDataSetChanged(); // Show confirmation dialog only for the first STB and only if progress // dialog is visible. if ((trackedDevices.size() == 1) && progressDialog.isShowing()) { broadcastHandler.removeMessages(DELAYED_MESSAGE); // delayed automatic adding Message message = DelayedMessage.GTV_DEVICE_FOUND .obtainMessage(broadcastHandler); broadcastHandler.sendMessageDelayed(message, getResources().getInteger(R.integer.gtv_finder_reconnect_delay)); } } } private ProgressDialog buildBroadcastProgressDialog() { String message; String networkName = getNetworkName(); if (!TextUtils.isEmpty(networkName)) { message = getString(R.string.finder_searching_with_ssid, networkName); } else { message = getString(R.string.finder_searching); } return buildProgressDialog(message, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int which) { broadcastHandler.removeMessages(DELAYED_MESSAGE); showOtherDevices(); } }); } private ProgressDialog buildProgressDialog(String message, DialogInterface.OnClickListener cancelListener) { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage(message); dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { public boolean onKey( DialogInterface dialogInterface, int which, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { finish(); return true; } return false; } }); dialog.setButton(getString(R.string.finder_cancel), cancelListener); return dialog; } private AlertDialog buildConfirmationDialog(final RemoteDevice remoteDevice) { AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.device_info, null); final TextView ipTextView = (TextView) view.findViewById(R.id.device_info_ip_address); if (remoteDevice.getName() != null) { builder.setMessage(remoteDevice.getName()); } ipTextView.setText(remoteDevice.getAddress().getHostAddress()); return builder .setTitle(R.string.finder_label) .setCancelable(false) .setPositiveButton(R.string.finder_connect, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { connectToEntry(remoteDevice); } }) .setNegativeButton( R.string.finder_add_other, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { showOtherDevices(); } }) .create(); } private AlertDialog buildManualIpDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.manual_ip, null); final EditText ipEditText = (EditText) view.findViewById(R.id.manual_ip_entry); ipEditText.setFilters(new InputFilter[] { new NumberKeyListener() { @Override protected char[] getAcceptedChars() { return "0123456789.:".toCharArray(); } public int getInputType() { return InputType.TYPE_CLASS_NUMBER; } } }); builder .setPositiveButton( R.string.manual_ip_connect, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { RemoteDevice remoteDevice = remoteDeviceFromString( ipEditText.getText().toString()); if (remoteDevice != null) { connectToEntry(remoteDevice); } else { Toast.makeText(DeviceFinder.this, getString(R.string.manual_ip_error_address), Toast.LENGTH_LONG).show(); } } }) .setNegativeButton( R.string.manual_ip_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setCancelable(true) .setTitle(R.string.manual_ip_label) .setMessage(R.string.manual_ip_entry_label) .setView(view); return builder.create(); } private AlertDialog buildBroadcastTimeoutDialog() { String message; String networkName = getNetworkName(); if (!TextUtils.isEmpty(networkName)) { message = getString(R.string.finder_no_devices_with_ssid, networkName); } else { message = getString(R.string.finder_no_devices); } return buildTimeoutDialog(message, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { startBroadcast(); } }); } private AlertDialog buildTimeoutDialog(CharSequence message, DialogInterface.OnClickListener retryListener) { AlertDialog.Builder builder = new AlertDialog.Builder(this); return builder .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.finder_wait, retryListener) .setNegativeButton( R.string.finder_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { setResult(RESULT_CANCELED, null); finish(); } }) .create(); } private AlertDialog buildNoWifiDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.finder_wifi_not_available); builder.setCancelable(false); builder.setPositiveButton(R.string.finder_configure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); startActivityForResult(intent, CODE_WIFI_SETTINGS); } }); builder.setNegativeButton( R.string.finder_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int id) { setResult(RESULT_CANCELED, null); finish(); } }); return builder.create(); } private void showProgressDialog(ProgressDialog newDialog) { if ((progressDialog != null) && progressDialog.isShowing()) { progressDialog.dismiss(); } progressDialog = newDialog; newDialog.show(); } private RemoteDevice remoteDeviceFromString(String text) { String[] ipPort = text.split(":"); int port; if (ipPort.length == 1) { port = getResources().getInteger(R.integer.manual_default_port); } else if (ipPort.length == 2) { try { port = Integer.parseInt(ipPort[1]); } catch (NumberFormatException e) { return null; } } else { return null; } try { InetAddress address = InetAddress.getByName(ipPort[0]); return new RemoteDevice( getString(R.string.manual_ip_default_box_name), address, port); } catch (UnknownHostException e) { } return null; } private ListView stbList; private final DeviceFinderListAdapter dataAdapter; private BroadcastHandler broadcastHandler; private BroadcastDiscoveryClient broadcastClient; private Thread broadcastClientThread; private TrackedDevices trackedDevices; /** * Handler message number for a service update from broadcast client. */ public static final int BROADCAST_RESPONSE = 100; /** * Handler message number for all delayed messages */ private static final int DELAYED_MESSAGE = 101; private enum DelayedMessage { BROADCAST_TIMEOUT, GTV_DEVICE_FOUND; Message obtainMessage(Handler handler) { Message message = handler.obtainMessage(DELAYED_MESSAGE); message.obj = this; return message; } } private static class TrackedDevices implements Iterable<RemoteDevice> { private final Map<InetAddress, RemoteDevice> devicesByAddress; private final SortedSet<RemoteDevice> devices; private RemoteDevice[] deviceArray; private static Comparator<RemoteDevice> COMPARATOR = new Comparator<RemoteDevice>() { public int compare(RemoteDevice remote1, RemoteDevice remote2) { int result = remote1.getName().compareToIgnoreCase(remote2.getName()); if (result != 0) { return result; } return remote1.getAddress().getHostAddress().compareTo( remote2.getAddress().getHostAddress()); } }; TrackedDevices() { devicesByAddress = new HashMap<InetAddress, RemoteDevice>(); devices = new TreeSet<RemoteDevice>(COMPARATOR); } public boolean add(RemoteDevice remoteDevice) { InetAddress address = remoteDevice.getAddress(); if (!devicesByAddress.containsKey(address)) { devicesByAddress.put(address, remoteDevice); devices.add(remoteDevice); deviceArray = null; return true; } // address? return false; } public int size() { return devices.size(); } public RemoteDevice get(int index) { return getDeviceArray()[index]; } private RemoteDevice[] getDeviceArray() { if (deviceArray == null) { deviceArray = devices.toArray(new RemoteDevice[0]); } return deviceArray; } public Iterator<RemoteDevice> iterator() { return devices.iterator(); } public RemoteDevice findRemoteDevice(RemoteDevice remoteDevice) { RemoteDevice byIp = devicesByAddress.get(remoteDevice.getAddress()); if (byIp != null && byIp.getName().equals(remoteDevice.getName())) { return byIp; } for (RemoteDevice device : devices) { Log.d(LOG_TAG, "New device: " + device); if (remoteDevice.getName().equals(device.getName())) { return device; } } return byIp; } } private boolean isWifiAvailable() { if (!wifiManager.isWifiEnabled()) { return false; } WifiInfo info = wifiManager.getConnectionInfo(); return info != null && info.getIpAddress() != 0; } private String getNetworkName() { if (!isWifiAvailable()) { return null; } WifiInfo info = wifiManager.getConnectionInfo(); return info != null ? info.getSSID() : null; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Simple tutorial. * */ public class TutorialActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tutorial); ((Button) findViewById(R.id.tutorial_button)).setOnClickListener( new View.OnClickListener() { public void onClick(View v) { finish(); } }); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.TouchHandler.Mode; import com.google.android.apps.tvremote.util.Action; import com.google.android.apps.tvremote.widget.ImeInterceptView; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.widget.TextView; /** * Text input activity. * <p> * Displays a soft keyboard if needed. * */ public final class KeyboardActivity extends BaseActivity { /** * Captures text inputs. */ private final TextInputHandler textInputHandler; /** * The main view. */ private ImeInterceptView view; public KeyboardActivity() { textInputHandler = new TextInputHandler(this, getCommands()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.keyboard); view = (ImeInterceptView) findViewById(R.id.keyboard); view.requestFocus(); view.setInterceptor(new ImeInterceptView.Interceptor() { public boolean onKeyEvent(KeyEvent event) { KeyboardActivity.this.onUserInteraction(); if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: finish(); return true; case KeyEvent.KEYCODE_SEARCH: Action.NAVBAR.execute(getCommands()); return true; case KeyEvent.KEYCODE_ENTER: Action.ENTER.execute(getCommands()); finish(); return true; } } return textInputHandler.handleKey(event); } public boolean onSymbol(char c) { KeyboardActivity.this.onUserInteraction(); textInputHandler.handleChar(c); return false; } }); textInputHandler.setDisplay( (TextView) findViewById(R.id.text_feedback_chars)); // Attach touch handler to the touch pad. new TouchHandler(view, Mode.POINTER_MULTITOUCH, getCommands()); } @Override public boolean onTrackballEvent(MotionEvent event){ if (event.getAction() == MotionEvent.ACTION_DOWN){ finish(); } return super.onTrackballEvent(event); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.Timer; import java.util.TimerTask; /** * An implementation of a trivial broadcast discovery protocol. * <p> * This client sends L3 broadcasts to probe for particular services on the * network. */ public class BroadcastDiscoveryClient implements Runnable { private static final String LOG_TAG = "BroadcastDiscoveryClient"; /** * UDP port to send probe messages to. */ private static final int BROADCAST_SERVER_PORT = 9101; /** * Frequency of probe messages. */ private static final int PROBE_INTERVAL_MS = 6000; /** * Command name for a discovery request. */ private static final String COMMAND_DISCOVER = "discover"; /** * Service name to discover. */ private static final String DESIRED_SERVICE = "_anymote._tcp"; /** * Broadcast address of the local device. */ private final InetAddress mBroadcastAddress; /** * Timer to send probes. */ private final Timer mProbeTimer; /** * TimerTask to send probes. */ private final TimerTask mProbeTimerTask; /** * Handle to main thread. */ private final Handler mHandler; /** * Send/receive socket. */ private final DatagramSocket mSocket; /** * Constructor * * @param broadcastAddress destination address for probes * @param handler update Handler in main thread */ public BroadcastDiscoveryClient(InetAddress broadcastAddress, Handler handler) { mBroadcastAddress = broadcastAddress; mHandler = handler; try { mSocket = new DatagramSocket(); // binds to random port mSocket.setBroadcast(true); } catch (SocketException e) { Log.e(LOG_TAG, "Could not create broadcast client socket.", e); throw new RuntimeException(); } mProbeTimer = new Timer(); mProbeTimerTask = new TimerTask() { @Override public void run() { BroadcastDiscoveryClient.this.sendProbe(); } }; Log.i(LOG_TAG, "Starting client on address " + mBroadcastAddress); } /** {@inheritDoc} */ public void run() { Log.i(LOG_TAG, "Broadcast client thread starting."); byte[] buffer = new byte[256]; mProbeTimer.schedule(mProbeTimerTask, 0, PROBE_INTERVAL_MS); while (true) { try { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); mSocket.receive(packet); handleResponsePacket(packet); } catch (InterruptedIOException e) { // timeout } catch (IOException e) { // SocketException - stop() was called mProbeTimer.cancel(); break; } } Log.i(LOG_TAG, "Exiting client loop."); mProbeTimer.cancel(); } /** * Sends a single broadcast discovery request. */ private void sendProbe() { DatagramPacket packet = makeRequestPacket(DESIRED_SERVICE, mSocket.getLocalPort()); try { mSocket.send(packet); } catch (IOException e) { Log.e(LOG_TAG, "Exception sending broadcast probe", e); return; } } /** * Immediately stops the receiver thread, and cancels the probe timer. */ public void stop() { if (mSocket != null) { mSocket.close(); } } /** * Constructs a new probe packet. * * @param serviceName the service name to discover * @param responsePort the udp port number for replies * @return a new DatagramPacket */ private DatagramPacket makeRequestPacket(String serviceName, int responsePort) { String message = COMMAND_DISCOVER + " " + serviceName + " " + responsePort + "\n"; byte[] buf = message.getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, mBroadcastAddress, BROADCAST_SERVER_PORT); return packet; } /** * Parse a received packet, and notify the main thread if valid. * * @param packet The locally-received DatagramPacket */ private void handleResponsePacket(DatagramPacket packet) { String strPacket = new String(packet.getData(), 0, packet.getLength()); String tokens[] = strPacket.trim().split("\\s+"); if (tokens.length != 3) { Log.w(LOG_TAG, "Malformed response: expected 3 tokens, got " + tokens.length); return; } BroadcastAdvertisement advert; try { String serviceType = tokens[0]; if (!serviceType.equals(DESIRED_SERVICE)) { return; } String serviceName = tokens[1]; int port = Integer.parseInt(tokens[2]); InetAddress addr = packet.getAddress(); Log.v(LOG_TAG, "Broadcast response: " + serviceName + ", " + addr + ", " + port); advert = new BroadcastAdvertisement(serviceName, addr, port); } catch (NumberFormatException e) { return; } Message message = mHandler.obtainMessage(DeviceFinder.BROADCAST_RESPONSE, advert); mHandler.sendMessage(message); } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.polo.ssl.SslUtil; import android.content.Context; import android.os.Build; import android.util.Log; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Enumeration; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; /** * Key store manager. * */ public final class KeyStoreManager { private static final String LOG_TAG = "KeyStoreUtil"; private static final String KEYSTORE_FILENAME = "ipremote.keystore"; private static final char[] KEYSTORE_PASSWORD = "1234567890".toCharArray(); /** * Alias for the remote controller (local) identity in the {@link KeyStore}. */ private static final String LOCAL_IDENTITY_ALIAS = "anymote-remote"; /** * Alias pattern for anymote server identities in the {@link KeyStore} */ private static final String REMOTE_IDENTITY_ALIAS_PATTERN = "anymote-server-%X"; private final Context mContext; private final KeyStore mKeyStore; public KeyStoreManager(Context context) { this.mContext = context; this.mKeyStore = load(); } /** * Loads key store from storage, or creates new one if storage is missing key * store or corrupted. */ private KeyStore load() { KeyStore keyStore; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { throw new IllegalStateException( "Unable to get default instance of KeyStore", e); } try { FileInputStream fis = mContext.openFileInput(KEYSTORE_FILENAME); keyStore.load(fis, KEYSTORE_PASSWORD); } catch (IOException e) { Log.v(LOG_TAG, "Unable open keystore file", e); keyStore = null; } catch (GeneralSecurityException e) { Log.v(LOG_TAG, "Unable open keystore file", e); keyStore = null; } if (keyStore != null) { // KeyStore loaded return keyStore; } try { keyStore = createKeyStore(); } catch (GeneralSecurityException e) { throw new IllegalStateException("Unable to create identity KeyStore", e); } store(keyStore); return keyStore; } public boolean hasServerIdentityAlias() { try { if (!mKeyStore.containsAlias(LOCAL_IDENTITY_ALIAS)) { Log.e( LOG_TAG, "Key store missing identity for " + LOCAL_IDENTITY_ALIAS); return false; } } catch (KeyStoreException e) { Log.e(LOG_TAG, "Key store exception occurred", e); return false; } return true; } public void initializeKeyStore(String id) { clearKeyStore(); try { Log.v(LOG_TAG, "Generating key pair ..."); KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = kg.generateKeyPair(); Log.v(LOG_TAG, "Generating certificate ..."); String name = getCertificateName(id); X509Certificate cert = SslUtil.generateX509V3Certificate(keyPair, name); Certificate[] chain = {cert}; Log.v(LOG_TAG, "Adding key to keystore ..."); mKeyStore.setKeyEntry( LOCAL_IDENTITY_ALIAS, keyPair.getPrivate(), null, chain); Log.d(LOG_TAG, "Key added!"); } catch (GeneralSecurityException e) { throw new IllegalStateException("Unable to create identity KeyStore", e); } store(mKeyStore); } private static KeyStore createKeyStore() throws GeneralSecurityException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { keyStore.load(null, KEYSTORE_PASSWORD); } catch (IOException e) { throw new GeneralSecurityException("Unable to create empty keyStore", e); } return keyStore; } private void store(KeyStore keyStore) { try { FileOutputStream fos = mContext.openFileOutput(KEYSTORE_FILENAME, Context.MODE_PRIVATE); keyStore.store(fos, KEYSTORE_PASSWORD); fos.close(); } catch (IOException e) { throw new IllegalStateException("Unable to store keyStore", e); } catch (GeneralSecurityException e) { throw new IllegalStateException("Unable to store keyStore", e); } } /** * Stores current state of key store. */ public synchronized void store() { store(mKeyStore); } /** * Returns the name that should be used in a new certificate. * <p> * The format is: "CN=anymote/PRODUCT/DEVICE/MODEL/unique identifier" */ private static final String getCertificateName(String id) { return "CN=anymote/" + Build.PRODUCT + "/" + Build.DEVICE + "/" + Build.MODEL + "/" + id; } /** * @return key managers loaded for this service. */ public synchronized KeyManager[] getKeyManagers() throws GeneralSecurityException { if (mKeyStore == null) { throw new NullPointerException("null mKeyStore"); } KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); factory.init(mKeyStore, "".toCharArray()); return factory.getKeyManagers(); } /** * @return trust managers loaded for this service. */ public synchronized TrustManager[] getTrustManagers() throws GeneralSecurityException { // Build a new set of TrustManagers based on the KeyStore. TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(mKeyStore); return tmf.getTrustManagers(); } public synchronized void storeCertificate(Certificate peerCert) { try { String alias = String.format( KeyStoreManager.REMOTE_IDENTITY_ALIAS_PATTERN, peerCert.hashCode()); if (mKeyStore.containsAlias(alias)) { Log.w(LOG_TAG, "Deleting existing entry for " + alias); mKeyStore.deleteEntry(alias); } Log.i(LOG_TAG, "Adding cert to keystore: " + alias); mKeyStore.setCertificateEntry(alias, peerCert); store(); } catch (KeyStoreException e) { Log.e(LOG_TAG, "Storing cert failed", e); } } private void clearKeyStore() { try { for (Enumeration<String> e = mKeyStore.aliases(); e.hasMoreElements();) { final String alias = e.nextElement(); Log.v(LOG_TAG, "Deleting alias: " + alias); mKeyStore.deleteEntry(alias); } } catch (KeyStoreException e) { Log.e(LOG_TAG, "Clearing certificates failed", e); } store(); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import java.net.InetAddress; /** * A wrapper for information in a broadcast advertisement. * */ public final class BroadcastAdvertisement { /** * Name of the service. */ private final String mServiceName; /** * Address of the service. */ private final InetAddress mServiceAddress; /** * Port of the service. */ private final int mServicePort; BroadcastAdvertisement(String name, InetAddress addr, int port) { mServiceName = name; mServiceAddress = addr; mServicePort = port; } public String getServiceName() { return mServiceName; } public InetAddress getServiceAddress() { return mServiceAddress; } public int getServicePort() { return mServicePort; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; /** * A utility class that contains the constants used in the anymote protocol. * */ public final class ProtocolConstants { /** * Data type used to send a string in a data message. */ public static final String DATA_TYPE_STRING = "com.google.tv.string"; /** * Device name used upon connection. */ public static final String DEVICE_NAME = "android"; /** * No constructor, this class contains only constants. */ private ProtocolConstants() {} }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import com.google.anymote.Key.Action; import com.google.anymote.Key.Code; /** * Dummy sender. * */ public class DummySender implements ICommandSender { public void moveRelative(int deltaX, int deltaY) { } public void click(Action action) { } public void keyPress(Code key) { } public void key(Code keycode, Action action) { } public void flingUrl(String url) { } public void scroll(int deltaX, int deltaY) { } public void string(String text) { } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import com.google.anymote.Key.Action; import com.google.anymote.Key.Code; /** * Utility class for building command wrappers. * */ public class Commands { private Commands() { // prevent instantiation throw new IllegalStateException(); } /** * Builds move command. * * @param deltaX an integer representing the amount of horizontal motion * @param deltaY an integer representing the amount of vertical motion */ public static Command buildMoveCommand(final int deltaX, final int deltaY) { return new Command() { public void execute(ICommandSender sender) { sender.moveRelative(deltaX, deltaY); } }; } /** * Builds key press command. * * @param key the pressed key */ public static Command buildKeyPressCommand(final Code key) { return new Command() { public void execute(ICommandSender sender) { sender.keyPress(key); } }; } /** * Builds detailed key command. * * @param keycode the keycode to send * @param action the corresponding action */ public static Command buildKeyCommand(final Code keycode, final Action action) { return new Command() { public void execute(ICommandSender sender) { sender.key(keycode, action); } }; } /** * Builds fling command. * * @param url a string representing the target URL */ public static Command buildFlingUrlCommand(final String url) { return new Command() { public void execute(ICommandSender sender) { sender.flingUrl(url); } }; } /** * Builds scroll command. * * @param deltaX an integer representing the amount of horizontal scrolling * @param deltaY an integer representing the amount of vertical scrolling */ public static Command buildScrollCommand(final int deltaX, final int deltaY) { return new Command() { public void execute(ICommandSender sender) { sender.scroll(deltaX, deltaY); } }; } /** * Builds string command. * * @param text the message to send */ public static Command buildStringCommand(final String text) { return new Command() { public void execute(ICommandSender sender) { sender.string(text); } }; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import com.google.anymote.Key.Action; import com.google.anymote.Key.Code; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; /** * An implementation of the ICommand sender that lies on top of the core * service and sends commands with a separate thread. * */ public final class QueuingSender implements ICommandSender { private static final String LOG_TAG = "QueuingSender"; /** * Buffered command that is will be sent when connected. */ private Command bufferedCommand; private final Handler handler; /** * Action that should be taken when sender is missing. */ private enum MissingAction { /** * Do nothing. */ IGNORE, /** * Missing action listener should be notified. */ NOTIFY, /** * Command should be enqueued for future execution. */ ENQUEUE } /** * Listener that will be notified about attempt of sending an event when no * sender is configured. */ public interface MissingSenderListener { public void onMissingSender(); } /** * The remote service through which commands should be sent. */ private ICommandSender sender; private final MissingSenderListener missingSenderListener; public QueuingSender(MissingSenderListener listener) { missingSenderListener = listener; HandlerThread handlerThread = new HandlerThread("Sender looper"); handlerThread.start(); handler = new Handler(handlerThread.getLooper(), new Handler.Callback() { public boolean handleMessage(Message msg) { Command command = (Command) msg.obj; ICommandSender currentSender = sender; if (currentSender != null) { command.execute(currentSender); } else { Log.w(LOG_TAG, "Sender removed before sending command"); } return true; } }); } public synchronized void setSender(ICommandSender sender) { this.sender = sender; if (sender != null) { flushBufferedEvents(); } } private boolean hasSender() { return sender != null; } private synchronized void sendCommand(Command command, MissingAction actionIfMissing) { if (!hasSender()) { switch (actionIfMissing) { case IGNORE: break; case ENQUEUE: bufferedCommand = command; break; case NOTIFY: missingSenderListener.onMissingSender(); break; default: throw new IllegalStateException("Unsupported action: " + actionIfMissing); } return; } Message msg = handler.obtainMessage(0, command); handler.sendMessage(msg); } private void sendCommand(Command command) { sendCommand(command, MissingAction.NOTIFY); } public void flingUrl(String url) { sendCommand(Commands.buildFlingUrlCommand(url), MissingAction.ENQUEUE); } public void key(Code keycode, Action action) { sendCommand(Commands.buildKeyCommand(keycode, action)); } public void keyPress(Code key) { sendCommand(Commands.buildKeyPressCommand(key)); } public void moveRelative(int deltaX, int deltaY) { sendCommand(Commands.buildMoveCommand(deltaX, deltaY)); } public void scroll(int deltaX, int deltaY) { sendCommand(Commands.buildScrollCommand(deltaX, deltaY)); } public void string(String text) { sendCommand(Commands.buildStringCommand(text)); } /** * Sends buffered events (currently last flinged URI is buffered). */ private void flushBufferedEvents() { if (!hasSender()) { throw new IllegalStateException("No sender is set."); } if (bufferedCommand != null) { sendCommand(bufferedCommand, MissingAction.IGNORE); bufferedCommand = null; } } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import com.google.anymote.Key.Action; import com.google.anymote.Key.Code; /** * Defines an API to send control commands to a box. * */ public interface ICommandSender { /** * Moves the pointer relatively. * * @param deltaX an integer representing the amount of horizontal motion * @param deltaY an integer representing the amount of vertical motion */ public void moveRelative(int deltaX, int deltaY); /** * Issues a key press. * <p> * This is equivalent to sending and {@link Action#DOWN} followed * immediately by an {@link Action#UP} * * @param key the pressed key */ public void keyPress(Code key); /** * A detailed key event. * * @param keycode the keycode to send * @param action the corresponding action */ public void key(Code keycode, Action action); /** * Sends a URL for display. * * @param url a string representing the target URL */ public void flingUrl(String url); /** * Issues scrolling command. * * @param deltaX an integer representing the amount of horizontal scrolling * @param deltaY an integer representing the amount of vertical scrolling */ public void scroll(int deltaX, int deltaY); /** * Sends a string. * * @param text the message to send */ public void string(String text); }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; /** * Command wrapper interface. * */ public interface Command { /** * Executes command on provided command sender. * * @param sender command sender. */ public void execute(ICommandSender sender); }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import java.util.concurrent.atomic.AtomicInteger; /** * This class manages the requests for acknowledgments that are sent to the * server to monitor the connection and the replies from it. * */ public final class AckManager { private static final String LOG_TAG = "AckManager"; private static final boolean DEBUG = false; /** * Duration between two ack requests. */ private static final long PONG_PERIOD = 3 * 1000; /** * Timeout before the connection is declared lost. */ private static final long PING_TIMEOUT = 500; /** * Interface used when the connection is lost. */ public interface Listener { /** * Called when the connection is considered lost, if no acknowledgment * message has been received after {@link #PING_TIMEOUT}. */ public void onTimeout(); } private final Listener connectionListener; private final AckHandler handler; private final AnymoteSender sender; public AckManager(Listener listener, AnymoteSender sender) { HandlerThread handlerThread = new HandlerThread("AckHandlerThread"); handlerThread.start(); handler = new AckHandler(handlerThread.getLooper()); connectionListener = listener; this.sender = sender; } /** * Notifies the AckManager that a acknowledgment message has been received. */ public void onAck() { handler.sendEmptyMessageAndIncrement(Action.ACK); } public void start() { handler.sendEmptyMessageAndIncrement(Action.START); } public void cancel() { handler.getLooper().quit(); } /** * Notifies the listener that the connection has been lost. */ private void connectionTimeout() { connectionListener.onTimeout(); } private enum Action { START, PING, ACK, TIMEOUT, } /** * Inner class that handles start / stop / pong / ack / timeout messages * from multiple threads, and serializes their execution. */ private final class AckHandler extends Handler { /** * The current sequence number. */ private final AtomicInteger sequence; AckHandler(Looper looper) { super(looper); sequence = new AtomicInteger(); } @Override public void handleMessage(Message msg) { Action action = actionValueOf(msg.what); if (DEBUG) { Log.d(LOG_TAG, "action=" + action + " : msg=" + msg + " : seq=" + sequence.get() + " @ " + System.currentTimeMillis()); } switch (action) { case START: handleStart(); break; case PING: handlePing(); break; case ACK: handleAck(); break; case TIMEOUT: handleTimeout(msg.arg1); break; } } private void handlePing() { int token = sequence.incrementAndGet(); removeMessages(Action.ACK, Action.TIMEOUT); sender.ping(); sendMessageDelayed(obtainMessage(Action.TIMEOUT, token), PING_TIMEOUT); } private void handleStart() { sequence.incrementAndGet(); removeMessages(Action.TIMEOUT, Action.PING, Action.ACK); handlePing(); } private void handleAck() { sequence.incrementAndGet(); removeMessages(Action.TIMEOUT); sendMessageDelayed(obtainMessage(Action.PING), PONG_PERIOD); } private void handleTimeout(int token) { removeMessages(Action.PING, Action.ACK); if (sequence.compareAndSet(token, token + 1)) { connectionTimeout(); } sequence.incrementAndGet(); } private void removeMessages(Action... actions) { for (Action action : actions) { removeMessages(action.ordinal()); } } private Message obtainMessage(Action action) { return obtainMessage(action.ordinal()); } private Message obtainMessage(Action action, int arg1) { return obtainMessage(action.ordinal(), arg1, 0); } private Action actionValueOf(int what) { return Action.values()[what]; } void sendEmptyMessageAndIncrement(Action action) { sequence.incrementAndGet(); sendEmptyMessage(action.ordinal()); } } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote.protocol; import com.google.android.apps.tvremote.CoreService; import com.google.android.apps.tvremote.protocol.AckManager.Listener; import com.google.anymote.Key.Action; import com.google.anymote.Key.Code; import com.google.anymote.Messages.DataList; import com.google.anymote.Messages.FlingResult; import com.google.anymote.common.AnymoteFactory; import com.google.anymote.common.ConnectInfo; import com.google.anymote.common.ErrorListener; import com.google.anymote.device.DeviceAdapter; import com.google.anymote.device.MessageReceiver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; import java.io.IOException; import java.net.Socket; /** * An implementation of the ICommandSender interface which uses the Anymote * protocol. * */ public final class AnymoteSender implements ICommandSender { private final static String LOG_TAG = "AnymoteSender"; /** * Core service that manages the connection to the server. */ private final CoreService coreService; /** * Receiver for the Anymote protocol. */ private final MessageReceiver receiver; /** * Error listener for the Anymote protocol. */ private final ErrorListener errorListener; /** * Sender for the Anymote protocol. */ private DeviceAdapter deviceAdapter; /** * The Ack manager. */ private final AckManager ackManager; public AnymoteSender(CoreService service) { coreService = service; ackManager = new AckManager(new Listener() { public void onTimeout() { onConnectionError(); } }, this); receiver = new MessageReceiver() { public void onAck() { ackManager.onAck(); } public void onData(String type, String data) { Log.d(LOG_TAG, "onData: " + type + " / " + data); } public void onDataList(DataList dataList) { Log.d(LOG_TAG, "onDataList: " + dataList.toString()); } public void onFlingResult( FlingResult flingResult, Integer sequenceNumber) { Log.d(LOG_TAG, "onFlingResult: " + flingResult.toString() + " " + sequenceNumber); } }; errorListener = new ErrorListener() { public void onIoError(String message, Throwable exception) { Log.d(LOG_TAG, "IoError: " + message, exception); onConnectionError(); } }; } /** * Sets the socket the sender will use to communicate with the server. * * @param socket the socket to the server */ public boolean setSocket(Socket socket) { if (socket == null) { throw new NullPointerException("null socket"); } return instantiateProtocol(socket); } public void click(Action action) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendKeyEvent(Code.BTN_MOUSE, action); } } public void flingUrl(String url) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendFling(url, 0); } } public void key(Code keycode, Action action) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendKeyEvent(keycode, action); } } public void keyPress(Code key) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendKeyEvent(key, Action.DOWN); sender.sendKeyEvent(key, Action.UP); } } public void moveRelative(int deltaX, int deltaY) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendMouseMove(deltaX, deltaY); } } public void scroll(int deltaX, int deltaY) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendMouseWheel(deltaX, deltaY); } } public void string(String text) { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendData(ProtocolConstants.DATA_TYPE_STRING, text); } } public void ping() { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendPing(); } } private void sendConnect() { DeviceAdapter sender = getSender(); if (sender != null) { sender.sendConnect(new ConnectInfo(ProtocolConstants.DEVICE_NAME, getVersionCode())); } } /** * Called when an error occurs on the transmission. */ private void onConnectionError() { if (disconnect()) { coreService.notifyConnectionFailed(); } } /** * Instantiates the protocol. */ private boolean instantiateProtocol(Socket socket) { disconnect(); try { deviceAdapter = AnymoteFactory.getDeviceAdapter(receiver, socket.getInputStream(), socket.getOutputStream(), errorListener); } catch (IOException e) { Log.d(LOG_TAG, "Unable to create sender", e); deviceAdapter = null; return false; } sendConnect(); ackManager.start(); return true; } /** * Returns the version number as defined in Android manifest * {@code versionCode} */ private int getVersionCode() { try { PackageInfo info = coreService.getPackageManager().getPackageInfo( coreService.getPackageName(), 0 /* basic info */); return info.versionCode; } catch (NameNotFoundException e) { Log.d(LOG_TAG, "cannot retrieve version number, package name not found"); } return -1; } public synchronized boolean disconnect() { ackManager.cancel(); if (deviceAdapter != null) { deviceAdapter.stop(); deviceAdapter = null; return true; } return false; } private DeviceAdapter getSender() { return deviceAdapter; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import java.util.LinkedList; import java.util.Queue; /** * Abstract activity that handles connection to the {@link CoreService}. * * The activity connects to service in {@link #onCreate(Bundle)}, and * disconnects in {@link #onDestroy()}. Upon successful connection, and before * disconnection appropriate callbacks are invoked. * */ public abstract class CoreServiceActivity extends Activity { private static final String LOG_TAG = "CoreServiceActivity"; /** * Used to connect to the background service. */ private ServiceConnection serviceConnection; private CoreService coreService; private Queue<Runnable> runnableQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); runnableQueue = new LinkedList<Runnable>(); connectToService(); } @Override protected void onDestroy() { disconnectFromService(); super.onDestroy(); } /** * Opens the connection to the underlying service. */ private void connectToService() { serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { coreService = ((CoreService.LocalBinder) service).getService(); runQueuedRunnables(); onServiceAvailable(coreService); } public void onServiceDisconnected(ComponentName name) { onServiceDisconnecting(coreService); coreService = null; } }; Intent intent = new Intent(this, CoreService.class); bindService(intent, serviceConnection, BIND_AUTO_CREATE); } /** * Closes the connection to the background service. */ private synchronized void disconnectFromService() { unbindService(serviceConnection); serviceConnection = null; } private void runQueuedRunnables() { Runnable runnable; while ((runnable = runnableQueue.poll()) != null) { runnable.run(); } } /** * Callback that is called when the core service become available. */ protected abstract void onServiceAvailable(CoreService coreService); /** * Callback that is called when the core service is about disconnecting. */ protected abstract void onServiceDisconnecting(CoreService coreService); /** * Starts an activity based on its class. */ protected void showActivity(Class<?> activityClass) { Intent intent = new Intent(this, activityClass); startActivity(intent); } protected ConnectionManager getConnectionManager() { return coreService; } protected KeyStoreManager getKeyStoreManager() { if (coreService != null) { return coreService.getKeyStoreManager(); } return null; } protected boolean executeWhenCoreServiceAvailable(Runnable runnable) { if (coreService == null) { Log.d(LOG_TAG, "Queueing runnable: " + runnable); runnableQueue.offer(runnable); return false; } runnable.run(); return true; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.os.Parcel; import android.os.Parcelable; import java.net.InetAddress; /** * Container for keeping target server configuration. * */ public final class RemoteDevice implements Parcelable { private final String name; private final InetAddress address; private final int port; public RemoteDevice(String name, InetAddress address, int port) { if (address == null) { throw new NullPointerException("Address is null"); } this.name = name; this.address = address; this.port = port; } /** * @return name of the controlled device. */ public String getName() { return name; } /** * @return address of the controlled device. */ public InetAddress getAddress() { return address; } /** * @return port of the controlled device. */ public int getPort() { return port; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof RemoteDevice)) { return false; } RemoteDevice that = (RemoteDevice) obj; return equal(this.name, that.name) && equal(this.address, that.address) && (this.port == that.port); } @Override public int hashCode() { int code = 7; code = code * 31 + (name != null ? name.hashCode() : 0); code = code * 31 + (address != null ? address.hashCode() : 0); code = code * 31 + port; return code; } @Override public String toString() { return String.format("%s [%s:%d]", name, address, port); } private static <T> boolean equal(T obj1, T obj2) { if (obj1 == null) { return obj2 == null; } return obj1.equals(obj2); } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(name); parcel.writeSerializable(address); parcel.writeInt(port); } public static final Parcelable.Creator<RemoteDevice> CREATOR = new Parcelable.Creator<RemoteDevice>() { public RemoteDevice createFromParcel(Parcel parcel) { return new RemoteDevice(parcel); } public RemoteDevice[] newArray(int size) { return new RemoteDevice[size]; } }; private RemoteDevice(Parcel parcel) { this(parcel.readString(), (InetAddress) parcel.readSerializable(), parcel.readInt()); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.protocol.ICommandSender; import com.google.android.apps.tvremote.util.Action; import com.google.anymote.Key.Code; import android.content.Context; import android.view.KeyEvent; import android.widget.TextView; /** * Handles text-related key input. * * This class also manages a view that displays the last few characters typed. * */ public final class TextInputHandler { /** * Interface to send commands during a touch sequence. */ private final ICommandSender commands; /** * Context. */ private final Context context; /** * {@code true} if display should be cleared before next output. */ private boolean clearNextTime; public TextInputHandler(Context context, ICommandSender commands) { this.commands = commands; this.context = context; } /** * The view that contains the visual feedback for text input. */ private TextView display; /** * Handles a character input. * * @param c the character being typed * @return {@code true} if the event was handled */ public boolean handleChar(char c) { if (isValidCharacter(c)) { String str = String.valueOf(c); appendDisplayedText(str); commands.string(str); return true; } return false; } /** * Handles a key event. * * @param event the key event to handle * @return {@code true} if the event was handled */ public boolean handleKey(KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } int code = event.getKeyCode(); if (code == KeyEvent.KEYCODE_ENTER) { displaySingleTimeMessage(context.getString(R.string.keyboard_enter)); Action.ENTER.execute(commands); return true; } if (code == KeyEvent.KEYCODE_DEL) { displaySingleTimeMessage(context.getString(R.string.keyboard_del)); Action.BACKSPACE.execute(commands); return true; } if (code == KeyEvent.KEYCODE_SPACE) { appendDisplayedText(" "); commands.keyPress(Code.KEYCODE_SPACE); return true; } int c = event.getUnicodeChar(); return handleChar((char) c); } private boolean isValidCharacter(int unicode) { return unicode > 0 && unicode < 256; } public void setDisplay(TextView textView) { display = textView; } private void appendDisplayedText(CharSequence seq) { if (display != null) { if (!clearNextTime) { seq = new StringBuffer(display.getText()).append(seq); } display.setText(seq); } clearNextTime = false; } private void displaySingleTimeMessage(CharSequence seq) { if (display != null) { display.setText(seq); clearNextTime = true; } } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.util; import java.util.LinkedHashMap; /** * Linked hash map that limits number of added entries. If exceeded the eldest * element is removed. * * @param <K> key type * @param <V> value type */ public class LimitedLinkedHashMap<K, V> extends LinkedHashMap<K, V> { private final int maxSize; /** * Constructor. * * @param maxSize maximum number of elements given hash map can hold. */ public LimitedLinkedHashMap(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) { return maxSize != 0 && size() > maxSize; } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote.util; import com.google.android.apps.tvremote.protocol.ICommandSender; import com.google.anymote.Key; import com.google.anymote.Key.Code; /** * Lists common control actions on a Google TV box. * */ public enum Action { BACKSPACE { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DEL); } }, CLICK_DOWN { @Override public void execute(ICommandSender sender) { sender.key(Code.BTN_MOUSE, Key.Action.DOWN); } }, CLICK_UP { @Override public void execute(ICommandSender sender) { sender.key(Code.BTN_MOUSE, Key.Action.UP); } }, DPAD_CENTER { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DPAD_CENTER); } }, DPAD_DOWN { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DPAD_DOWN); } }, DPAD_DOWN_PRESSED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_DOWN, Key.Action.DOWN); } }, DPAD_DOWN_RELEASED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_DOWN, Key.Action.UP); } }, DPAD_LEFT { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DPAD_LEFT); } }, DPAD_LEFT_PRESSED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_LEFT, Key.Action.DOWN); } }, DPAD_LEFT_RELEASED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_LEFT, Key.Action.UP); } }, DPAD_RIGHT { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DPAD_RIGHT); } }, DPAD_RIGHT_PRESSED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_RIGHT, Key.Action.DOWN); } }, DPAD_RIGHT_RELEASED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_RIGHT, Key.Action.UP); } }, DPAD_UP { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DPAD_UP); } }, DPAD_UP_PRESSED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_UP, Key.Action.DOWN); } }, DPAD_UP_RELEASED { @Override public void execute(ICommandSender sender) { sender.key(Code.KEYCODE_DPAD_UP, Key.Action.UP); } }, ENTER { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_ENTER); } }, ESCAPE { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_ESCAPE); } }, GO_TO_DVR { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_DVR); } }, GO_TO_GUIDE { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_GUIDE); } }, GO_TO_LIVE_TV { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_LIVE); } }, NAVBAR { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_SEARCH); } }, POWER { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_POWER); } }, VOLUME_DOWN { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_VOLUME_DOWN); } }, VOLUME_UP { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_VOLUME_UP); } }, ZOOM_IN { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_ZOOM_IN); } }, ZOOM_OUT { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_ZOOM_OUT); } }, COLOR_RED { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_PROG_RED); } }, COLOR_GREEN { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_PROG_GREEN); } }, COLOR_YELLOW { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_PROG_YELLOW); } }, COLOR_BLUE { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_PROG_BLUE); } }, POWER_BD { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_BD_POWER); } }, INPUT_BD { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_BD_INPUT); } }, POWER_AVR { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_AVR_POWER); } }, INPUT_AVR { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_AVR_INPUT); } }, POWER_TV { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_TV_POWER); } }, INPUT_TV { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_TV_INPUT); } }, BD_TOP_MENU { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_BD_TOP_MENU); } }, BD_MENU { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_BD_POPUP_MENU); } }, EJECT { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_EJECT); } }, AUDIO { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_AUDIO); } }, SETTINGS { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_SETTINGS); } }, CAPTIONS { @Override public void execute(ICommandSender sender) { sender.keyPress(Code.KEYCODE_INSERT); } }; /** * Executes the action. * * @param sender interface to the remote box */ public abstract void execute(ICommandSender sender); }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.util; /** * Debug configuration flags. * */ public class Debug { private static final boolean DEBUG_CONNECTION = false; private static final boolean DEBUG_DEVICES = false; private static final boolean DEBUG_NO_CONNECTION = false; /** * @return {@code true} if connection debugging is enabled. */ public static boolean isDebugConnection() { return DEBUG_CONNECTION; } /** * @return {@code true} if recently connected (usually manually) devices list * is enabled. */ public static boolean isDebugDevices() { return DEBUG_DEVICES; } /** * @return {@code true} if testing remote without connection is enabled. */ public static boolean isDebugConnectionLess() { return DEBUG_NO_CONNECTION; } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.protocol.AnymoteSender; import com.google.android.apps.tvremote.protocol.DummySender; import com.google.android.apps.tvremote.util.Debug; import com.google.android.apps.tvremote.util.LimitedLinkedHashMap; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** * The central point to connect to a remote box and send commands. * */ public final class CoreService extends Service implements ConnectionManager { private static final String LOG_TAG = "TvRemoteCoreService"; /** * Connection status enumeration. */ public enum ConnectionStatus { /** * Connection successful. */ OK, /** * Error while creating socket or establishing connection. */ ERROR_CREATE, /** * Error during SSL handshake. */ ERROR_HANDSHAKE } private ConnectionListener connectionListener; private Socket sendSocket; private RemoteDevice target; private LimitedLinkedHashMap<InetAddress, RemoteDevice> recentlyConnected; /** * Key store manager. */ private KeyStoreManager keyStoreManager; private Handler handler; private ConnectionTask connectionTask; private static final Map<State, Set<State>> ALLOWED_TRANSITION = allowedTransitions(); private enum State { IDLE, CONNECTING, CONNECTED, DISCONNECTING, DEVICE_FINDER, PAIRING } /** * Various tags used to store the service's configuration. */ private static final String SHARED_PREF_NAME = "CoreServicePrefs"; private static final String DEVICE_NAME_TAG = "DeviceName"; private static final String DEVICE_IP_TAG = "DeviceIp"; private static final String DEVICE_PORT_TAG = "DevicePort"; /** * Notable values for ports, ip addresses and target names. */ private static final int MIN_PORT = 0; private static final int MAX_PORT = 0xFFFF; private static final int INVALID_PORT = -1; private static final String INVALID_IP = "no#ip"; private static final String INVALID_TARGET = "no#target"; /** * Timeout when creating a socket. */ private static int SOCKET_CREATION_TIMEOUT_MS = 300; /** * Timeout when reconnecting. */ private static final int RECONNECTION_DELAY_MS = 1000; private static final int MAX_CONNECTION_ATTEMPTS = 3; /** * Sender that uses the Anymote protocol. */ private AnymoteSender anymoteSender; public CoreService() { target = null; sendSocket = null; } @Override public void onCreate() { super.onCreate(); handler = new Handler(new ConnectionRequestCallback()); recentlyConnected = new LimitedLinkedHashMap<InetAddress, RemoteDevice>( getResources().getInteger(R.integer.recently_connected_count)); keyStoreManager = new KeyStoreManager(this); loadConfig(); } @Override public void onDestroy() { storeConfig(); cleanupSocket(); if (keyStoreManager != null) { keyStoreManager.store(); } super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return new LocalBinder(); } /** * Determines whether a port number is valid. * * @param port an integer representing the port number * @return {@code true} if the number falls within the range of valid ports */ private static boolean isPortValid(int port) { return port > MIN_PORT && port < MAX_PORT; } /** * Validates a connection configuration. * * @param name a string representing the name of the target * @param ip a string representing the ip of the target * @param port an integer representing the target's remote port * @return {@code true} if the configuration is valid */ private static boolean isConfigValid(String name, String ip, int port) { return !INVALID_TARGET.equals(name) && !INVALID_IP.equals(ip) && isPortValid(port); } private void cleanupSocket() { if (sendSocket == null) { return; } Log.i(LOG_TAG, "Closing connection to " + sendSocket.getInetAddress() + ":" + sendSocket.getPort()); if (anymoteSender != null) { anymoteSender.disconnect(); anymoteSender = null; } try { sendSocket.close(); } catch (IOException e) { Log.e(LOG_TAG, "failed to close socket"); } sendSocket = null; } /** * Stores the service's configuration to saved preferences. * * @return {@code true} if the config was saved */ private boolean storeConfig() { SharedPreferences pref = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); SharedPreferences.Editor prefEdit = pref.edit(); prefEdit.clear(); if (target != null) { storeRemoteDevice(prefEdit, "", target); } int index = 0; for (RemoteDevice remoteDevice : recentlyConnected.values()) { storeRemoteDevice(prefEdit, "_" + index, remoteDevice); ++index; } if (target != null || index > 0) { prefEdit.commit(); return true; } return false; } private void storeRemoteDevice(SharedPreferences.Editor prefEdit, String suffix, RemoteDevice remoteDevice) { prefEdit.putString(DEVICE_NAME_TAG + suffix, remoteDevice.getName()); prefEdit.putString(DEVICE_IP_TAG + suffix, remoteDevice.getAddress().getHostAddress()); prefEdit.putInt(DEVICE_PORT_TAG + suffix, remoteDevice.getPort()); } /** * Loads an existing configuration, and builds the socket to the target. */ private void loadConfig() { SharedPreferences pref = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); RemoteDevice restoredTarget = loadRemoteDevice(pref, ""); for (int i = 0; i < getResources() .getInteger(R.integer.recently_connected_count); ++i) { RemoteDevice remoteDevice = loadRemoteDevice(pref, "_" + i); if (remoteDevice != null) { recentlyConnected.put(remoteDevice.getAddress(), remoteDevice); } } if (restoredTarget != null) { setTarget(restoredTarget); } } private RemoteDevice loadRemoteDevice(SharedPreferences pref, String suffix) { String name = pref.getString(DEVICE_NAME_TAG + suffix, INVALID_TARGET); String ip = pref.getString(DEVICE_IP_TAG + suffix, INVALID_IP); int port = pref.getInt(DEVICE_PORT_TAG + suffix, INVALID_PORT); if (!isConfigValid(name, ip, port)) { return null; } InetAddress address; try { address = InetAddress.getByName(ip); } catch (UnknownHostException e) { return null; } return new RemoteDevice(name, address, port); } /** * Enables in-process access to this service. */ final class LocalBinder extends Binder { CoreService getService() { return CoreService.this; } } public KeyStoreManager getKeyStoreManager() { return keyStoreManager; } private void addRecentlyConnected(RemoteDevice remoteDevice) { recentlyConnected.remove(remoteDevice.getAddress()); recentlyConnected.put(remoteDevice.getAddress(), remoteDevice); storeConfig(); } // CONNECTION MANAGER private enum Request { CONNECT, CONNECTED, SET_TARGET, DISCONNECT, CONNECTION_ERROR, SET_KEEP_CONNECTED, REQUEST_PAIRING, PAIRING_FINISHED, REQUEST_DEVICE_FINDER, DEVICE_FINDER_FINISHED, } public void notifyConnectionFailed() { sendMessage(Request.CONNECTION_ERROR, null); } public void connect(ConnectionListener listener) { sendMessage(Request.CONNECT, listener); } public void connected(ConnectionResult result) { sendMessage(Request.CONNECTED, result); } public void disconnect(ConnectionListener listener) { sendMessage(Request.DISCONNECT, listener); } public void setKeepConnected(boolean keepConnected) { sendMessage(Request.SET_KEEP_CONNECTED, Boolean.valueOf(keepConnected)); } public void setTarget(RemoteDevice remoteDevice) { sendMessage(Request.SET_TARGET, remoteDevice); } public RemoteDevice getTarget() { return target; } public ArrayList<RemoteDevice> getRecentlyConnected() { ArrayList<RemoteDevice> devices = new ArrayList<RemoteDevice>( recentlyConnected.values()); Collections.reverse(devices); return devices; } public void pairingFinished() { sendMessage(Request.PAIRING_FINISHED, null); } public void deviceFinderFinished() { sendMessage(Request.DEVICE_FINDER_FINISHED, null); } public void requestDeviceFinder() { sendMessage(Request.REQUEST_DEVICE_FINDER, null); } private void requestPairing() { sendMessage(Request.REQUEST_PAIRING, null); } private void sendMessage(Request request, Object obj) { Message msg = handler.obtainMessage(request.ordinal()); msg.obj = obj; handler.dispatchMessage(msg); } private class ConnectionRequestCallback implements Handler.Callback { private int keepConnectedRefcount; private State currentState = State.IDLE; private boolean pendingNotification; private boolean changeState(State newState) { return changeState(newState, null); } private boolean changeState(State newState, Runnable callback) { if (isTransitionLegal(currentState, newState)) { if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "Changing state: " + currentState + " -> " + newState); } currentState = newState; if (callback != null) { callback.run(); } sendNotification(); return true; } if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "Illegal transition: " + currentState + " -> " + newState); } return false; } public boolean handleMessage(Message msg) { Request request = Request.values()[msg.what]; Log.v(LOG_TAG, "handleMessage:" + request + " (" + msg.obj + ")"); switch (request) { case CONNECT: handleConnect((ConnectionListener) msg.obj); return true; case CONNECTED: connectionTask = null; handleConnected((ConnectionResult) msg.obj); return true; case DISCONNECT: handleDisconnect((ConnectionListener) msg.obj); return true; case SET_TARGET: handleSetTarget((RemoteDevice) msg.obj); return true; case CONNECTION_ERROR: handleConnectionError(); return true; case SET_KEEP_CONNECTED: handleSetKeepConnected((Boolean) msg.obj); return true; case REQUEST_DEVICE_FINDER: handleRequestDeviceFinder(); return true; case REQUEST_PAIRING: handleRequestPairing(); return true; case PAIRING_FINISHED: changeState(State.IDLE); return true; case DEVICE_FINDER_FINISHED: changeState(State.IDLE); return true; } return false; } private boolean isConnected() { return Debug.isDebugConnectionLess() || sendSocket != null; } private boolean isConnecting() { return State.CONNECTING.equals(currentState); } private void handleConnectionError() { if (changeState(State.DISCONNECTING)) { cleanupSocket(); } if (changeState(State.CONNECTING)) { connect(); } } private void handleConnect(ConnectionListener listener) { handleSetKeepConnected(true); if (listener != connectionListener) { connectionListener = listener; if (pendingNotification) { sendNotification(); } else if (isConnecting() || isConnected()) { sendNotification(); } } if (target != null && changeState(State.CONNECTING)) { connect(); } else if (target == null) { changeState(State.DEVICE_FINDER); } } private void handleRequestDeviceFinder() { stopConnectionTask(); disconnect(true); changeState(State.DEVICE_FINDER); } private void handleRequestPairing() { stopConnectionTask(); changeState(State.PAIRING); } private void handleConnected(final ConnectionResult result) { stopConnectionTask(); if (sendSocket != null) { throw new IllegalStateException(); } changeState(State.CONNECTED, new Runnable() { public void run() { addRecentlyConnected(target); anymoteSender = result.sender; sendSocket = result.socket; } }); } private void handleDisconnect(ConnectionListener listener) { handleSetKeepConnected(false); if (listener == connectionListener) { connectionListener = null; } } private void handleSetKeepConnected(boolean keepConnected) { keepConnectedRefcount += keepConnected ? 1 : -1; if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "KeepConnectedRefcount: " + keepConnectedRefcount); } if (keepConnectedRefcount < 0) { throw new IllegalStateException("KeepConnectedRefCount < 0"); } if (connectionListener == null) { disconnect(false); } } private void handleSetTarget(RemoteDevice remoteDevice) { disconnect(true); target = remoteDevice; if (target != null && changeState(State.CONNECTING)) { connect(); } } private void disconnect(boolean unconditionally) { if (unconditionally || keepConnectedRefcount == 0) { if (isConnected()) { changeState(State.DISCONNECTING); cleanupSocket(); changeState(State.IDLE); } else if (isConnecting()) { changeState(State.DISCONNECTING); stopConnectionTask(); changeState(State.IDLE); } } } private void connect() { if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "Connecting to: " + target); } if (sendSocket != null) { throw new IllegalStateException("Already connected"); } if (target == null) { changeState(State.DEVICE_FINDER); return; } startConnectionTask(target); } private void sendNotification() { if (connectionListener == null) { pendingNotification = true; if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "Pending notification: " + currentState); } return; } pendingNotification = false; if (Debug.isDebugConnection()) { Log.d(LOG_TAG, "Sending notification: " + currentState + " to " + connectionListener); } switch (currentState) { case IDLE: break; case CONNECTING: connectionListener.onConnecting(); break; case CONNECTED: connectionListener.onConnectionSuccessful( Debug.isDebugConnectionLess() ? new DummySender() : anymoteSender); break; case DISCONNECTING: connectionListener.onDisconnected(); break; case DEVICE_FINDER: connectionListener.onShowDeviceFinder(); break; case PAIRING: if (target != null) { connectionListener.onNeedsPairing(target); } else { connectionListener.onShowDeviceFinder(); } break; default: throw new IllegalStateException("Unsupported state: " + currentState); } } } private void startConnectionTask(RemoteDevice remoteDevice) { stopConnectionTask(); connectionTask = new ConnectionTask(this); connectionTask.execute(remoteDevice); } private void stopConnectionTask() { if (connectionTask != null) { connectionTask.cancel(true); connectionTask = null; } } private static class ConnectionResult { final ConnectionStatus status; final AnymoteSender sender; final Socket socket; private ConnectionResult(ConnectionStatus status, AnymoteSender sender, Socket socket) { this.status = status; this.sender = sender; this.socket = socket; } } private static class ConnectionTask extends AsyncTask<RemoteDevice, Void, ConnectionResult> { private final CoreService coreService; private AnymoteSender sender; private Socket socket; private ConnectionTask(CoreService coreService) { this.coreService = coreService; } @Override protected ConnectionResult doInBackground(RemoteDevice... params) { if (params.length != 1) { throw new IllegalStateException("Expected exactly one remote device"); } for (int i = 0; i <= MAX_CONNECTION_ATTEMPTS; ++i) { try { Thread.sleep(RECONNECTION_DELAY_MS * i); } catch (InterruptedException e) { return null; } sender = null; socket = null; if (isCancelled()) { return null; } ConnectionStatus status = buildSocket(params[0]); if (isCancelled()) { return null; } switch (status) { case OK: return new ConnectionResult(status, sender, socket); case ERROR_HANDSHAKE: return new ConnectionResult(status, null, null); case ERROR_CREATE: // try to reconnect break; default: throw new IllegalStateException("Unsupported status: " + status); } } return new ConnectionResult(ConnectionStatus.ERROR_CREATE, null, null); } private ConnectionStatus buildSocket(RemoteDevice target) { if (target == null) { throw new IllegalStateException(); } // Set up the new connection. try { socket = getSslSocket(target); } catch (SSLException e) { Log.e(LOG_TAG, "(SSL) Could not create socket to " + target, e); return ConnectionStatus.ERROR_HANDSHAKE; } catch (GeneralSecurityException e) { Log.e(LOG_TAG, "(GSE) Could not create socket to " + target, e); return ConnectionStatus.ERROR_HANDSHAKE; } catch (IOException e) { // Hack for Froyo which throws IOException for SSL handshake problem: if (e.getMessage().startsWith("SSL handshake")) { return ConnectionStatus.ERROR_HANDSHAKE; } Log.e(LOG_TAG, "(IOE) Could not create socket to " + target, e); return ConnectionStatus.ERROR_CREATE; } Log.i(LOG_TAG, "Connected to " + target); if (isCancelled()) { return ConnectionStatus.ERROR_CREATE; } sender = new AnymoteSender(coreService); if (!sender.setSocket(socket)) { Log.e(LOG_TAG, "Initial message failed"); sender.disconnect(); try { socket.close(); } catch (IOException e) { Log.e(LOG_TAG, "failed to close socket"); } return ConnectionStatus.ERROR_CREATE; } // Connection successful - we need to reset connection attempts counter, // so next time the connection will drop we will try reconnecting. return ConnectionStatus.OK; } /** * Generates an SSL-enabled socket. * * @return the new socket * @throws GeneralSecurityException on error building the socket * @throws IOException on error loading the KeyStore */ private SSLSocket getSslSocket(RemoteDevice target) throws GeneralSecurityException, IOException { // Build a new key store based on the key store manager. KeyManager[] keyManagers = coreService.getKeyStoreManager() .getKeyManagers(); TrustManager[] trustManagers = coreService.getKeyStoreManager() .getTrustManagers(); if (keyManagers.length == 0) { throw new IllegalStateException("No key managers"); } // Create a new SSLContext, using the new KeyManagers and TrustManagers // as the sources of keys and trust decisions, respectively. SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); // Finally, build a new SSLSocketFactory from the SSLContext, and // then generate a new SSLSocket from it. SSLSocketFactory factory = sslContext.getSocketFactory(); SSLSocket sock = (SSLSocket) factory.createSocket(); sock.setNeedClientAuth(true); sock.setUseClientMode(true); sock.setKeepAlive(true); sock.setTcpNoDelay(true); InetSocketAddress fullAddr = new InetSocketAddress(target.getAddress(), target.getPort()); sock.connect(fullAddr, SOCKET_CREATION_TIMEOUT_MS); sock.startHandshake(); return sock; } // Notifications @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(ConnectionResult result) { super.onPostExecute(result); switch (result.status) { case OK: coreService.connected(result); break; case ERROR_CREATE: coreService.requestDeviceFinder(); break; case ERROR_HANDSHAKE: coreService.requestPairing(); break; } } } // State transition management private static Map<State, Set<State>> allowedTransitions() { Map<State, Set<State>> allowedTransitions = new HashMap<State, Set<State>>(); allowedTransitions.put(State.IDLE, EnumSet.of(State.IDLE, State.CONNECTING, State.DEVICE_FINDER)); allowedTransitions.put(State.CONNECTING, EnumSet.of(State.CONNECTED, State.DEVICE_FINDER, State.PAIRING, State.DISCONNECTING)); allowedTransitions.put(State.CONNECTED, EnumSet.of(State.DISCONNECTING)); allowedTransitions.put(State.DEVICE_FINDER, EnumSet.of(State.IDLE)); allowedTransitions.put(State.PAIRING, EnumSet.of(State.IDLE)); allowedTransitions.put(State.DISCONNECTING, EnumSet.of(State.IDLE, State.CONNECTING)); for (State state : State.values()) { if (!allowedTransitions.containsKey(state)) { throw new IllegalStateException("Incomplete transition map"); } } return allowedTransitions; } private static boolean isTransitionLegal(State from, State to) { return ALLOWED_TRANSITION.get(from).contains(to); } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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. */ // BACKPORTED FROM ANDROID PUBLIC REPOSITORY package com.google.android.apps.tvremote.backport; import android.view.MotionEvent; /** * Detects transformation gestures involving more than one pointer * ("multitouch") using the supplied {@link MotionEvent}s. The * {@link OnScaleGestureListener} callback will notify users when a particular * gesture event has occurred. This class should only be used with * {@link MotionEvent}s reported via touch. * * To use this class: * <ul> * <li>Create an instance of the {@code ScaleGestureDetector} for your * {@link View} * <li>In the {@link View#onTouchEvent(MotionEvent)} method ensure you call * {@link #onTouchEvent(MotionEvent)}. The methods defined in your callback will * be executed when the events occur. * </ul> * */ public interface ScaleGestureDetector { /** * The listener for receiving notifications when gestures occur. If you want * to listen for all the different gestures then implement this interface. If * you only want to listen for a subset it might be easier to extend * {@link SimpleOnScaleGestureListener}. * * An application will receive events in the following order: * <ul> * <li>One {@link OnScaleGestureListener#onScaleBegin(ScaleGestureDetector)} * <li>Zero or more * {@link OnScaleGestureListener#onScale(ScaleGestureDetector)} * <li>One {@link OnScaleGestureListener#onScaleEnd(ScaleGestureDetector)} * </ul> */ public interface OnScaleGestureListener { /** * Responds to scaling events for a gesture in progress. Reported by pointer * motion. * * @param detector The detector reporting the event - use this to retrieve * extended info about event state. * @return Whether or not the detector should consider this event as * handled. If an event was not handled, the detector will continue * to accumulate movement until an event is handled. This can be * useful if an application, for example, only wants to update * scaling factors if the change is greater than 0.01. */ public boolean onScale(ScaleGestureDetector detector); /** * Responds to the beginning of a scaling gesture. Reported by new pointers * going down. * * @param detector The detector reporting the event - use this to retrieve * extended info about event state. * @return Whether or not the detector should continue recognizing this * gesture. For example, if a gesture is beginning with a focal * point outside of a region where it makes sense, onScaleBegin() * may return false to ignore the rest of the gesture. */ public boolean onScaleBegin(ScaleGestureDetector detector); /** * Responds to the end of a scale gesture. Reported by existing pointers * going up. * * Once a scale has ended, {@link ScaleGestureDetector#getFocusX()} and * {@link ScaleGestureDetector#getFocusY()} will return the location of the * pointer remaining on the screen. * * @param detector The detector reporting the event - use this to retrieve * extended info about event state. */ public void onScaleEnd(ScaleGestureDetector detector); } /** * A convenience class to extend when you only want to listen for a subset of * scaling-related events. This implements all methods in * {@link OnScaleGestureListener} but does nothing. * {@link OnScaleGestureListener#onScale(ScaleGestureDetector)} returns {@code * false} so that a subclass can retrieve the accumulated scale factor in an * overridden onScaleEnd. * {@link OnScaleGestureListener#onScaleBegin(ScaleGestureDetector)} returns * {@code true}. */ public static class SimpleOnScaleGestureListener implements OnScaleGestureListener { public boolean onScale(ScaleGestureDetector detector) { return false; } public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } public void onScaleEnd(ScaleGestureDetector detector) { // Intentionally empty } } /** * Returns {@code true} if a two-finger scale gesture is in progress. * * @return {@code true} if a scale gesture is in progress, {@code false} * otherwise. */ public boolean isInProgress(); /** * Get the X coordinate of the current gesture's focal point. If a gesture is * in progress, the focal point is directly between the two pointers forming * the gesture. If a gesture is ending, the focal point is the location of the * remaining pointer on the screen. If {@link #isInProgress()} would return * false, the result of this function is undefined. * * @return X coordinate of the focal point in pixels. */ public float getFocusX(); /** * Get the Y coordinate of the current gesture's focal point. If a gesture is * in progress, the focal point is directly between the two pointers forming * the gesture. If a gesture is ending, the focal point is the location of the * remaining pointer on the screen. If {@link #isInProgress()} would return * false, the result of this function is undefined. * * @return Y coordinate of the focal point in pixels. */ public float getFocusY(); /** * Return the current distance between the two pointers forming the gesture in * progress. * * @return Distance between pointers in pixels. */ public float getCurrentSpan(); /** * Return the previous distance between the two pointers forming the gesture * in progress. * * @return Previous distance between pointers in pixels. */ public float getPreviousSpan(); /** * Return the scaling factor from the previous scale event to the current * event. This value is defined as ({@link #getCurrentSpan()} / * {@link #getPreviousSpan()}). * * @return The current scaling factor. */ public float getScaleFactor(); /** * Return the time difference in milliseconds between the previous accepted * scaling event and the current scaling event. * * @return Time difference since the last scaling event in milliseconds. */ public long getTimeDelta(); /** * Return the event time of the current event being processed. * * @return Current event time in milliseconds. */ public long getEventTime(); public boolean onTouchEvent(MotionEvent event); }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.backport; import android.os.Build; import android.view.View; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * Factory of {@link ScaleGestureDetector} implementation. Creates gesture * detector that depends on available APIs. For API levels that support * multitouch, creates implementation that detects two finger gestures. * */ public class ScaleGestureDetectorFactory { private static final int MIN_API_LEVEL_MULTITOUCH = 5; private ScaleGestureDetectorFactory() { // prevents instantiation throw new IllegalStateException(); } public static ScaleGestureDetector createScaleGestureDetector(View view, ScaleGestureDetector.OnScaleGestureListener listener) { ScaleGestureDetector result = null; if (Build.VERSION.SDK_INT >= MIN_API_LEVEL_MULTITOUCH) { result = createScaleGestureDetectorImpl(view, listener); } return result; } private static ScaleGestureDetector createScaleGestureDetectorImpl(View view, ScaleGestureDetector.OnScaleGestureListener listener) { try { Class<?> clazz = Class.forName( "com.google.android.apps.tvremote.backport.ScaleGestureDetectorImpl"); Constructor<?> constructor = clazz.getConstructor(View.class, ScaleGestureDetector.OnScaleGestureListener.class); return (ScaleGestureDetector) constructor.newInstance(view, listener); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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. */ // BACKPORTED FROM ANDROID PUBLIC REPOSITORY package com.google.android.apps.tvremote.backport; import android.graphics.Rect; import android.util.DisplayMetrics; import android.util.FloatMath; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; /** * Detects transformation gestures involving more than one pointer * ("multitouch") using the supplied {@link MotionEvent}s. The * {@link OnScaleGestureListener} callback will notify users when a particular * gesture event has occurred. This class should only be used with * {@link MotionEvent}s reported via touch. * * To use this class: * <ul> * <li>Create an instance of the {@code ScaleGestureDetector} for your * {@link View} * <li>In the {@link View#onTouchEvent(MotionEvent)} method ensure you call * {@link #onTouchEvent(MotionEvent)}. The methods defined in your callback will * be executed when the events occur. * </ul> * */ public class ScaleGestureDetectorImpl implements ScaleGestureDetector { /** * This value is the threshold ratio between our previous combined pressure * and the current combined pressure. We will only fire an onScale event if * the computed ratio between the current and previous event pressures is * greater than this value. When pressure decreases rapidly between events the * position values can often be imprecise, as it usually indicates that the * user is in the process of lifting a pointer off of the device. Its value * was tuned experimentally. */ private static final float PRESSURE_THRESHOLD = 0.67f; private final View mView; private final OnScaleGestureListener mListener; private boolean mGestureInProgress; private MotionEvent mPrevEvent; private MotionEvent mCurrEvent; private float mFocusX; private float mFocusY; private float mPrevFingerDiffX; private float mPrevFingerDiffY; private float mCurrFingerDiffX; private float mCurrFingerDiffY; private float mCurrLen; private float mPrevLen; private float mScaleFactor; private float mCurrPressure; private float mPrevPressure; private long mTimeDelta; private final float mEdgeSlop; private float mRightSlopEdge; private float mBottomSlopEdge; private boolean mSloppyGesture; public ScaleGestureDetectorImpl(View view, OnScaleGestureListener listener) { ViewConfiguration config = ViewConfiguration.get(view.getContext()); mView = view; mListener = listener; mEdgeSlop = config.getScaledEdgeSlop(); } public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); boolean handled = true; Rect rect = new Rect(); if (!mView.getGlobalVisibleRect(rect)) { return false; } if (!mGestureInProgress) { switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_POINTER_DOWN: { // We have a new multi-finger gesture // as orientation can change, query the metrics in touch down DisplayMetrics metrics = mView.getContext().getResources().getDisplayMetrics(); mRightSlopEdge = metrics.widthPixels - mEdgeSlop; mBottomSlopEdge = metrics.heightPixels - mEdgeSlop; // Be paranoid in case we missed an event reset(); mPrevEvent = MotionEvent.obtain(event); mTimeDelta = 0; setContext(event); // Check if we have a sloppy gesture. If so, delay // the beginning of the gesture until we're sure that's // what the user wanted. Sloppy gestures can happen if the // edge of the user's hand is touching the screen, for example. final float edgeSlop = mEdgeSlop; final float rightSlop = mRightSlopEdge; final float bottomSlop = mBottomSlopEdge; final float x0 = event.getRawX(); final float y0 = event.getRawY(); final float x1 = getRawX(event, 1, rect); final float y1 = getRawY(event, 1, rect); boolean p0sloppy = x0 < edgeSlop || y0 < edgeSlop || x0 > rightSlop || y0 > bottomSlop; boolean p1sloppy = x1 < edgeSlop || y1 < edgeSlop || x1 > rightSlop || y1 > bottomSlop; if (p0sloppy && p1sloppy) { mFocusX = -1; mFocusY = -1; mSloppyGesture = true; } else if (p0sloppy) { mFocusX = event.getX(1); mFocusY = event.getY(1); mSloppyGesture = true; } else if (p1sloppy) { mFocusX = event.getX(0); mFocusY = event.getY(0); mSloppyGesture = true; } else { mGestureInProgress = mListener.onScaleBegin(this); } } break; case MotionEvent.ACTION_MOVE: if (mSloppyGesture) { // Initiate sloppy gestures if we've moved outside of the slop area. final float edgeSlop = mEdgeSlop; final float rightSlop = mRightSlopEdge; final float bottomSlop = mBottomSlopEdge; final float x0 = event.getRawX(); final float y0 = event.getRawY(); final float x1 = getRawX(event, 1, rect); final float y1 = getRawY(event, 1, rect); boolean p0sloppy = x0 < edgeSlop || y0 < edgeSlop || x0 > rightSlop || y0 > bottomSlop; boolean p1sloppy = x1 < edgeSlop || y1 < edgeSlop || x1 > rightSlop || y1 > bottomSlop; if (p0sloppy && p1sloppy) { mFocusX = -1; mFocusY = -1; } else if (p0sloppy) { mFocusX = event.getX(1); mFocusY = event.getY(1); } else if (p1sloppy) { mFocusX = event.getX(0); mFocusY = event.getY(0); } else { mSloppyGesture = false; mGestureInProgress = mListener.onScaleBegin(this); } } break; case MotionEvent.ACTION_POINTER_UP: if (mSloppyGesture) { // Set focus point to the remaining finger int id = ( ((action & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT) == 0) ? 1 : 0; mFocusX = event.getX(id); mFocusY = event.getY(id); } break; } } else { // Transform gesture in progress - attempt to handle it switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_POINTER_UP: // Gesture ended setContext(event); // Set focus point to the remaining finger int id = (((action & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT) == 0) ? 1 : 0; mFocusX = event.getX(id); mFocusY = event.getY(id); if (!mSloppyGesture) { mListener.onScaleEnd(this); } reset(); break; case MotionEvent.ACTION_CANCEL: if (!mSloppyGesture) { mListener.onScaleEnd(this); } reset(); break; case MotionEvent.ACTION_MOVE: setContext(event); // Only accept the event if our relative pressure is within // a certain limit - this can help filter shaky data as a // finger is lifted. if (mCurrPressure / mPrevPressure > PRESSURE_THRESHOLD) { final boolean updatePrevious = mListener.onScale(this); if (updatePrevious) { mPrevEvent.recycle(); mPrevEvent = MotionEvent.obtain(event); } } break; } } return handled; } /** * MotionEvent has no getRawX(int) method; simulate it pending future API * approval. */ private static float getRawX( MotionEvent event, int pointerIndex, Rect viewRect) { return event.getX(pointerIndex) + viewRect.left; } /** * MotionEvent has no getRawY(int) method; simulate it pending future API * approval. */ private static float getRawY( MotionEvent event, int pointerIndex, Rect viewRect) { return event.getY(pointerIndex) + viewRect.top; } private void setContext(MotionEvent curr) { if (mCurrEvent != null) { mCurrEvent.recycle(); } mCurrEvent = MotionEvent.obtain(curr); mCurrLen = -1; mPrevLen = -1; mScaleFactor = -1; final MotionEvent prev = mPrevEvent; final float px0 = prev.getX(0); final float py0 = prev.getY(0); final float px1 = prev.getX(1); final float py1 = prev.getY(1); final float cx0 = curr.getX(0); final float cy0 = curr.getY(0); final float cx1 = curr.getX(1); final float cy1 = curr.getY(1); final float pvx = px1 - px0; final float pvy = py1 - py0; final float cvx = cx1 - cx0; final float cvy = cy1 - cy0; mPrevFingerDiffX = pvx; mPrevFingerDiffY = pvy; mCurrFingerDiffX = cvx; mCurrFingerDiffY = cvy; mFocusX = cx0 + cvx * 0.5f; mFocusY = cy0 + cvy * 0.5f; mTimeDelta = curr.getEventTime() - prev.getEventTime(); mCurrPressure = curr.getPressure(0) + curr.getPressure(1); mPrevPressure = prev.getPressure(0) + prev.getPressure(1); } private void reset() { if (mPrevEvent != null) { mPrevEvent.recycle(); mPrevEvent = null; } if (mCurrEvent != null) { mCurrEvent.recycle(); mCurrEvent = null; } mSloppyGesture = false; mGestureInProgress = false; } /** * Returns {@code true} if a two-finger scale gesture is in progress. * * @return {@code true} if a scale gesture is in progress, {@code false} * otherwise. */ public boolean isInProgress() { return mGestureInProgress; } /** * Get the X coordinate of the current gesture's focal point. If a gesture is * in progress, the focal point is directly between the two pointers forming * the gesture. If a gesture is ending, the focal point is the location of the * remaining pointer on the screen. If {@link #isInProgress()} would return * false, the result of this function is undefined. * * @return X coordinate of the focal point in pixels. */ public float getFocusX() { return mFocusX; } /** * Get the Y coordinate of the current gesture's focal point. If a gesture is * in progress, the focal point is directly between the two pointers forming * the gesture. If a gesture is ending, the focal point is the location of the * remaining pointer on the screen. If {@link #isInProgress()} would return * false, the result of this function is undefined. * * @return Y coordinate of the focal point in pixels. */ public float getFocusY() { return mFocusY; } /** * Return the current distance between the two pointers forming the gesture in * progress. * * @return Distance between pointers in pixels. */ public float getCurrentSpan() { if (mCurrLen == -1) { final float cvx = mCurrFingerDiffX; final float cvy = mCurrFingerDiffY; mCurrLen = FloatMath.sqrt(cvx * cvx + cvy * cvy); } return mCurrLen; } /** * Return the previous distance between the two pointers forming the gesture * in progress. * * @return Previous distance between pointers in pixels. */ public float getPreviousSpan() { if (mPrevLen == -1) { final float pvx = mPrevFingerDiffX; final float pvy = mPrevFingerDiffY; mPrevLen = FloatMath.sqrt(pvx * pvx + pvy * pvy); } return mPrevLen; } /** * Return the scaling factor from the previous scale event to the current * event. This value is defined as ({@link #getCurrentSpan()} / * {@link #getPreviousSpan()}). * * @return The current scaling factor. */ public float getScaleFactor() { if (mScaleFactor == -1) { mScaleFactor = getCurrentSpan() / getPreviousSpan(); } return mScaleFactor; } /** * Return the time difference in milliseconds between the previous accepted * scaling event and the current scaling event. * * @return Time difference since the last scaling event in milliseconds. */ public long getTimeDelta() { return mTimeDelta; } /** * Return the event time of the current event being processed. * * @return Current event time in milliseconds. */ public long getEventTime() { return mCurrEvent.getEventTime(); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.util.Action; /** * Storage class representing a shortcut. * */ public class Shortcut { /** * Resource id of the name. */ private final int titleId; /** * Resource id of the detail string {@code null} if none. */ private final Integer detailId; /** * Attached action. */ private final Action action; /** * Color of the first component. */ private final Integer colorId; private Shortcut(Action action, int title, Integer detail, Integer colorId) { if (action == null) { throw new NullPointerException(); } this.titleId = title; this.action = action; this.detailId = detail; this.colorId = colorId; } public Shortcut(int title, int detail, int colorId, Action action) { this(action, title, detail, colorId); } public Shortcut(int title, int detail, Action action) { this(action, title, detail, null); } public Shortcut(int title, Action action) { this(action, title, null, null); } public int getTitleId() { return titleId; } public int getDetailId() { return detailId; } public boolean hasDetailId() { return detailId != null; } public Action getAction() { return action; } public boolean hasColor() { return colorId != null; } public int getColor() { return colorId; } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.content.Intent; import android.os.AsyncTask; import android.provider.Settings; import android.view.View; import android.widget.Button; /** * Startup activity that checks if certificates are generated, and if not * begins async generation of certificates, and displays remote logo. * */ public class StartupActivity extends CoreServiceActivity { private boolean keystoreAvailable; private Button connectButton; @Override protected void onServiceAvailable(CoreService coreService) { // Show UI. if (!getKeyStoreManager().hasServerIdentityAlias()) { setContentView(R.layout.tutorial); connectButton = (Button) findViewById(R.id.tutorial_button); connectButton.setEnabled(false); connectButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showMainActivity(); } }); new KeystoreInitializerTask(getUniqueId()).execute(getKeyStoreManager()); } else { keystoreAvailable = true; showMainActivity(); } } @Override protected void onNewIntent(Intent intent) { setIntent(intent); if (keystoreAvailable) { showMainActivity(); } } @Override protected void onServiceDisconnecting(CoreService coreService) { // Do nothing } private void showMainActivity() { Intent intent = new Intent(this, MainActivity.class); Intent originalIntent = getIntent(); if (originalIntent != null) { intent.setAction(originalIntent.getAction()); intent.putExtras(originalIntent); } startActivity(intent); } private class KeystoreInitializerTask extends AsyncTask< KeyStoreManager, Void, Void> { private final String id; public KeystoreInitializerTask(String id) { this.id = id; } @Override protected Void doInBackground(KeyStoreManager... keyStoreManagers) { if (keyStoreManagers.length != 1) { throw new IllegalStateException("Only one key store manager expected"); } keyStoreManagers[0].initializeKeyStore(id); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); keystoreAvailable = true; connectButton.setEnabled(true); } } private String getUniqueId() { String id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); // null ANDROID_ID is possible on emulator return id != null ? id : "emulator"; } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.ConnectionManager.ConnectionListener; import com.google.android.apps.tvremote.TrackballHandler.Direction; import com.google.android.apps.tvremote.TrackballHandler.Listener; import com.google.android.apps.tvremote.TrackballHandler.Mode; import com.google.android.apps.tvremote.protocol.ICommandSender; import com.google.android.apps.tvremote.protocol.QueuingSender; import com.google.android.apps.tvremote.util.Action; import com.google.android.apps.tvremote.util.Debug; import com.google.android.apps.tvremote.widget.SoftDpad; import com.google.android.apps.tvremote.widget.SoftDpad.DpadListener; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.WindowManager; import android.widget.Toast; import java.util.concurrent.TimeUnit; /** * Base for most activities in the app. * <p> * Automatically connects to the background service on startup. * */ public class BaseActivity extends CoreServiceActivity implements ConnectionListener { private static final String LOG_TAG = "BaseActivity"; /** * Request code used by this activity. */ private static final int CODE_SWITCH_BOX = 1; /** * Request code used by this activity for pairing requests. */ private static final int CODE_PAIRING = 2; private static final long MIN_TOAST_PERIOD = TimeUnit.SECONDS.toMillis(3); /** * User codes defined in activities extending this one should start above * this value. */ public static final int FIRST_USER_CODE = 100; /** * Code for delayed messages to dim the screen. */ private static final int SCREEN_DIM = 1; /** * Backported brightness level from API level 8 */ private static final float BRIGHTNESS_OVERRIDE_NONE = -1.0f; /** * Turns trackball events into commands. */ private TrackballHandler trackballHandler; private final QueuingSender commands; private boolean isConnected; private boolean isKeepingConnection; private boolean isScreenDimmed; private Handler handler; /** * Constructor. */ BaseActivity() { commands = new QueuingSender(new MissingSenderToaster()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); handler = new Handler(new ScreenDimCallback()); trackballHandler = createTrackballHandler(); trackballHandler.setAudioManager(am); } @Override protected void onStart() { super.onStart(); setKeepConnected(true); } @Override protected void onStop() { setKeepConnected(false); super.onStop(); } @Override protected void onResume() { super.onResume(); connect(); resetScreenDim(); } @Override protected void onPause() { handler.removeMessages(SCREEN_DIM); disconnect(); super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { int code = event.getKeyCode(); switch (code) { case KeyEvent.KEYCODE_VOLUME_DOWN: Action.VOLUME_DOWN.execute(getCommands()); return true; case KeyEvent.KEYCODE_VOLUME_UP: Action.VOLUME_UP.execute(getCommands()); return true; case KeyEvent.KEYCODE_SEARCH: Action.NAVBAR.execute(getCommands()); showActivity(KeyboardActivity.class); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTrackballEvent(MotionEvent event) { return trackballHandler.onTrackballEvent(event); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = new MenuInflater(this); inflater.inflate(R.menu.main, menu); return true; } // MENU HANDLER @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_switch: getConnectionManager().requestDeviceFinder(); return true; case R.id.menu_about: showActivity(AboutActivity.class); return true; default: return super.onOptionsItemSelected(item); } } /** * Returns an object handling trackball events. */ private TrackballHandler createTrackballHandler() { TrackballHandler handler = new TrackballHandler(new Listener() { public void onClick() { Action.DPAD_CENTER.execute(getCommands()); } public void onDirectionalEvent(Direction direction) { switch (direction) { case DOWN: Action.DPAD_DOWN.execute(getCommands()); break; case LEFT: Action.DPAD_LEFT.execute(getCommands()); break; case RIGHT: Action.DPAD_RIGHT.execute(getCommands()); break; case UP: Action.DPAD_UP.execute(getCommands()); break; default: break; } } public void onScrollEvent(int dx, int dy) { getCommands().scroll(dx, dy); } }, this); handler.setEnabled(true); handler.setMode(Mode.DPAD); return handler; } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { executeWhenCoreServiceAvailable(new Runnable() { public void run() { if (requestCode == CODE_SWITCH_BOX) { if (resultCode == RESULT_OK && data != null) { RemoteDevice remoteDevice = data.getParcelableExtra(DeviceFinder.EXTRA_REMOTE_DEVICE); if (remoteDevice != null) { getConnectionManager().setTarget(remoteDevice); } } getConnectionManager().deviceFinderFinished(); connectOrFinish(); } else if (requestCode == CODE_PAIRING) { getConnectionManager().pairingFinished(); handlePairingResult(resultCode); } } }); } private void showMessage(int resId) { Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show(); } private void handlePairingResult(int resultCode) { switch (resultCode) { case PairingActivity.RESULT_OK: showMessage(R.string.pairing_succeeded_toast); connect(); break; case PairingActivity.RESULT_CANCELED: getConnectionManager().requestDeviceFinder(); break; case PairingActivity.RESULT_CONNECTION_FAILED: case PairingActivity.RESULT_PAIRING_FAILED: showMessage(R.string.pairing_failed_toast); getConnectionManager().requestDeviceFinder(); break; default: throw new IllegalStateException("Unsupported pairing activity result: " + resultCode); } } /** * Returns the interface to send commands to the remote box. */ protected final ICommandSender getCommands() { return commands; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { onKeyboardOpened(); } if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) { onKeyboardClosed(); } } /** * Called when the physical keyboard is opened. * <p> * The default behavior is to close the current activity and to start the * keyboard activity. Extending classes can override to change behavior. */ protected void onKeyboardOpened() { showActivity(KeyboardActivity.class); finish(); } /** * Called when the physical keyboard is closed. * <p> * Extending classes can override to change behavior. */ protected void onKeyboardClosed() { // default behavior is to do nothing } /** * Returns {@code true} if the activity is in landscape mode. */ protected boolean isLandscape() { return (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); } /** * Returns a default implementation for the DpadListener. */ protected DpadListener getDefaultDpadListener() { return new DpadListener() { public void onDpadClicked() { if(getCommands() != null) { Action.DPAD_CENTER.execute(getCommands()); } } public void onDpadMoved(SoftDpad.Direction direction, boolean pressed) { Action action = translateDirection(direction, pressed); if (action != null) { action.execute(getCommands()); } } }; } /** * Translates a direction and a key pressed in an action. * * @param direction the direction of the movement * @param pressed {@code true} if the key was pressed */ private static Action translateDirection(SoftDpad.Direction direction, boolean pressed) { switch (direction) { case DOWN: return pressed ? Action.DPAD_DOWN_PRESSED : Action.DPAD_DOWN_RELEASED; case LEFT: return pressed ? Action.DPAD_LEFT_PRESSED : Action.DPAD_LEFT_RELEASED; case RIGHT: return pressed ? Action.DPAD_RIGHT_PRESSED : Action.DPAD_RIGHT_RELEASED; case UP: return pressed ? Action.DPAD_UP_PRESSED : Action.DPAD_UP_RELEASED; default: return null; } } private void connect() { if (!isConnected) { isConnected = true; executeWhenCoreServiceAvailable(new Runnable() { public void run() { getConnectionManager().connect(BaseActivity.this); } }); } } private void disconnect() { if (isConnected) { commands.setSender(null); isConnected = false; executeWhenCoreServiceAvailable(new Runnable() { public void run() { getConnectionManager().disconnect(BaseActivity.this); } }); } } private void setKeepConnected(final boolean keepConnected) { if (isKeepingConnection != keepConnected) { isKeepingConnection = keepConnected; executeWhenCoreServiceAvailable(new Runnable() { public void run() { logConnectionStatus("Keep Connected: " + keepConnected); getConnectionManager().setKeepConnected(keepConnected); } }); } } /** * Starts the box selection dialog. */ private final void showSwitchBoxActivity() { disconnect(); startActivityForResult( DeviceFinder.createConnectIntent(this, getConnectionManager().getTarget(), getConnectionManager().getRecentlyConnected()), CODE_SWITCH_BOX); } /** * If connection failed due to SSL handshake failure, this method will be * invoked to start the pairing session with device, and establish secure * connection. * <p> * When pairing finishes, PairingListener's method will be called to * differentiate the result. */ private final void showPairingActivity(RemoteDevice target) { disconnect(); if (target != null) { startActivityForResult( PairingActivity.createIntent(this, new RemoteDevice( target.getName(), target.getAddress(), target.getPort() + 1)), CODE_PAIRING); } } public void onConnecting() { commands.setSender(null); logConnectionStatus("Connecting"); } public void onShowDeviceFinder() { commands.setSender(null); logConnectionStatus("Show device finder"); showSwitchBoxActivity(); } public void onConnectionSuccessful(ICommandSender sender) { logConnectionStatus("Connected"); commands.setSender(sender); } public void onNeedsPairing(RemoteDevice remoteDevice) { logConnectionStatus("Pairing"); showPairingActivity(remoteDevice); } public void onDisconnected() { commands.setSender(null); logConnectionStatus("Disconnected"); } private class MissingSenderToaster implements QueuingSender.MissingSenderListener { private long lastToastTime; public void onMissingSender() { if (System.currentTimeMillis() - lastToastTime > MIN_TOAST_PERIOD) { lastToastTime = System.currentTimeMillis(); showMessage(R.string.sender_missing); } } } private void logConnectionStatus(CharSequence sequence) { String message = String.format("%s (%s)", sequence, getClass().getSimpleName()); if (Debug.isDebugConnection()) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } Log.d(LOG_TAG, "Connection state: " + sequence); } private void connectOrFinish() { if (getConnectionManager() != null) { if (getConnectionManager().getTarget() != null) { connect(); } else { finish(); } } } @Override protected void onServiceAvailable(CoreService coreService) { } @Override protected void onServiceDisconnecting(CoreService coreService) { disconnect(); setKeepConnected(false); } // Screen dimming @Override public void onUserInteraction() { super.onUserInteraction(); resetScreenDim(); } private void screenDim() { if (!isScreenDimmed) { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = getResources().getInteger( R.integer.screen_brightness_dimmed) / 100.0f; getWindow().setAttributes(lp); } isScreenDimmed = true; } private void resetScreenDim() { if (isScreenDimmed) { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = BRIGHTNESS_OVERRIDE_NONE; getWindow().setAttributes(lp); } isScreenDimmed = false; handler.removeMessages(SCREEN_DIM); handler.sendEmptyMessageDelayed(SCREEN_DIM, TimeUnit.SECONDS.toMillis(getResources().getInteger( R.integer.timeout_screen_dim))); } private class ScreenDimCallback implements Handler.Callback { public boolean handleMessage(Message msg) { switch (msg.what) { case SCREEN_DIM: screenDim(); return true; } return false; } } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * About activity. * */ public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView versionTextView = (TextView) findViewById(R.id.version_text); String versionString = getString(R.string.unknown_build); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0 /* basic info */); versionString = info.versionName; } catch (NameNotFoundException e) { // do nothing } versionTextView.setText(getString(R.string.about_version_title, versionString)); ((Button) findViewById(R.id.button_tos)).setOnClickListener( new GoToLinkListener(R.string.tos_link)); ((Button) findViewById(R.id.button_privacy)).setOnClickListener( new GoToLinkListener(R.string.privacy_link)); ((Button) findViewById(R.id.button_tutorial)).setOnClickListener( new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(AboutActivity.this, TutorialActivity.class); startActivity(intent); } }); } private class GoToLinkListener implements OnClickListener { private String link; public GoToLinkListener(int linkId) { this.link = getString(linkId); } public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(link)); startActivity(intent); } } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.widget; import com.google.android.apps.tvremote.R; import com.google.android.apps.tvremote.MainActivity; import com.google.anymote.Key.Code; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ImageButton; /** * Button of the remote controller that has remote controller keycode assigned, * and supports displaying highlight with the support of {@link HighlightView}. * */ public class KeyCodeButton extends ImageButton { private final Code keyCode; private boolean wasPressed; /** * Key code handler interface. */ public interface KeyCodeHandler { /** * Invoked when key has became touched. * * @param keyCode touched key code. */ public void onTouch(Code keyCode); /** * Invoked when key has been released. * * @param keyCode released key code. */ public void onRelease(Code keyCode); } public KeyCodeButton(Context context) { super(context); keyCode = null; initialize(); } public KeyCodeButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RemoteButton); try { CharSequence s = a.getString(R.styleable.RemoteButton_key_code); if (s != null) { keyCode = Code.valueOf(s.toString()); enableKeyCodeAction(); } else { keyCode = null; } } finally { a.recycle(); } initialize(); } private void initialize() { setScaleType(ScaleType.CENTER_INSIDE); } private void enableKeyCodeAction() { setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { Context context = getContext(); if (context instanceof KeyCodeHandler) { KeyCodeHandler handler = (KeyCodeHandler) context; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: handler.onTouch(keyCode); break; case MotionEvent.ACTION_UP: handler.onRelease(keyCode); break; } } return false; } }); } /** * Draws button, and notifies highlight view to draw the glow. * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Notify highlight layer to draw highlight Context context = getContext(); if (context instanceof MainActivity) { HighlightView highlightView = ((MainActivity) context).getHighlightView(); if (this.isPressed()) { Rect rect = new Rect(); if (this.getGlobalVisibleRect(rect)) { highlightView.drawButtonHighlight(rect); wasPressed = true; } } else if (wasPressed) { wasPressed = false; highlightView.clearButtonHighlight(); } } } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.widget; import com.google.android.apps.tvremote.R; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.TextView; /** * Widget for displaying text that will become completely transparent. * */ public final class FadingTextView extends TextView { private final AlphaAnimation animation; private void initialize() { animation.setDuration( getContext().getResources().getInteger(R.integer.fading_text_timeout)); animation.setFillAfter(true); animation.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { } public void onAnimationRepeat(Animation animation) { } public void onAnimationEnd(Animation animation) { FadingTextView.this.setText(""); } }); setAnimation(animation); } public FadingTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); animation = new AlphaAnimation(1.0f, 0.0f); initialize(); } public FadingTextView(Context context, AttributeSet attrs) { super(context, attrs); animation = new AlphaAnimation(1.0f, 0.0f); initialize(); } public FadingTextView(Context context) { super(context); animation = new AlphaAnimation(1.0f, 0.0f); initialize(); } @Override protected void onTextChanged( CharSequence text, int start, int before, int after) { super.onTextChanged(text, start, before, after); if (!TextUtils.isEmpty(text)) { startFading(); } } private void startFading() { animation.reset(); animation.start(); } }
Java
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * 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.android.apps.tvremote.widget; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; /** * Allows key events to be intercepted when an IME is showing. * */ public final class ImeInterceptView extends ImageView { /** * Will receive intercepted key events. */ public interface Interceptor { /** * Called on non symbol key events. * * @param event the key event * @return {@code true} if the event was handled */ public boolean onKeyEvent(KeyEvent event); /** * Called when a symbol is typed. * * @param c the character being typed * @return {@code true} if the event was handled */ public boolean onSymbol(char c); } private Interceptor interceptor; private void initialize() { setFocusable(true); setFocusableInTouchMode(true); } public ImeInterceptView(Context context) { super(context); initialize(); } public ImeInterceptView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public ImeInterceptView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } public void setInterceptor(Interceptor interceptor) { this.interceptor = interceptor; } @Override public boolean dispatchKeyEventPreIme(KeyEvent event) { if (interceptor != null && interceptor.onKeyEvent(event)) { return true; } return super.dispatchKeyEventPreIme(event); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new InterceptConnection(this, true); } /** * A class that intercepts events from the soft keyboard. */ private final class InterceptConnection extends BaseInputConnection { public InterceptConnection(View targetView, boolean fullEditor) { super(targetView, fullEditor); } @Override public boolean performEditorAction(int actionCode) { interceptor.onKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); return true; } @Override public boolean setComposingText(CharSequence text, int newCursorPosition) { for (int i = 0; i < text.length(); ++i) { interceptor.onSymbol(text.charAt(i)); } return super.setComposingText(text, newCursorPosition); } @Override public boolean sendKeyEvent(KeyEvent event) { interceptor.onKeyEvent(event); return true; } @Override public boolean commitText(CharSequence text, int newCursorPosition) { for (int i = 0; i < text.length(); ++i) { interceptor.onSymbol(text.charAt(i)); } return true; } } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (hasWindowFocus) { requestFocus(); showKeyboard(); } else { hideKeyboard(); } } private void hideKeyboard() { getInputManager().hideSoftInputFromWindow( getWindowToken(), 0 /* no flag */); } private void showKeyboard() { InputMethodManager manager = getInputManager(); manager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT); } /** * Gets access to the system input manager. */ private InputMethodManager getInputManager() { return (InputMethodManager) getContext().getSystemService( Context.INPUT_METHOD_SERVICE); } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.widget; import com.google.android.apps.tvremote.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.os.Vibrator; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.widget.ImageView; /** * A widget that imitates a Dpad that would float on top of the UI. Dpad * is being simulated as a touch area that recognizes slide gestures or taps * for OK. * <p> * Make sure you set up a {@link DpadListener} to handle the events. * <p> * To position the dpad on the screen, use {@code paddingTop} or * {@code PaddingBottom}. If you use {@code PaddingBottom}, the widget will be * aligned on the bottom of the screen minus the padding. * */ public final class SoftDpad extends ImageView { /** * Interface that receives the commands. */ public interface DpadListener { /** * Called when the Dpad was clicked. */ void onDpadClicked(); /** * Called when the Dpad was moved in a given direction, and with which * action (pressed or released). * * @param direction the direction in which the Dpad was moved * @param pressed {@code true} to represent an event down */ void onDpadMoved(Direction direction, boolean pressed); } /** * Tangent of the angle used to detect a direction. * <p> * The angle should be less that 45 degree. Pre-calculated for performance. */ private static final double TAN_DIRECTION = Math.tan(Math.PI / 4); /** * Different directions where the Dpad can be moved. */ public enum Direction { /** * @hide */ IDLE(false), CENTER(false), RIGHT(true), LEFT(true), UP(true), DOWN(true); final boolean isMove; Direction(boolean isMove) { this.isMove = isMove; } } /** * Coordinates of the center of the Dpad in its initial position. */ private int centerX; private int centerY; /** * Current dpad image offset. */ private int offsetX; private int offsetY; /** * Radius of the Dpad's touchable area. */ private int radiusTouchable; /** * Radius of the area around touchable area where events get caught and ignored. */ private int radiusIgnore; /** * Percentage of half of drawable's width that is the radius. */ private float radiusPercent; /** * OK area expressed as percentage of half of drawable's width. */ private float radiusPercentOk; /** * Radius of the area handling events, should be &gt;= {@code radiusPercent} */ private float radiusPercentIgnore; /** * Coordinates of the first touch event on a sequence of movements. */ private int originTouchX; private int originTouchY; /** * Touch bounds. */ private int clickRadiusSqr; /** * {@code true} if the Dpad is capturing the events. */ private boolean isDpadFocused; /** * Direction in which the DPad is, or {@code null} if idle. */ private Direction dPadDirection; private DpadListener listener; /** * Vibrator. */ private final Vibrator vibrator; public SoftDpad(Context context, AttributeSet attrs) { super(context, attrs); vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SoftDpad); try { radiusPercent = a.getFloat(R.styleable.SoftDpad_radius_percent, 100.0f); radiusPercentOk = a.getFloat(R.styleable.SoftDpad_radius_percent_ok, 20.0f); radiusPercentIgnore = a.getFloat( R.styleable.SoftDpad_radius_percent_ignore_touch, radiusPercent); if (radiusPercentIgnore < radiusPercent) { throw new IllegalStateException( "Ignored area smaller than touchable area"); } } finally { a.recycle(); } initialize(); } private void initialize() { isDpadFocused = false; setScaleType(ScaleType.CENTER_INSIDE); dPadDirection = Direction.IDLE; } public int getCenterX() { return centerX; } public int getCenterY() { return centerY; } public void setDpadListener(DpadListener listener) { this.listener = listener; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); prepare(); } /** * Initializes the widget. Must be called after the view has been inflated. */ public void prepare() { int w = getWidth() - getPaddingLeft() - getPaddingRight(); radiusTouchable = (int) (radiusPercent * w / 200); radiusIgnore = (int) (radiusPercentIgnore * w / 200); centerX = getWidth() / 2; centerY = getHeight() / 2; clickRadiusSqr = (int) (radiusPercentOk * w / 200); clickRadiusSqr *= clickRadiusSqr; center(); } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (isEventOutsideIgnoredArea(x, y)) { return false; } if (!isEventInsideTouchableArea(x, y)) { return true; } handleActionDown(x, y); return true; case MotionEvent.ACTION_MOVE: if (isDpadFocused) { handleActionMove(x, y); return true; } break; case MotionEvent.ACTION_UP: if (isDpadFocused) { handleActionUp(x, y); } break; } return false; } private void handleActionDown(int x, int y) { dPadDirection = Direction.IDLE; isDpadFocused = true; originTouchX = x; originTouchY = y; } private void handleActionMove(int x, int y) { int dx = x - originTouchX; int dy = y - originTouchY; Direction move = getDirection(dx, dy); if (move.isMove && !dPadDirection.isMove) { sendEvent(move, true, true); dPadDirection = move; } } private void handleActionUp(int x, int y) { boolean playSound = true; handleActionMove(x, y); if (dPadDirection.isMove) { sendEvent(dPadDirection, false, playSound); } else { onCenterAction(); } center(); } /** * Centers the Dpad. */ private void center() { isDpadFocused = false; dPadDirection = Direction.IDLE; } /** * Quickly dismiss a touch event if it's not in a square around the idle * position of the Dpad. * <p> * May return {@code false} for an event outside the DPad. * * @param x x-coordinate form the top left of the screen * @param y y-coordinate form the top left of the screen * @param r radius of the circle we are testing * @return {@code true} if event is outside the Dpad */ private boolean quickDismissEvent(int x, int y, int r) { return (x < getCenterX() - r || x > getCenterX() + r || y < getCenterY() - r || y > getCenterY() + r); } /** * Returns {@code true} if the touch event is outside a circle centered on the * idle position of the Dpad and of a given radius * * @param x x-coordinate of the touch event form the top left of the screen * @param y y-coordinate of the touch event form the top left of the screen * @param r radius of the circle we are testing. * @return {@code true} if event is outside designated zone */ private boolean isEventOutside(int x, int y, int r) { if (quickDismissEvent(x, y ,r)) { return true; } int dx = (x - getCenterX()) * (x - getCenterX()); int dy = (y - getCenterY()) * (y - getCenterY()); return (dx + dy) > r * r; } /** * Returns {@code true} if the touch event is outside the touchable area * where the Dpad handles events. * * @param x x-coordinate form the top left of the screen * @param y y-coordinate form the top left of the screen * @return {@code true} if outside */ public boolean isEventOutsideIgnoredArea(int x, int y) { return isEventOutside(x, y, radiusIgnore); } /** * Returns {@code true} if the touch event is outside the area where the Dpad * is when idle, the touchable area. * * @param x x-coordinate form the top left of the screen * @param y y-coordinate form the top left of the screen * @return {@code true} if outside */ public boolean isEventInsideTouchableArea(int x, int y) { return !isEventOutside(x, y, radiusTouchable); } /** * Returns {@code true} if the dpad has moved enough from its idle position to * stop being interpreted as a click. * * @param dx movement along the x-axis from the idle position * @param dy movement along the y-axis from the idle position * @return {@code true} if not a click event */ private boolean isClick(int dx, int dy) { return (dx * dx + dy * dy) < clickRadiusSqr; } /** * Returns a direction for the movement. * * @param dx x-coordinate form the idle position of Dpad * @param dy y-coordinate form the idle position of Dpad * @return a direction, or unknown if the direction is not clear enough */ private Direction getDirection(int dx, int dy) { if (isClick(dx, dy)) { return Direction.CENTER; } if (dx == 0) { if (dy > 0) { return Direction.DOWN; } else { return Direction.UP; } } if (dy == 0) { if (dx > 0) { return Direction.RIGHT; } else { return Direction.LEFT; } } float ratioX = (float) (dy) / (float) (dx); float ratioY = (float) (dx) / (float) (dy); if (Math.abs(ratioX) < TAN_DIRECTION) { if (dx > 0) { return Direction.RIGHT; } else { return Direction.LEFT; } } if (Math.abs(ratioY) < TAN_DIRECTION) { if (dy > 0) { return Direction.DOWN; } else { return Direction.UP; } } return Direction.CENTER; } /** * Sends a DPad event if the Dpad is in the right position. * * @param move the direction in witch the event should be sent. * @param pressed {@code true} if touch just begun. * @param playSound {@code true} if click sound should be played. */ private void sendEvent(Direction move, boolean pressed, boolean playSound) { if (listener != null) { switch (move) { case UP: case DOWN: case LEFT: case RIGHT: listener.onDpadMoved(move, pressed); if (playSound) { if (pressed) { vibrator.vibrate(getResources().getInteger( R.integer.dpad_vibrate_time)); } playSound(); } } } } /** * Actions performed when the user click on the Dpad. */ private void onCenterAction() { if (listener != null) { listener.onDpadClicked(); vibrator.vibrate(getResources().getInteger( R.integer.dpad_vibrate_time)); playSound(); } } /** * Plays a sound when sending a key. */ private void playSound() { playSoundEffect(SoundEffectConstants.CLICK); } @Override protected void onDraw(Canvas canvas) { canvas.translate(offsetX, offsetY); super.onDraw(canvas); } }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote.widget; import com.google.android.apps.tvremote.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.NinePatchDrawable; import android.util.AttributeSet; import android.view.View; /** * View for displaying single "highlight" layer over buttons. * */ public final class HighlightView extends View { private final NinePatchDrawable highlightDrawable; private final Rect highlightRect; private Rect buttonRect = null; private Rect drawRect = new Rect(); public HighlightView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.HighlightView); highlightDrawable = (NinePatchDrawable) array.getDrawable(R.styleable.HighlightView_button); highlightRect = new Rect(); if (!highlightDrawable.getPadding(highlightRect)) { throw new IllegalStateException("Highlight drawable has to have padding"); } array.recycle(); } public HighlightView(Context context, AttributeSet attrs) { this(context, attrs, 0); } @Override protected void onDraw(Canvas canvas) { if (buttonRect != null) { Rect myRect = new Rect(); if (getGlobalVisibleRect(myRect)) { highlightDrawable.setBounds(drawRect); highlightDrawable.draw(canvas); } } } public void drawButtonHighlight(Rect rect) { if (highlightDrawable != null) { if (buttonRect != null) { invalidate(drawRect); } buttonRect = rect; drawRect = getHighlightRectangle(buttonRect); invalidate(drawRect); } } private Rect getHighlightRectangle(Rect globalRect) { Rect myRect = new Rect(); if (!getGlobalVisibleRect(myRect)) { throw new IllegalStateException("Highlight view not visible???"); } drawRect.left = buttonRect.left - myRect.left - highlightRect.left; drawRect.right = buttonRect.right - myRect.left + highlightRect.right; drawRect.top = buttonRect.top - myRect.top - highlightRect.top; drawRect.bottom = buttonRect.bottom - myRect.top + highlightRect.bottom; return drawRect; } public void clearButtonHighlight() { if (buttonRect != null) { buttonRect = null; invalidate(drawRect); } } }
Java
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import android.view.Menu; import android.view.MenuItem; /** */ public interface MenuInitializer { public MenuItem.OnMenuItemClickListener addMenuItems( Menu menu); }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.android.apps.tvremote.util.Action; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; /** * Simple activity that displays shortcut commands. * */ public class ShortcutsActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shortcuts); ListView list = (ListView) findViewById(R.id.command_list); list.setAdapter(new ShortcutAdapter()); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id) { Shortcut shortcut = ((ShortcutAdapter) parent.getAdapter()).get(position); shortcut.getAction().execute(getCommands()); finish(); } }); } /** * Basic adapter around the array of available shortcuts. */ private class ShortcutAdapter extends BaseAdapter { public int getCount() { return SHORTCUTS.length; } public Object getItem(int position) { return get(position); } /** * Returns the shortcut at a given position. */ Shortcut get(int position) { return SHORTCUTS[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { Shortcut item = get(position); int layoutId = R.layout.shortcuts_item; if (item.hasColor()) { layoutId = R.layout.shortcuts_item_color; } View view = getLayoutInflater().inflate(layoutId, parent, false /* don't attach now */); TextView titleView = (TextView) view.findViewById(R.id.text); if (item.hasColor()) { titleView.setTextColor(getResources().getColor(item.getColor())); } else { titleView.setTextColor( getResources().getColor(android.R.color.primary_text_dark)); } titleView.setText(item.getTitleId()); if (item.hasDetailId()) { ((TextView) view.findViewById(R.id.text_detail)).setText( item.getDetailId()); } else { ((TextView) view.findViewById(R.id.text_detail)).setText(""); } return view; } } private static final Shortcut[] SHORTCUTS = { new Shortcut(R.string.shortcut_detail_tv, R.string.shortcut_power_on_off, Action.POWER_TV), new Shortcut(R.string.shortcut_detail_tv, R.string.shortcut_input, Action.INPUT_TV), new Shortcut(R.string.shortcut_detail_avr, R.string.shortcut_power_on_off, Action.POWER_AVR), new Shortcut(R.string.shortcut_detail_bd, R.string.shortcut_menu, Action.BD_MENU), new Shortcut(R.string.shortcut_detail_bd, R.string.shortcut_topmenu, Action.BD_TOP_MENU), new Shortcut(R.string.shortcut_detail_bd, R.string.shortcut_eject, Action.EJECT), new Shortcut(R.string.shortcut_color_red, R.string.shortcut_detail_button, R.color.red, Action.COLOR_RED), new Shortcut(R.string.shortcut_color_green, R.string.shortcut_detail_button, R.color.green, Action.COLOR_GREEN), new Shortcut(R.string.shortcut_color_yellow, R.string.shortcut_detail_button, R.color.yellow, Action.COLOR_YELLOW), new Shortcut(R.string.shortcut_color_blue, R.string.shortcut_detail_button, R.color.blue, Action.COLOR_BLUE), new Shortcut(R.string.shortcut_settings, Action.SETTINGS), }; }
Java
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * 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.android.apps.tvremote; import com.google.polo.exception.PoloException; import com.google.polo.pairing.ClientPairingSession; import com.google.polo.pairing.PairingContext; import com.google.polo.pairing.PairingListener; import com.google.polo.pairing.PairingSession; import com.google.polo.pairing.message.EncodingOption; import com.google.polo.ssl.DummySSLSocketFactory; import com.google.polo.wire.PoloWireInterface; import com.google.polo.wire.WireFormat; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import java.io.IOException; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** * An Activity that handles pairing process. * * Pairing activity establishes and handles Polo pairing session. If needed, * it displays dialog to enter secret code. * */ public class PairingActivity extends CoreServiceActivity { private static final String LOG_TAG = "PairingActivity"; private static final String EXTRA_REMOTE_DEVICE = "remote_device"; private static final String EXTRA_PAIRING_RESULT = "pairing_result"; private static final String REMOTE_NAME = Build.MANUFACTURER + " " + Build.MODEL; /** * Result for pairing failure due to connection problem. */ public static final int RESULT_CONNECTION_FAILED = RESULT_FIRST_USER; /** * Result for pairing failure due to invalid code or protocol error. */ public static final int RESULT_PAIRING_FAILED = RESULT_FIRST_USER + 1; /** * Enumeration that encapsulates all valid pairing results. */ private enum Result { /** * Pairing successful. */ SUCCEEDED(Activity.RESULT_OK), /** * Pairing failed - connection problem. */ FAILED_CONNECTION(PairingActivity.RESULT_CONNECTION_FAILED), /** * Pairing failed - canceled. */ FAILED_CANCELED(Activity.RESULT_CANCELED), /** * Pairing failed - invalid secret. */ FAILED_SECRET(PairingActivity.RESULT_PAIRING_FAILED); private final int resultCode; Result(int resultCode) { this.resultCode = resultCode; } } private Handler handler; /** * Pairing dialog. */ private AlertDialog alertDialog; private PairingClientThread pairing; private ProgressDialog progressDialog; private RemoteDevice remoteDevice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(); progressDialog = buildProgressDialog(); progressDialog.show(); remoteDevice = getIntent().getParcelableExtra(EXTRA_REMOTE_DEVICE); if (remoteDevice == null) { throw new IllegalStateException(); } } @Override protected void onPause() { if (pairing != null) { pairing.cancel(); pairing = null; } hideKeyboard(); super.onPause(); } public static Intent createIntent(Context context, RemoteDevice remoteDevice) { Intent intent = new Intent(context, PairingActivity.class); intent.putExtra(EXTRA_REMOTE_DEVICE, remoteDevice); return intent; } private void startPairing() { if (pairing != null) { Log.v(LOG_TAG, "Already pairing - cancel first."); return; } Log.v(LOG_TAG, "Starting pairing with " + remoteDevice); pairing = new PairingClientThread(); new Thread(pairing).start(); } private AlertDialog createPairingDialog(final PairingClientThread client) { AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.pairing, null); final EditText pinEditText = (EditText) view.findViewById(R.id.pairing_pin_entry); builder .setPositiveButton( R.string.pairing_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog = null; client.setSecret(pinEditText.getText().toString()); } }) .setNegativeButton( R.string.pairing_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog = null; client.cancel(); } }) .setCancelable(false) .setTitle(R.string.pairing_label) .setMessage(remoteDevice.getName()) .setView(view); return builder.create(); } private void finishedPairing(Result result) { Intent resultIntent = new Intent(); resultIntent.putExtra(EXTRA_PAIRING_RESULT, result); setResult(result.resultCode); finish(); } /** * Pairing client thread, that handles pairing logic. * */ private final class PairingClientThread extends Thread { private String secret; private boolean isCancelling; public synchronized void setSecret(String secretEntered) { if (secret != null) { throw new IllegalStateException("Secret already set: " + secret); } secret = secretEntered; notify(); } public void cancel() { synchronized (this) { Log.d(LOG_TAG, "Cancelling: " + this); isCancelling = true; notify(); } try { join(); } catch (InterruptedException e) { e.printStackTrace(); } } private synchronized String getSecret() { if (isCancelling) { return null; } if (secret != null) { return secret; } try { wait(); } catch (InterruptedException e) { Log.d(LOG_TAG, "Exception occurred", e); return null; } return secret; } @Override public void run() { Result result = Result.FAILED_CONNECTION; try { SSLSocketFactory socketFactory; try { socketFactory = DummySSLSocketFactory.fromKeyManagers( getKeyStoreManager().getKeyManagers()); } catch (GeneralSecurityException e) { throw new IllegalStateException("Cannot build socket factory", e); } SSLSocket socket; try { socket = (SSLSocket) socketFactory.createSocket( remoteDevice.getAddress(), remoteDevice.getPort()); } catch (UnknownHostException e) { return; } catch (IOException e) { return; } PairingContext context; try { context = PairingContext.fromSslSocket(socket, false); } catch (PoloException e) { return; } catch (IOException e) { return; } PoloWireInterface protocol = WireFormat.PROTOCOL_BUFFERS.getWireInterface(context); ClientPairingSession pairingSession = new ClientPairingSession(protocol, context, "AnyMote", REMOTE_NAME); EncodingOption hexEnc = new EncodingOption( EncodingOption.EncodingType.ENCODING_HEXADECIMAL, 4); pairingSession.addInputEncoding(hexEnc); pairingSession.addOutputEncoding(hexEnc); PairingListener listener = new PairingListener() { public void onSessionEnded(PairingSession session) { Log.d(LOG_TAG, "onSessionEnded: " + session); } public void onSessionCreated(PairingSession session) { Log.d(LOG_TAG, "onSessionCreated: " + session); } public void onPerformOutputDeviceRole(PairingSession session, byte[] gamma) { Log.d(LOG_TAG, "onPerformOutputDeviceRole: " + session + ", " + session.getEncoder().encodeToString(gamma)); } public void onPerformInputDeviceRole(PairingSession session) { showPairingDialog(PairingClientThread.this); Log.d(LOG_TAG, "onPerformInputDeviceRole: " + session); String secret = getSecret(); Log.d(LOG_TAG, "Got: " + secret + " " + isCancelling); if (!isCancelling && secret != null) { try { byte[] secretBytes = session.getEncoder().decodeToBytes(secret); session.setSecret(secretBytes); } catch (IllegalArgumentException exception) { Log.d(LOG_TAG, "Exception while decoding secret: ", exception); session.teardown(); } catch (IllegalStateException exception) { // ISE may be thrown when session is currently terminating Log.d(LOG_TAG, "Exception while setting secret: ", exception); session.teardown(); } } else { session.teardown(); } } public void onLogMessage(LogLevel level, String message) { Log.d(LOG_TAG, "Log: " + message + " (" + level + ")"); } }; boolean ret = pairingSession.doPair(listener); if (ret) { Log.d(LOG_TAG, "Success"); getKeyStoreManager().storeCertificate(context.getServerCertificate()); result = Result.SUCCEEDED; } else if (isCancelling) { result = Result.FAILED_CANCELED; } else { result = Result.FAILED_SECRET; } } finally { sendPairingResult(result); } } } private void showPairingDialog(final PairingClientThread client) { handler.post(new Runnable() { public void run() { dismissProgressDialog(); if (pairing == null) { return; } alertDialog = createPairingDialog(client); alertDialog.show(); // Focus and show keyboard View pinView = alertDialog.findViewById(R.id.pairing_pin_entry); pinView.requestFocus(); showKeyboard(); } }); } private void sendPairingResult(final Result pairingResult) { handler.post(new Runnable() { public void run() { if (alertDialog != null) { hideKeyboard(); alertDialog.dismiss(); } finishedPairing(pairingResult); } }); } private ProgressDialog buildProgressDialog() { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage(getString(R.string.pairing_waiting)); dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { public boolean onKey( DialogInterface dialogInterface, int which, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { cancelPairing(); return true; } return false; } }); dialog.setButton(getString(R.string.pairing_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int which) { cancelPairing(); } }); return dialog; } @Override protected void onServiceAvailable(CoreService coreService) { startPairing(); } @Override protected void onServiceDisconnecting(CoreService coreService) { cancelPairing(); } private void cancelPairing() { if (pairing != null) { pairing.cancel(); pairing = null; } dismissProgressDialog(); finishedPairing(Result.FAILED_CANCELED); } private void dismissProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } private void hideKeyboard() { InputMethodManager manager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); manager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); } private void showKeyboard() { InputMethodManager manager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); manager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } }
Java