code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package com.zysoft.common.entity; import org.apache.commons.lang.builder.ToStringBuilder; import com.zysoft.common.dao.ICommonDao; import com.zysoft.common.util.ContextUtil; public abstract class AbstractEntity implements java.io.Serializable { private static final long serialVersionUID = 2035013017939483936L; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public void save() { ICommonDao commonDao = ContextUtil.getBean("ICommonDao"); commonDao.save(this); } public void delete() { ICommonDao commonDao = ContextUtil.getBean("ICommonDao"); commonDao.deleteObject(this); } public void update() { ICommonDao commonDao = ContextUtil.getBean("ICommonDao"); commonDao.update(this); } public void merge(){ ICommonDao commonDao = ContextUtil.getBean("ICommonDao"); commonDao.merge(this); } public void saveOrUpdate() { ICommonDao commonDao = ContextUtil.getBean("ICommonDao"); commonDao.saveOrUpdate(this); } /* public <T extends AbstractEntity, PK extends Serializable> T getById(PK id){ ICommonService commonService = SpringContextUtil.getBean("CommonService"); return (T) commonService.get(this.getClass(), id); } public List<? extends AbstractEntity> list(){ ICommonService commonService = SpringContextUtil.getBean("CommonService"); return commonService.listAll(this.getClass()); } */ }
zy-web-oa
src/Common/com/zysoft/common/entity/AbstractEntity.java
Java
asf20
1,590
package com.zysoft.common.dao.hibernate4Impl; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import javax.persistence.Id; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import com.zysoft.common.dao.ICommonDao; import com.zysoft.common.entity.AbstractEntity; @Repository("CommonDao") public class CommonHibernate4DaoImpl implements ICommonDao { @Autowired @Qualifier("sessionFactory") private SessionFactory sessionFactory; public Session getSession() { return sessionFactory.getCurrentSession(); } @Override public <T extends AbstractEntity> T save(T model) { // TODO Auto-generated method stub return (T) getSession().save(model); } @Override public <T extends AbstractEntity> void saveOrUpdate(T model) { // TODO Auto-generated method stub getSession().saveOrUpdate(model); } @Override public <T extends AbstractEntity> void update(T model) { // TODO Auto-generated method stub getSession().update(model); } @Override public <T extends AbstractEntity> void merge(T model) { // TODO Auto-generated method stub getSession().merge(model); } @Override public <T extends AbstractEntity, PK extends Serializable> void delete( Class<T> entityClass, PK id) { // TODO Auto-generated method stub getSession().delete(get(entityClass, id)); } @Override public <T extends AbstractEntity> void deleteObject(T model) { // TODO Auto-generated method stub getSession().delete(model); } @Override public <T extends AbstractEntity, PK extends Serializable> T get( Class<T> entityClass, PK id) { // TODO Auto-generated method stub return (T) getSession().get(entityClass, id); } @Override public int executeUpdate(String hqlUpdate, Object... paramlist) { // TODO Auto-generated method stub Query query = getSession().createQuery(hqlUpdate); if(paramlist!=null && paramlist.length==1 && (paramlist[0] instanceof Map<?,?>)) setParameters(query, (Map<String, Object>)paramlist[0]); else setParameters(query, paramlist); return query.executeUpdate(); } protected void setParameters(Query query, final Map<String, Object> map){ if(map != null){ for (Entry<String, Object> e : map.entrySet()) { Object value = e.getValue(); if(value instanceof Long) query.setLong(e.getKey(), (Long) value); else if(value instanceof Integer) query.setInteger(e.getKey(), (Integer) value); else if(value instanceof Boolean) query.setBoolean(e.getKey(), (Boolean) value); else if(value instanceof Date) query.setTimestamp(e.getKey(), (Date) value); else if(value instanceof Collection<?>) query.setParameterList(e.getKey(), (Collection<?>) value); else query.setString(e.getKey(), value.toString()); } } } protected void setParameters(Query query, Object[] paramlist) { if (paramlist != null) { for (int i = 0; i < paramlist.length; i++) { if(paramlist[i] instanceof Date) { //TODO 难道这是bug 使用setParameter不行?? query.setTimestamp(i, (Date)paramlist[i]); }else { query.setParameter(i, paramlist[i]); } } } } protected Field getPrimaryKey(Class entityClass){ Field[] fields = entityClass.getDeclaredFields(); Field primaryKey = null; for(Field f : fields) { if(f.isAnnotationPresent(Id.class)) { primaryKey = f; } } return primaryKey; } }
zy-web-oa
src/Common/com/zysoft/common/dao/hibernate4Impl/CommonHibernate4DaoImpl.java
Java
asf20
4,182
package com.zysoft.common.dao; import java.io.Serializable; import com.zysoft.common.entity.AbstractEntity; public interface ICommonDao { public <T extends AbstractEntity> T save(T model); public <T extends AbstractEntity> void saveOrUpdate(T model); public <T extends AbstractEntity> void update(T model); public <T extends AbstractEntity> void merge(T model); public <T extends AbstractEntity, PK extends Serializable> void delete(Class<T> entityClass, PK id); public <T extends AbstractEntity> void deleteObject(T model); public <T extends AbstractEntity, PK extends Serializable> T get(Class<T> entityClass, PK id); public int executeUpdate(final String hqlUpdate, final Object... paramlist); }
zy-web-oa
src/Common/com/zysoft/common/dao/ICommonDao.java
Java
asf20
788
package com.zysoft.common; public class Constants { public static final int DEFAULT_PAGE_SIZE = 10; public static final String COMMAND = "command"; }
zy-web-oa
src/Common/com/zysoft/common/Constants.java
Java
asf20
177
package com.zysoft.common.util; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.support.RequestContextUtils; @Component public class ContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; // Spring应用上下文环境 /** * 实现ApplicationContextAware接口的回调方法,设置上下文环境 * * @param applicationContext * @throws org.springframework.beans.BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ContextUtil.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } public static String getMessage(String code,Object[] args,Locale loc){ return applicationContext.getMessage(code, args, loc); } public static String getMessage(String code,Object[] args, HttpServletRequest request){ WebApplicationContext webApplicationContext = RequestContextUtils .getWebApplicationContext(request); Locale locale = null; if (webApplicationContext != null) { LocaleResolver localeResolver = RequestContextUtils .getLocaleResolver(request); if (localeResolver != null) { locale = localeResolver.resolveLocale(request); } } return webApplicationContext.getMessage(code, args, locale); } public static String getMessage(String code, HttpServletRequest request){ return getMessage(code, new Object[0], request); } /** * 获取对象 * * @param name * @return Object 一个以所给名字注册的bean的实例 * @throws org.springframework.beans.BeansException */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) applicationContext.getBean(name); } /** * 获取类型为requiredType的对象 * * @param clz * @return * @throws org.springframework.beans.BeansException */ public static <T> T getBean(Class<T> clz) throws BeansException { @SuppressWarnings("unchecked") T result = (T) applicationContext.getBean(clz); return result; } /** * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true * * @param name * @return boolean */ public static boolean containsBean(String name) { return applicationContext.containsBean(name); } /** * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) * * @param name * @return boolean * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException */ public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return applicationContext.isSingleton(name); } /** * @param name * @return Class 注册对象的类型 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException */ public static Class<?> getType(String name) throws NoSuchBeanDefinitionException { return applicationContext.getType(name); } /** * 如果给定的bean名字在bean定义中有别名,则返回这些别名 * * @param name * @return * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException */ public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { return applicationContext.getAliases(name); } }
zy-web-oa
src/Common/com/zysoft/common/util/ContextUtil.java
Java
asf20
4,358
package com.zysoft.common.util; import java.util.WeakHashMap; /** * 同步器 * */ public class KeySynchronizer { private static final WeakHashMap<Object, Locker> LOCK_MAP = new WeakHashMap<Object, Locker>(); private static class Locker { private Locker() { } } public static synchronized Object acquire(Object key) { Locker locker = LOCK_MAP.get(key); if(locker == null) { locker = new Locker(); LOCK_MAP.put(key, locker); } return locker; } }
zy-web-oa
src/Common/com/zysoft/common/util/KeySynchronizer.java
Java
asf20
575
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ include file="inc/header.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>welcome</title> </head> <body> welcome </body> </html>
zy-web-oa
WebContent/WEB-INF/jsp/index.jsp
Java Server Pages
asf20
383
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ include file="inc/header.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>欢迎</title> </head> <body> <form:form method="POST"> <form:errors path="*" cssStyle="font-color:red"/><br/> <label for="loginName" class="label">用户名:</label> <form:input path="loginName"/><br/> <label for=loginPasswd class="label">密码:</label> <form:input path="loginPasswd"/><br/> <input type="submit" value="提交"/><br/> </form:form> </body> </html>
zy-web-oa
WebContent/WEB-INF/jsp/login.jsp
Java Server Pages
asf20
728
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ include file="inc/header.jsp"%><% Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); String message = (String) request.getAttribute("javax.servlet.error.message"); String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name"); String uri = (String) request.getAttribute("javax.servlet.error.request_uri"); Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception"); if(t == null) { t = (Throwable) request.getAttribute("exception"); } Class<?> exception = (Class<?>) request.getAttribute("javax.servlet.error.exception_type"); String exceptionName = ""; if (exception != null) { exceptionName = exception.getName(); } if (statusCode == null) { statusCode = 0; } if (statusCode == 500) { LOGGER.error(statusCode + "|" + message + "|" + servletName + "|" + uri + "|" + exceptionName + "|" + request.getRemoteAddr(), t); } else if (statusCode == 404) { LOGGER.error(statusCode + "|" + message + "|" + servletName + "|" + uri + "|" + request.getRemoteAddr()); } String queryString = request.getQueryString(); String url = uri + (queryString == null || queryString.length() == 0 ? "" : "?" + queryString); url = url.replaceAll("&amp;", "&").replaceAll("&", "&amp;"); if(t != null) { LOGGER.error("error", t); } %> <html> <head> <title>页面<%=statusCode%>错误</title> </head> <body> <% if (statusCode == 404) { out.println("对不起,暂时没有找到您所访问的页面地址,请联系管理员解决此问题.<br/><br/>"); out.println("<a href=\"" + url + "\">刷新,看看是否能访问了</a><br/>"); } else { out.println("对不起,您访问的页面出了一点内部小问题,请<a href=\"" + url + "\">刷新一下</a>重新访问,或者先去别的页面转转,过会再来吧~<br/><br/>"); } %> <a href="javascript:void(0);" onclick="history.go(-1)">返回刚才页面</a><br/><br/> </body> </html> <%! private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger("DAILY_ALL"); %>
zy-web-oa
WebContent/WEB-INF/jsp/error_all.jsp
Java Server Pages
asf20
2,382
<link href="<c:url value='/css/css.css'/>" rel="stylesheet" type="text/css" media="all"></link> <script type="text/javascript" src="<c:url value='/js/jquery-1.3.2.js'/>"></script> <script type="text/javascript" src="<c:url value='/js/application.js'/>"></script>
zy-web-oa
WebContent/WEB-INF/jsp/inc/import.jsp
Java Server Pages
asf20
266
<%request.setAttribute("ctx", request.getContextPath());%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/strict.dtd"><%@include file="taglib.jsp" %><%@include file="import.jsp" %>
zy-web-oa
WebContent/WEB-INF/jsp/inc/header.jsp
Java Server Pages
asf20
223
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><%@ taglib prefix="common" uri="http://zysfot.com/common/" %>
zy-web-oa
WebContent/WEB-INF/jsp/inc/taglib.jsp
Java Server Pages
asf20
405
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/ApplicationVariantConfig.java
Java
asf20
1,503
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/TouchHandler.java
Java
asf20
13,326
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/DeviceFinder.java
Java
asf20
23,407
/* * 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(); } }); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/TutorialActivity.java
Java
asf20
1,205
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/KeyboardActivity.java
Java
asf20
2,868
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/BroadcastDiscoveryClient.java
Java
asf20
5,810
/* * 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(); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/KeyStoreManager.java
Java
asf20
7,424
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/BroadcastAdvertisement.java
Java
asf20
1,414
/* * 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() {} }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/ProtocolConstants.java
Java
asf20
1,154
/* * 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) { } }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/DummySender.java
Java
asf20
1,163
/* * 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); } }; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/Commands.java
Java
asf20
2,947
/* * 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; } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/QueuingSender.java
Java
asf20
4,476
/* * 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); }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/ICommandSender.java
Java
asf20
2,021
/* * 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); }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/Command.java
Java
asf20
893
/* * 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()); } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/AckManager.java
Java
asf20
4,969
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/protocol/AnymoteSender.java
Java
asf20
6,319
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/CoreServiceActivity.java
Java
asf20
3,836
/* * 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()); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/RemoteDevice.java
Java
asf20
3,021
/* * 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; } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/TextInputHandler.java
Java
asf20
3,433
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/util/LimitedLinkedHashMap.java
Java
asf20
1,288
/* * 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); }
zzbe0103-ji
src/com/google/android/apps/tvremote/util/Action.java
Java
asf20
6,986
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/util/Debug.java
Java
asf20
1,419
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/CoreService.java
Java
asf20
23,736
/* * 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); }
zzbe0103-ji
src/com/google/android/apps/tvremote/backport/ScaleGestureDetector.java
Java
asf20
7,082
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/backport/ScaleGestureDetectorFactory.java
Java
asf20
2,578
/* * 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(); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/backport/ScaleGestureDetectorImpl.java
Java
asf20
13,146
/* * 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; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/Shortcut.java
Java
asf20
2,040
/* * 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"; } }
zzbe0103-ji
src/com/google/android/apps/tvremote/StartupActivity.java
Java
asf20
3,171
/* * 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; } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/BaseActivity.java
Java
asf20
15,100
/* * 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); } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/AboutActivity.java
Java
asf20
2,560
/* * 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(); } } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/widget/KeyCodeButton.java
Java
asf20
3,754
/* * 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(); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/widget/FadingTextView.java
Java
asf20
2,425
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/widget/ImeInterceptView.java
Java
asf20
4,374
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/widget/SoftDpad.java
Java
asf20
11,934
/* * 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); } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/widget/HighlightView.java
Java
asf20
3,048
/* * 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); }
zzbe0103-ji
src/com/google/android/apps/tvremote/MenuInitializer.java
Java
asf20
842
/* * 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), }; }
zzbe0103-ji
src/com/google/android/apps/tvremote/ShortcutsActivity.java
Java
asf20
4,356
/* * 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); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/PairingActivity.java
Java
asf20
12,900
/* * 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.content.Context; import android.media.AudioManager; import android.view.MotionEvent; /** * The trackball logic. * */ public final class TrackballHandler { /** * Direction of dpad events. */ enum Direction { DOWN, LEFT, RIGHT, UP } /** * Modes this handler can be in. */ enum Mode { DPAD, SCROLL } /** * Sound played on trackball Dpad event. */ private static final int SOUND_TRACKBALL = AudioManager.FX_KEY_CLICK; /** * Receives translated trackball events. */ interface Listener { /** * Called when a trackball event should be interpreted as a dpad event. * * @param direction represents the direction of the dpad event */ void onDirectionalEvent(Direction direction); /** * Called when a trackball event should be interpreted as a scrolling event. * * @param dx scrolling delta along the horizontal axis * @param dy scrolling delta along the vertical axis */ void onScrollEvent(int dx, int dy); /** * Called when the trackball was clicked. */ void onClick(); } private final Listener listener; /** * Parameter that controls the threshold for the amount of trackball motion * needed to generate a directional event. */ private final float dpadThreshold; private final int scrollAmount; /** * {@code true} if trackball events should be handled. */ private boolean enabled; /** * Mode this handler is currently in. */ private Mode mode; /** * Used to store the amounts of trackball motion observed. */ private float dpadAccuX, dpadAccuY; /** * Plays some sounds on trackball events. */ private AudioManager audioManager; TrackballHandler(Listener listener, Context context) { this.listener = listener; this.mode = Mode.SCROLL; dpadThreshold = (float) context.getResources().getInteger( R.integer.dpad_threshold) / 100; scrollAmount = context.getResources().getInteger( R.integer.scroll_amount); } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setMode(Mode mode) { this.mode = mode; } public void setAudioManager(AudioManager audioManager) { this.audioManager = audioManager; } /** * Should be called on every trackball event. */ public boolean onTrackballEvent(MotionEvent event) { if (!enabled) { return false; } switch (mode) { case DPAD: return onDpad(event); case SCROLL: return onScroll(event); default: return false; } } /** * Called to interpret an event as a scrolling event. */ private boolean onScroll(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE) { int deltaX = (int) (scrollAmount * event.getX() * event.getXPrecision()); int deltaY = (int) (scrollAmount * event.getY() * event.getYPrecision()); listener.onScrollEvent(deltaX, deltaY); return true; } return false; } /** * Called to interpret an event as a dpad event. */ private boolean onDpad(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { playSoundOnDPad(); listener.onClick(); resetMotionAccumulators(); return true; } dpadAccuX += event.getX(); dpadAccuY += event.getY(); if (Math.abs(dpadAccuX) > dpadThreshold) { playSoundOnDPad(); listener.onDirectionalEvent( dpadAccuX > 0 ? Direction.RIGHT : Direction.LEFT); resetMotionAccumulators(); } if (Math.abs(dpadAccuY) > dpadThreshold) { playSoundOnDPad(); listener.onDirectionalEvent( dpadAccuY > 0 ? Direction.DOWN : Direction.UP); resetMotionAccumulators(); } return true; } private void resetMotionAccumulators() { dpadAccuX = 0; dpadAccuY = 0; } /** * Plays a sound when a Dpad event is performed. */ private void playSoundOnDPad() { if (audioManager != null) { audioManager.playSoundEffect(SOUND_TRACKBALL); } } }
zzbe0103-ji
src/com/google/android/apps/tvremote/TrackballHandler.java
Java
asf20
4,819
/* * 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.protocol.ICommandSender; import java.util.ArrayList; /** * Connection management interface. * */ public interface ConnectionManager { /** * Connection state change listener. */ public interface ConnectionListener { /** * Called when device finder is being requested. */ public void onShowDeviceFinder(); /** * Called when connection process has started. */ public void onConnecting(); /** * Called when connection succeeds. * * @param commandSender sender for given connection. */ public void onConnectionSuccessful(ICommandSender commandSender); /** * Called when remote target needs pairing. * * @param remoteDevice target to pair with. */ public void onNeedsPairing(RemoteDevice remoteDevice); /** * Called when remote gets disonnected from GTV. */ public void onDisconnected(); } /** * Setting new active target or {@code null} for no target. * * @param remoteDevice remote device. */ public void setTarget(RemoteDevice remoteDevice); /** * Connect with given connection listener. * * @param listener listener to be notified with connection state changes. */ public void connect(ConnectionListener listener); /** * Disconnect with given connection listener. * * @param listener listener to be unregistered. */ public void disconnect(ConnectionListener listener); public void setKeepConnected(boolean keepConnected); /** * Returns current active remote device. * * @return remote device. */ public RemoteDevice getTarget(); /** * Returns list of recently connected devices. * * @return recently connected devices. */ public ArrayList<RemoteDevice> getRecentlyConnected(); /** * Notifies connection manager that pairing has finished. */ public void pairingFinished(); /** * Notifies connection manager that device finder has finished. */ public void deviceFinderFinished(); /** * Requests device finder. */ public void requestDeviceFinder(); }
zzbe0103-ji
src/com/google/android/apps/tvremote/ConnectionManager.java
Java
asf20
2,806
/* * 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.TouchHandler.Mode; import com.google.android.apps.tvremote.layout.SlidingLayout; import com.google.android.apps.tvremote.util.Action; import com.google.android.apps.tvremote.widget.HighlightView; import com.google.android.apps.tvremote.widget.KeyCodeButton; import com.google.android.apps.tvremote.widget.SoftDpad; import com.google.anymote.Key; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.speech.RecognizerIntent; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import java.util.ArrayList; /** * Main screen of the remote controller activity. */ public class MainActivity extends BaseActivity implements KeyCodeButton.KeyCodeHandler { private static final String LOG_TAG = "RemoteActivity"; private HighlightView surface; private final Handler handler; /** * The enum represents modes of the remote controller with * {@link SlidingLayout} screens assignment. In conjunction with * {@link ModeSelector} allows sliding between the screens. */ private enum RemoteMode { TV(0, R.drawable.icon_04_touchpad_selector), TOUCHPAD(1, R.drawable.icon_04_buttons_selector); private final int screenId; private final int switchButtonId; RemoteMode(int screenId, int switchButtonId) { this.screenId = screenId; this.switchButtonId = switchButtonId; } } /** * Mode selector allow sliding across the modes, keeps currently selected mode * information, and slides among the modes. */ private static final class ModeSelector { private final SlidingLayout slidingLayout; private final ImageButton imageButton; private RemoteMode mode; ModeSelector( RemoteMode initialMode, SlidingLayout slidingLayout, ImageButton imageButton) { mode = initialMode; this.slidingLayout = slidingLayout; this.imageButton = imageButton; applyMode(); } void slideNext() { setMode(RemoteMode.TOUCHPAD.equals(mode) ? RemoteMode.TV : RemoteMode.TOUCHPAD); } void setMode(RemoteMode newMode) { mode = newMode; applyMode(); } void applyMode() { slidingLayout.snapToScreen(mode.screenId); imageButton.setImageResource(mode.switchButtonId); } } public MainActivity() { handler = new Handler(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_touchpad_top); surface = (HighlightView) findViewById(R.id.HighlightView); LayoutInflater inflater = LayoutInflater.from(getBaseContext()); SlidingLayout slidingLayout = (SlidingLayout) findViewById(R.id.slider); slidingLayout.addView( inflater.inflate(R.layout.subview_playcontrol_tv, null), 0); slidingLayout.addView( inflater.inflate(R.layout.subview_touchpad, null), 1); slidingLayout.setCurrentScreen(0); ImageButton nextButton = (ImageButton) findViewById(R.id.button_next_page); ImageButton keyboardButton = (ImageButton) findViewById(R.id.button_keyboard); ImageButton voiceButton = (ImageButton) findViewById(R.id.button_voice); ImageButton searchButton = (ImageButton) findViewById(R.id.button_search); ImageButton shortcutsButton = (ImageButton) findViewById(R.id.button_shortcuts); ImageButton liveTvButton = (ImageButton) findViewById(R.id.button_livetv); final ModeSelector current = new ModeSelector(RemoteMode.TV, slidingLayout, nextButton); nextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { current.slideNext(); } }); liveTvButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { current.setMode(RemoteMode.TV); } }); keyboardButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { showActivity(KeyboardActivity.class); } }); voiceButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { showVoiceSearchActivity(); } }); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Action.NAVBAR.execute(getCommands()); showActivity(KeyboardActivity.class); } }); shortcutsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { showActivity(ShortcutsActivity.class); } }); SoftDpad softDpad = (SoftDpad) findViewById(R.id.SoftDpad); softDpad.setDpadListener(getDefaultDpadListener()); // Attach touch handler to the touchpad new TouchHandler( findViewById(R.id.touch_pad), Mode.POINTER_MULTITOUCH, getCommands()); flingIntent(getIntent()); } @Override protected void onDestroy() { super.onDestroy(); } public HighlightView getHighlightView() { return surface; } // KeyCode handler implementation. public void onRelease(Key.Code keyCode) { getCommands().key(keyCode, Key.Action.UP); } public void onTouch(Key.Code keyCode) { playClick(); getCommands().key(keyCode, Key.Action.DOWN); } private void playClick() { ((AudioManager) getSystemService(Context.AUDIO_SERVICE)).playSoundEffect( AudioManager.FX_KEY_CLICK); } private void flingIntent(Intent intent) { if (intent != null) { if (Intent.ACTION_SEND.equals(intent.getAction())) { String text = intent.getStringExtra(Intent.EXTRA_TEXT); if (text != null) { Uri uri = Uri.parse(text); if (uri != null && ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))) { getCommands().flingUrl(text); } else { Toast.makeText( this, R.string.error_could_not_send_url, Toast.LENGTH_SHORT) .show(); } } else { Log.w(LOG_TAG, "No URI to fling"); } } } } @Override protected void onKeyboardOpened() { showActivity(KeyboardActivity.class); } // SUBACTIVITIES /** * The activities that can be launched from the main screen. * <p> * These codes should not conflict with the request codes defined in * {@link BaseActivity}. */ private enum SubActivity { VOICE_SEARCH, UNKNOWN; public int code() { return BaseActivity.FIRST_USER_CODE + ordinal(); } public static SubActivity fromCode(int code) { for (SubActivity activity : values()) { if (code == activity.code()) { return activity; } } return UNKNOWN; } } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { SubActivity activity = SubActivity.fromCode(requestCode); switch (activity) { case VOICE_SEARCH: onVoiceSearchResult(resultCode, data); break; default: super.onActivityResult(requestCode, resultCode, data); break; } } // VOICE SEARCH private void showVoiceSearchActivity() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); startActivityForResult(intent, SubActivity.VOICE_SEARCH.code()); } private void onVoiceSearchResult(int resultCode, Intent data) { String searchQuery; if ((resultCode == RESULT_CANCELED) || (data == null)) { return; } ArrayList<String> queryResults = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if ((queryResults == null) || (queryResults.isEmpty())) { Log.d(LOG_TAG, "No results from VoiceSearch server."); return; } else { searchQuery = queryResults.get(0); if (TextUtils.isEmpty(searchQuery)) { Log.d(LOG_TAG, "Empty result from VoiceSearch server."); return; } } showVoiceSearchDialog(searchQuery); } private void showVoiceSearchDialog(final String query) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setNeutralButton( R.string.voice_send, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { getCommands().string(query); } }) .setPositiveButton( R.string.voice_search_send, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { getCommands().keyPress(Key.Code.KEYCODE_SEARCH); // Send query delayed handler.postDelayed(new Runnable() { public void run() { getCommands().string(query); } }, getResources().getInteger(R.integer.search_query_delay)); } }) .setNegativeButton( R.string.pairing_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setCancelable(true) .setTitle(R.string.voice_dialog_label) .setMessage(query); builder.create().show(); } }
zzbe0103-ji
src/com/google/android/apps/tvremote/MainActivity.java
Java
asf20
10,322
<?php require dirname(__FILE__) . '/framework/Moon.php'; MoonBird::singleton()->start(); ?>
zyp-frame-yframe
trunk/web/server/index.php
PHP
oos
94
<?php function p($output){ $outputStr = '<pre>'; $output = var_export($output, true); $outputStr .= $output . '</pre>'; echo $outputStr; } function import($requireFile){ $file = MOON_ROOT_DIR . __DS__ . str_replace('.', __DS__, $requireFile) . '.php'; if(!file_exists($file)){ throw new MException("the file in dir({$file}) is not found"); } require_once $file; } function m_get_uri(){ return $_SERVER['REQUEST_URI']; } ?>
zyp-frame-yframe
trunk/web/server/framework/plugin/functions/functions.php
PHP
oos
454
<?php class MException extends Exception { } ?>
zyp-frame-yframe
trunk/web/server/framework/module/exception/MException.php
PHP
oos
53
<?php interface IProtocol{ public function setRoute($route); public function getRoute(); } ?>
zyp-frame-yframe
trunk/web/server/framework/module/protocol/IProtocol.php
PHP
oos
100
<?php import('framework.module.protocol.IProtocol'); class MAmfProtocol implements IProtocol { private $_route; public function setRoute($route){ $this->_route = $route; } public function getRoute(){ return $this->_route; } } ?>
zyp-frame-yframe
trunk/web/server/framework/module/protocol/MAmfProtocol.php
PHP
oos
248
<?php /** * This is a factory class of protocol * */ class MProtocolFactory{ static $_factory; private function __construct(){} static function singleton(){ if(!self::$_factory instanceof self){ self::$_factory = new self; } return self::$_factory; } public function getProtocol(){ $uri = m_get_uri(); preg_match("/^([^\?]+)/i", $uri, $match); $route = $match[1]; $routeArr = array( 'rest' => 'MRestProtocol', 'amf' => 'MAmfProtocol', ); foreach ($routeArr as $key => $value){ if(preg_match("/^\/+{$key}/i", $route)){ import('framework.module.protocol.' . $value); $protocol = new $value(); $protocol->setRoute($route); return $protocol; } } return null; } } ?>
zyp-frame-yframe
trunk/web/server/framework/module/protocol/MProtocolFactory.php
PHP
oos
760
<?php import('framework.module.protocol.IProtocol'); class MRestProtocol implements IProtocol { private $_route; public function setRoute($route){ $this->_route = $route; } } ?>
zyp-frame-yframe
trunk/web/server/framework/module/protocol/MRestProtocol.php
PHP
oos
190
<?php class MServiceResponse{ } ?>
zyp-frame-yframe
trunk/web/server/framework/module/service/MServiceResponse.php
PHP
oos
40
<?php interface IService{ } ?>
zyp-frame-yframe
trunk/web/server/framework/module/service/IService.php
PHP
oos
36
<?php class MServiceRequest{ } ?>
zyp-frame-yframe
trunk/web/server/framework/module/service/MServiceRequest.php
PHP
oos
39
<?php class MService implements IService { } ?>
zyp-frame-yframe
trunk/web/server/framework/module/service/MService.php
PHP
oos
53
<?php class MActiveRecord extends MObject { } ?>
zyp-frame-yframe
trunk/web/server/framework/module/dao/MActiveRecord.php
PHP
oos
54
<?php class MActiveRecord implements IActiveRecordDao { } ?>
zyp-frame-yframe
trunk/web/server/framework/module/dao/MActiveRecordDao.php
PHP
oos
66
<?php interface IActiveRecordDao{ function save(); function remove(); } ?>
zyp-frame-yframe
trunk/web/server/framework/module/dao/IActiveRecordDao.php
PHP
oos
81
<?php class MObject{ } ?>
zyp-frame-yframe
trunk/web/server/framework/module/dao/MObject.php
PHP
oos
31
<?php interface IRouteParse{ public function parse($dir, $route, $params); } ?>
zyp-frame-yframe
trunk/web/server/framework/module/router/IRouteParse.php
PHP
oos
84
<?php class MDbDriver { } ?>
zyp-frame-yframe
trunk/web/server/framework/module/db/MDbDriver.php
PHP
oos
34
<?php /** * define constant * */ define("__DS__", DIRECTORY_SEPARATOR); define("MOON_FRAMEWORK_DIR", dirname(__FILE__)); define("MOON_ROOT_DIR", substr(dirname(__FILE__), 0, strrpos(dirname(__FILE__), __DS__))); define("MOON_MVC_DIR", MOON_ROOT_DIR . __DS__ . 'mvc'); define("MOON_SERVICE_DIR", MOON_ROOT_DIR . __DS__ . 'service'); /** * require plugin and module */ require MOON_FRAMEWORK_DIR . __DS__ . 'plugin/functions/functions.php'; require MOON_FRAMEWORK_DIR . __DS__ . 'module/exception/MException.php'; /** * core class */ class MoonBird{ static private $_moonBird; function singleton(){ if (!self::$_moonBird instanceof self) { self::$_moonBird = new self; } return self::$_moonBird; } public function start(){ try { //get type of protocol import('framework.module.protocol.MProtocolFactory'); $protocol = MProtocolFactory::singleton()->getProtocol(); //request for mvc if($protocol == NULL){ import('framework.module.router.MRouter'); MRouter::singleton()->mvc(); exit(); } //request for service }catch (Exception $e){ p($e->getMessage()); exit(); } } } ?>
zyp-frame-yframe
trunk/web/server/framework/Moon.php
PHP
oos
1,191
#!/bin/sh SCRIPTDIR=`dirname $0` cd $SCRIPTDIR/.. RED="0.5 0.5 0.5 0 0 0 0 0 0" GREEN="0 0 0 0.5 0.5 0.5 0 0 0" for x in btn_zoom_down_disabled.9 btn_zoom_down_disabled_focused.9 btn_zoom_down_normal.9 btn_zoom_up_disabled.9 btn_zoom_up_disabled_focused.9 btn_zoom_up_normal.9 btn_zoom_width_normal ; do convert res/drawable/$x.png -recolor "$RED" res/drawable/red_$x.png convert res/drawable/$x.png -recolor "$GREEN" res/drawable/green_$x.png convert res/drawable-hdpi/$x.png -recolor "$RED" res/drawable-hdpi/red_$x.png convert res/drawable-hdpi/$x.png -recolor "$GREEN" res/drawable-hdpi/green_$x.png done
zzyangming-szyangming
pdfview/scripts/colorize-images.sh
Shell
gpl3
636
#!/bin/sh # make sure ndk-build is in path SCRIPTDIR=`dirname $0` MUPDF=mupdf-0.8.165 FREETYPE=freetype-2.4.6 OPENJPEG=openjpeg_v1_4_sources_r697 JBIG2DEC=jbig2dec-0.11 JPEGSRC=jpegsrc.v8a.tar.gz JPEGDIR=jpeg-8a cd $SCRIPTDIR/../deps tar xvf $FREETYPE.tar.bz2 tar xvf $JPEGSRC tar xvf $MUPDF-source.tar.gz tar xvf $OPENJPEG.tgz tar xvf $JBIG2DEC.tar.gz cp $OPENJPEG/libopenjpeg/*.[ch] ../jni/openjpeg/ echo '#define PACKAGE_VERSION' '"'$OPENJPEG'"' > ../jni/openjpeg/opj_config.h cp $JPEGDIR/*.[ch] ../jni/jpeg/ cp $JBIG2DEC/* ../jni/jbig2dec/ for x in draw fitz pdf ; do cp -r $MUPDF/$x/*.[ch] ../jni/mupdf/$x/ done cp -r $MUPDF/fonts ../jni/mupdf/ cp -r $FREETYPE/{src,include} ../jni/freetype/ gcc -o ../scripts/fontdump $MUPDF/scripts/fontdump.c cd ../jni/mupdf mkdir generated 2> /dev/null ../../scripts/fontdump generated/font_base14.h fonts/*.cff ../../scripts/fontdump generated/font_droid.h fonts/droid/DroidSans.ttf cd .. ndk-build
zzyangming-szyangming
pdfview/scripts/build-native.sh
Shell
gpl3
948
#!/bin/sh SCRIPTDIR=`dirname $0` cd $SCRIPTDIR/.. for x in upfolder folder home recent1 recent2 recent3 recent4 recent5 ; do convert res/drawable-hdpi/$x.png -resize 66.7% res/drawable-mdpi/$x.png convert res/drawable-hdpi/$x.png -resize 50% res/drawable-ldpi/$x.png done
zzyangming-szyangming
pdfview/scripts/scale-images.sh
Shell
gpl3
287
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Android PDF Viewer</title> <style type="text/css"> body { font-family: sans-serif; font-size: 11pt; } </style> </head> <body> <h1>O programie APV</h1> <h2>Wstęp</h2> <p> APV to natywny czytnik plików PDF dla platformy Android. </p> <p> Adres strony projektu APV to <a href="http://apv.googlecode.com/">apv.googlecode.com</a>.<br/> Zapraszamy do zgłaszania błędów na stronie <a href="http://code.google.com/p/apv/issues/">code.google.com/p/apv/issues/</a>.<br/> Istnieje również grupa użytkowników pod adresem <a href="http://groups.google.com/group/android-pdf-viewer">groups.google.com/group/android-pdf-viewer</a>. </p> <h2>Skróty klawiszowe</h2> <ul> <li>DPad Prawo/Left: następna/poprzednia strona</li> <li>DPad Dół, Spacja: przewijanie w dół</li> <li>DPad Góra, Delete: przewijanie w w górę</li> <li>H, J, K, L: przewijanie w stylu VI</li> <li>O, P: Fine zoom</li> </ul> <h2>Licencje / Biblioteki</h2> <p> APV is free software: you can redistribute it and/or modify it under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public License</a> as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. </p> <p> APV wykorzystuje następujące oprogramowanie: </p> <ul> <li> Biblioteka MuPDF firmy Artifex Software, Inc. dostępna na <a href="http://www.mupdf.com/">www.mupdf.com</a> </li> <li> This software is based in part on the work of the Independent JPEG Group. JPEG library is available at <a href="http://www.ijg.org/">www.ijg.org</a> </li> <li> Biblioteka Freetype2 dostępna na <a href="http://www.freetype.org/">www.freetype.org</a> </li> <li> Biblioteka OpenJPEG dostępna na <a href="http://code.google.com/p/openjpeg/">http://code.google.com/p/openjpeg/</a>. Licencja biblioteki OpenJPEG to <a href="http://www.opensource.org/licenses/bsd-license.php">Nowa licencja BSD</a>. </li> <li> Biblioteka jbig2dec dostępna na <a href="http://jbig2dec.sourceforge.net/">http://jbig2dec.sourceforge.net/</a> na licencji GPLv3. </li> <li> Czcionka Droid jest copyright (c) 2005-2008, The Android Open Source Project, pod <a href="http://www.apache.org/licenses/">Apache License, Wersja 2.0</a>. </li> </ul> <p>APV wykorzystuje następujące pliki graficzne:</p> <ul> <li>obiekty <em>drawable</em> btn_zoom_up i btn_zoom_down pochodzące z projektu Android Platform</li> </ul> <h2>Autorzy</h2> <ul> <li>Maciej Pietrzak <a href="mailto:maciej@hell.cx">maciej@hell.cx</a></li> <li>Ludovic Drolez <a href="mailto:ldrolez@gmail.com">ldrolez@gmail.com</a></li> <li>Naseer Ahmed <a href="mailto:naseer.ahmed@gmail.com">naseer.ahmed@gmail.com</a></li> <li>Riaz Ur Rahaman <a href="mailto:rahamanriaz@gmail.com">rahamanriaz@gmail.com</a></li> <li>Alexander Pruss <a href="mailto:arpruss@gmail.com">arpruss@gmail.com</a></li> </ul> <h2>Darowizny</h2> <p> APV jest dostępny za darmo dla wszystkich, ale jeśli chcesz, możesz wesprzeć projekt finansowo przez PayPal. Darowizny naprawdę poprawiają nam samopoczucie, a gdy się dobrze czujemy, istnieje większa szansa, że będziemy naprawiać błędy w aplikacji (aczkolwiek nic nie obiecujemy). Jeśli masz ochotę przekazać darowiznę, <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LKB59NTKW9QLS">kliknij tutaj</a>, </p> <h3 style="text-align: center;">GNU GENERAL PUBLIC LICENSE</h3> <p style="text-align: center;">Version 3, 29 June 2007</p> <p>Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<a href="http://fsf.org/">http://fsf.org/</a>&gt;</p><p> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.</p> <h3><a name="preamble"></a>Preamble</h3> <p>The GNU General Public License is a free, copyleft license for software and other kinds of works.</p> <p>The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.</p> <p>When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.</p> <p>To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.</p> <p>For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.</p> <p>Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.</p> <p>For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.</p> <p>Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.</p> <p>Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.</p> <p>The precise terms and conditions for copying, distribution and modification follow.</p> <h3><a name="terms"></a>TERMS AND CONDITIONS</h3> <h4><a name="section0"></a>0. Definitions.</h4> <p>&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.</p> <p>&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.</p> <p>&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and &ldquo;recipients&rdquo; may be individuals or organizations.</p> <p>To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a &ldquo;modified version&rdquo; of the earlier work or a work &ldquo;based on&rdquo; the earlier work.</p> <p>A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on the Program.</p> <p>To &ldquo;propagate&rdquo; a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.</p> <p>To &ldquo;convey&rdquo; a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.</p> <p>An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo; to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.</p> <h4><a name="section1"></a>1. Source Code.</h4> <p>The &ldquo;source code&rdquo; for a work means the preferred form of the work for making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a work.</p> <p>A &ldquo;Standard Interface&rdquo; means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.</p> <p>The &ldquo;System Libraries&rdquo; of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A &ldquo;Major Component&rdquo;, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.</p> <p>The &ldquo;Corresponding Source&rdquo; for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.</p> <p>The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.</p> <p>The Corresponding Source for a work in source code form is that same work.</p> <h4><a name="section2"></a>2. Basic Permissions.</h4> <p>All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.</p> <p>You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.</p> <p>Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.</p> <h4><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4> <p>No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.</p> <p>When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.</p> <h4><a name="section4"></a>4. Conveying Verbatim Copies.</h4> <p>You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.</p> <p>You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.</p> <h4><a name="section5"></a>5. Conveying Modified Source Versions.</h4> <p>You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:</p> <ul> <li>a) The work must carry prominent notices stating that you modified it, and giving a relevant date.</li> <li>b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to &ldquo;keep intact all notices&rdquo;.</li> <li>c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.</li> <li>d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.</li> </ul> <p>A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an &ldquo;aggregate&rdquo; if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.</p> <h4><a name="section6"></a>6. Conveying Non-Source Forms.</h4> <p>You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:</p> <ul> <li>a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.</li> <li>b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.</li> <li>c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.</li> <li>d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.</li> <li>e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.</li> </ul> <p>A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.</p> <p>A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, &ldquo;normally used&rdquo; refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.</p> <p>&ldquo;Installation Information&rdquo; for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.</p> <p>If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).</p> <p>The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.</p> <p>Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.</p> <h4><a name="section7"></a>7. Additional Terms.</h4> <p>&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.</p> <p>When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.</p> <p>Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:</p> <ul> <li>a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or</li> <li>b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or</li> <li>c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or</li> <li>d) Limiting the use for publicity purposes of names of licensors or authors of the material; or</li> <li>e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or</li> <li>f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.</li> </ul> <p>All other non-permissive additional terms are considered &ldquo;further restrictions&rdquo; within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.</p> <p>If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.</p> <p>Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.</p> <h4><a name="section8"></a>8. Termination.</h4> <p>You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).</p> <p>However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.</p> <p>Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.</p> <p>Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.</p> <h4><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4> <p>You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.</p> <h4><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4> <p>Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.</p> <p>An &ldquo;entity transaction&rdquo; is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.</p> <p>You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.</p> <h4><a name="section11"></a>11. Patents.</h4> <p>A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's &ldquo;contributor version&rdquo;.</p> <p>A contributor's &ldquo;essential patent claims&rdquo; are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, &ldquo;control&rdquo; includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.</p> <p>Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.</p> <p>In the following three paragraphs, a &ldquo;patent license&rdquo; is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To &ldquo;grant&rdquo; such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.</p> <p>If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. &ldquo;Knowingly relying&rdquo; means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.</p> <p>If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.</p> <p>A patent license is &ldquo;discriminatory&rdquo; if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.</p> <p>Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.</p> <h4><a name="section12"></a>12. No Surrender of Others' Freedom.</h4> <p>If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.</p> <h4><a name="section13"></a>13. Use with the GNU Affero General Public License.</h4> <p>Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.</p> <h4><a name="section14"></a>14. Revised Versions of this License.</h4> <p>The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.</p> <p>Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License &ldquo;or any later version&rdquo; applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.</p> <p>If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.</p> <p>Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.</p> <h4><a name="section15"></a>15. Disclaimer of Warranty.</h4> <p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p> <h4><a name="section16"></a>16. Limitation of Liability.</h4> <p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> <h4><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4> <p>If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.</p> <p>END OF TERMS AND CONDITIONS</p> </body> </html>
zzyangming-szyangming
pdfview/res/raw-pl/about.html
HTML
gpl3
38,640
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Android PDF Viewer</title> <style type="text/css"> body { font-family: sans-serif; font-size: 11pt; } </style> </head> <body> <h1>About APV</h1> <h2>Overview</h2> <p> APV is native PDF Viewer for Android Platform. </p> <p> APV project page is at <a href="http://apv.googlecode.com/">apv.googlecode.com</a>.<br/> You are welcome to report bugs at <a href="http://code.google.com/p/apv/issues/">code.google.com/p/apv/issues/</a>.<br/> There's also a user group at <a href="http://groups.google.com/group/android-pdf-viewer">groups.google.com/group/android-pdf-viewer</a>. </p> <h2>Keyboard shortcuts</h2> <ul> <li>DPad Right/Left: next/previous page</li> <li>DPad Down, Space: scroll down</li> <li>DPad Up, Delete: scroll up</li> <li>H, J, K, L: VI like motion keys</li> <li>O, P: Fine zoom</li> </ul> <h2>License / Libraries</h2> <p> APV is free software: you can redistribute it and/or modify it under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public License</a> as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. </p> <p> APV uses following third party software: </p> <ul> <li> MuPDF library by Artifex Software, Inc. available at <a href="http://www.mupdf.com/">www.mupdf.com/</a></li> <li> This software is based in part on the work of the Independent JPEG Group. JPEG library is available at <a href="http://www.ijg.org/">www.ijg.org</a> </li> <li> FreeType2 library available at <a href="http://www.freetype.org/">www.freetype.org</a></li> <li> OpenJPEG library available at <a href="http://code.google.com/p/openjpeg/">http://code.google.com/p/openjpeg/</a>. OpenJPEG library is licensed under <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD License</a>. </li> <li> jbig2dec library available at <a href="http://jbig2dec.sourceforge.net/">http://jbig2dec.sourceforge.net/</a>. jbig2dec is licensed under GPLv3. <li> Droid font is Copyright (c) 2005-2008, The Android Open Source Project. Licensed under the <a href="http://www.apache.org/licenses/">Apache License, Version 2.0</a>. </li> </ul> <p>APV uses following third party media:</p> <ul> <li>btn_zoom_up and btn_zoom_down drawables that are part of Android Platform</li> </ul> <h2>Credits</h2> <p>APV is developed by</p> <ul> <li>Maciej Pietrzak <a href="mailto:maciej@hell.cx">maciej@hell.cx</a></li> <li>Ludovic Drolez <a href="mailto:ldrolez@gmail.com">ldrolez@gmail.com</a></li> <li>Naseer Ahmed <a href="mailto:naseer.ahmed@gmail.com">naseer.ahmed@gmail.com</a></li> <li>Riaz Ur Rahaman <a href="mailto:rahamanriaz@gmail.com">rahamanriaz@gmail.com</a></li> <li>Alexander Pruss <a href="mailto:arpruss@gmail.com">arpruss@gmail.com</a></li> </ul> <h2>Donations</h2> <p> APV is free (like in freedom), but you can always show gratitude for our work by donating via PayPal. Dontations really make us feel appreciated, and when we feel appreciated, we are more likely to fix bugs (although we can't promise anything). If you'd like to donate, please click <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LKB59NTKW9QLS">here</a>. </p> <h3 style="text-align: center;">GNU GENERAL PUBLIC LICENSE</h3> <p style="text-align: center;">Version 3, 29 June 2007</p> <p>Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<a href="http://fsf.org/">http://fsf.org/</a>&gt;</p><p> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.</p> <h3><a name="preamble"></a>Preamble</h3> <p>The GNU General Public License is a free, copyleft license for software and other kinds of works.</p> <p>The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.</p> <p>When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.</p> <p>To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.</p> <p>For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.</p> <p>Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.</p> <p>For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.</p> <p>Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.</p> <p>Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.</p> <p>The precise terms and conditions for copying, distribution and modification follow.</p> <h3><a name="terms"></a>TERMS AND CONDITIONS</h3> <h4><a name="section0"></a>0. Definitions.</h4> <p>&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.</p> <p>&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.</p> <p>&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and &ldquo;recipients&rdquo; may be individuals or organizations.</p> <p>To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a &ldquo;modified version&rdquo; of the earlier work or a work &ldquo;based on&rdquo; the earlier work.</p> <p>A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on the Program.</p> <p>To &ldquo;propagate&rdquo; a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.</p> <p>To &ldquo;convey&rdquo; a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.</p> <p>An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo; to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.</p> <h4><a name="section1"></a>1. Source Code.</h4> <p>The &ldquo;source code&rdquo; for a work means the preferred form of the work for making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a work.</p> <p>A &ldquo;Standard Interface&rdquo; means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.</p> <p>The &ldquo;System Libraries&rdquo; of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A &ldquo;Major Component&rdquo;, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.</p> <p>The &ldquo;Corresponding Source&rdquo; for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.</p> <p>The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.</p> <p>The Corresponding Source for a work in source code form is that same work.</p> <h4><a name="section2"></a>2. Basic Permissions.</h4> <p>All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.</p> <p>You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.</p> <p>Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.</p> <h4><a name="section3"></a>3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4> <p>No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.</p> <p>When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.</p> <h4><a name="section4"></a>4. Conveying Verbatim Copies.</h4> <p>You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.</p> <p>You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.</p> <h4><a name="section5"></a>5. Conveying Modified Source Versions.</h4> <p>You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:</p> <ul> <li>a) The work must carry prominent notices stating that you modified it, and giving a relevant date.</li> <li>b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to &ldquo;keep intact all notices&rdquo;.</li> <li>c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.</li> <li>d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.</li> </ul> <p>A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an &ldquo;aggregate&rdquo; if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.</p> <h4><a name="section6"></a>6. Conveying Non-Source Forms.</h4> <p>You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:</p> <ul> <li>a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.</li> <li>b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.</li> <li>c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.</li> <li>d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.</li> <li>e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.</li> </ul> <p>A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.</p> <p>A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, &ldquo;normally used&rdquo; refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.</p> <p>&ldquo;Installation Information&rdquo; for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.</p> <p>If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).</p> <p>The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.</p> <p>Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.</p> <h4><a name="section7"></a>7. Additional Terms.</h4> <p>&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.</p> <p>When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.</p> <p>Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:</p> <ul> <li>a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or</li> <li>b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or</li> <li>c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or</li> <li>d) Limiting the use for publicity purposes of names of licensors or authors of the material; or</li> <li>e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or</li> <li>f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.</li> </ul> <p>All other non-permissive additional terms are considered &ldquo;further restrictions&rdquo; within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.</p> <p>If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.</p> <p>Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.</p> <h4><a name="section8"></a>8. Termination.</h4> <p>You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).</p> <p>However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.</p> <p>Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.</p> <p>Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.</p> <h4><a name="section9"></a>9. Acceptance Not Required for Having Copies.</h4> <p>You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.</p> <h4><a name="section10"></a>10. Automatic Licensing of Downstream Recipients.</h4> <p>Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.</p> <p>An &ldquo;entity transaction&rdquo; is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.</p> <p>You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.</p> <h4><a name="section11"></a>11. Patents.</h4> <p>A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's &ldquo;contributor version&rdquo;.</p> <p>A contributor's &ldquo;essential patent claims&rdquo; are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, &ldquo;control&rdquo; includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.</p> <p>Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.</p> <p>In the following three paragraphs, a &ldquo;patent license&rdquo; is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To &ldquo;grant&rdquo; such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.</p> <p>If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. &ldquo;Knowingly relying&rdquo; means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.</p> <p>If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.</p> <p>A patent license is &ldquo;discriminatory&rdquo; if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.</p> <p>Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.</p> <h4><a name="section12"></a>12. No Surrender of Others' Freedom.</h4> <p>If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.</p> <h4><a name="section13"></a>13. Use with the GNU Affero General Public License.</h4> <p>Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.</p> <h4><a name="section14"></a>14. Revised Versions of this License.</h4> <p>The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.</p> <p>Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License &ldquo;or any later version&rdquo; applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.</p> <p>If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.</p> <p>Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.</p> <h4><a name="section15"></a>15. Disclaimer of Warranty.</h4> <p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p> <h4><a name="section16"></a>16. Limitation of Liability.</h4> <p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> <h4><a name="section17"></a>17. Interpretation of Sections 15 and 16.</h4> <p>If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.</p> <p>END OF TERMS AND CONDITIONS</p> </body> </html>
zzyangming-szyangming
pdfview/res/raw/about.html
HTML
gpl3
38,716
package cx.hell.android.pdfview; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.text.InputType; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import cx.hell.android.lib.pagesview.FindResult; import cx.hell.android.lib.pagesview.PagesView; /** * Document display activity. */ public class OpenFileActivity extends Activity { private final static String TAG = "cx.hell.android.pdfview"; private final static int[] zoomAnimations = { R.anim.zoom_disappear, R.anim.zoom_almost_disappear, R.anim.zoom }; private final static int[] pageNumberAnimations = { R.anim.page_disappear, R.anim.page_almost_disappear, R.anim.page, R.anim.page_show_always }; private PDF pdf = null; private PagesView pagesView = null; private PDFPagesProvider pdfPagesProvider = null; private Handler zoomHandler = null; private Handler pageHandler = null; private Runnable zoomRunnable = null; private Runnable pageRunnable = null; private MenuItem aboutMenuItem = null; private MenuItem gotoPageMenuItem = null; private MenuItem rotateLeftMenuItem = null; private MenuItem rotateRightMenuItem = null; private MenuItem findTextMenuItem = null; private MenuItem clearFindTextMenuItem = null; private MenuItem chooseFileMenuItem = null; private MenuItem optionsMenuItem = null; private EditText pageNumberInputField = null; private EditText findTextInputField = null; private LinearLayout findButtonsLayout = null; private Button findPrevButton = null; private Button findNextButton = null; private Button findHideButton = null; private RelativeLayout activityLayout = null; // currently opened file path private String filePath = "/"; private String findText = null; private Integer currentFindResultPage = null; private Integer currentFindResultNumber = null; // zoom buttons, layout and fade animation private ImageButton zoomDownButton; private ImageButton zoomWidthButton; private ImageButton zoomUpButton; private Animation zoomAnim; private LinearLayout zoomLayout; // page number display private TextView pageNumberTextView; private Animation pageNumberAnim; private int box = 2; private int fadeStartOffset = 7000; private int colorMode = Options.COLOR_MODE_NORMAL; private static final int ZOOM_COLOR_NORMAL = 0; private static final int ZOOM_COLOR_RED = 1; private static final int ZOOM_COLOR_GREEN = 2; private static final int[] zoomUpId = { R.drawable.btn_zoom_up, R.drawable.red_btn_zoom_up, R.drawable.green_btn_zoom_up }; private static final int[] zoomDownId = { R.drawable.btn_zoom_down, R.drawable.red_btn_zoom_down, R.drawable.green_btn_zoom_down }; private static final int[] zoomWidthId = { R.drawable.btn_zoom_width, R.drawable.red_btn_zoom_width, R.drawable.green_btn_zoom_width }; /** * Called when the activity is first created. * TODO: initialize dialog fast, then move file loading to other thread * TODO: add progress bar for file load * TODO: add progress icon for file rendering */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Options.setOrientation(this); SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this); this.box = Integer.parseInt(options.getString(Options.PREF_BOX, "2")); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Get display metrics DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); // use a relative layout to stack the views activityLayout = new RelativeLayout(this); // the PDF view this.pagesView = new PagesView(this); activityLayout.addView(pagesView); startPDF(options); // the find buttons this.findButtonsLayout = new LinearLayout(this); this.findButtonsLayout.setOrientation(LinearLayout.HORIZONTAL); this.findButtonsLayout.setVisibility(View.GONE); this.findButtonsLayout.setGravity(Gravity.CENTER); this.findPrevButton = new Button(this); this.findPrevButton.setText("Prev"); this.findButtonsLayout.addView(this.findPrevButton); this.findNextButton = new Button(this); this.findNextButton.setText("Next"); this.findButtonsLayout.addView(this.findNextButton); this.findHideButton = new Button(this); this.findHideButton.setText("Hide"); this.findButtonsLayout.addView(this.findHideButton); this.setFindButtonHandlers(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.CENTER_HORIZONTAL); lp.addRule(RelativeLayout.ALIGN_PARENT_TOP); activityLayout.addView(this.findButtonsLayout, lp); this.pageNumberTextView = new TextView(this); this.pageNumberTextView.setTextSize(8f*metrics.density); lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); lp.addRule(RelativeLayout.ALIGN_PARENT_TOP); activityLayout.addView(this.pageNumberTextView, lp); // display this this.setContentView(activityLayout); // go to last viewed page // gotoLastPage(); // send keyboard events to this view pagesView.setFocusable(true); pagesView.setFocusableInTouchMode(true); this.zoomHandler = new Handler(); this.pageHandler = new Handler(); this.zoomRunnable = new Runnable() { public void run() { fadeZoom(); } }; this.pageRunnable = new Runnable() { public void run() { fadePage(); } }; } /** * Save the current page before exiting */ @Override protected void onPause() { saveLastPage(); super.onPause(); } @Override protected void onResume() { super.onResume(); Options.setOrientation(this); SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this); setZoomLayout(options); this.pagesView.setSideMargins(options.getBoolean(Options.PREF_SIDE_MARGINS, false)); int newBox = Integer.parseInt(options.getString(Options.PREF_BOX, "2")); if (this.box != newBox) { saveLastPage(); this.box = newBox; startPDF(options); this.pagesView.goToBookmark(); } this.colorMode = Options.getColorMode(options); this.pageNumberTextView.setBackgroundColor(Options.getBackColor(colorMode)); this.pageNumberTextView.setTextColor(Options.getForeColor(colorMode)); this.pdfPagesProvider.setGray(Options.isGray(this.colorMode)); this.pdfPagesProvider.setExtraCache(1024*1024*Options.getIntFromString(options, Options.PREF_EXTRA_CACHE, 0)); this.pdfPagesProvider.setOmitImages(options.getBoolean(Options.PREF_OMIT_IMAGES, false)); this.pagesView.setColorMode(this.colorMode); pagesView.setZoomIncrement( Float.parseFloat(options.getString(Options.PREF_ZOOM_INCREMENT, "1.414"))); this.pdfPagesProvider.setRenderAhead(options.getBoolean(Options.PREF_RENDER_AHEAD, true)); this.pagesView.setPageWithVolume(options.getBoolean(Options.PREF_PAGE_WITH_VOLUME, true)); this.pagesView.setVerticalScrollLock(options.getBoolean(Options.PREF_VERTICAL_SCROLL_LOCK, false)); this.pagesView.invalidate(); zoomAnim = AnimationUtils.loadAnimation(this, zoomAnimations[ Integer.parseInt(options.getString(Options.PREF_ZOOM_ANIMATION, "2"))]); pageNumberAnim = AnimationUtils.loadAnimation(this, pageNumberAnimations[ Integer.parseInt(options.getString(Options.PREF_PAGE_ANIMATION, "3"))]); fadeStartOffset = 1000 * Integer.parseInt(options.getString(Options.PREF_FADE_SPEED, "7")); if (options.getBoolean(Options.PREF_FULLSCREEN, false)) getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); showAnimated(); } /** * Set handlers on findNextButton and findHideButton. */ private void setFindButtonHandlers() { this.findPrevButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findPrev(); } }); this.findNextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findNext(); } }); this.findHideButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findHide(); } }); } /** * Set handlers on zoom level buttons */ private void setZoomButtonHandlers() { this.zoomDownButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { pagesView.zoomDownBig(); return true; } }); this.zoomDownButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagesView.zoomDown(); } }); this.zoomWidthButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagesView.zoomWidth(); } }); this.zoomWidthButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { pagesView.zoomFit(); return true; } }); this.zoomUpButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagesView.zoomUp(); } }); this.zoomUpButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { pagesView.zoomUpBig(); return true; } }); } private void startPDF(SharedPreferences options) { this.pdf = this.getPDF(); this.colorMode = Options.getColorMode(options); this.pdfPagesProvider = new PDFPagesProvider(this, pdf, Options.isGray(this.colorMode), options.getBoolean(Options.PREF_OMIT_IMAGES, false), options.getBoolean(Options.PREF_RENDER_AHEAD, true)); pagesView.setPagesProvider(pdfPagesProvider); Bookmark b = new Bookmark(this.getApplicationContext()).open(); pagesView.setStartBookmark(b, filePath); b.close(); } /** * Return PDF instance wrapping file referenced by Intent. * Currently reads all bytes to memory, in future local files * should be passed to native code and remote ones should * be downloaded to local tmp dir. * @return PDF instance */ private PDF getPDF() { final Intent intent = getIntent(); Uri uri = intent.getData(); filePath = uri.getPath(); if (uri.getScheme().equals("file")) { Recent recent = new Recent(this); recent.add(0, filePath); recent.commit(); return new PDF(new File(filePath), this.box); } else if (uri.getScheme().equals("content")) { ContentResolver cr = this.getContentResolver(); FileDescriptor fileDescriptor; try { fileDescriptor = cr.openFileDescriptor(uri, "r").getFileDescriptor(); } catch (FileNotFoundException e) { throw new RuntimeException(e); // TODO: handle errors } return new PDF(fileDescriptor, this.box); } else { throw new RuntimeException("don't know how to get filename from " + uri); } } /** * Handle menu. * @param menuItem selected menu item * @return true if menu item was handled */ @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem == this.aboutMenuItem) { Intent intent = new Intent(); intent.setClass(this, AboutPDFViewActivity.class); this.startActivity(intent); return true; } else if (menuItem == this.gotoPageMenuItem) { this.showGotoPageDialog(); } else if (menuItem == this.rotateLeftMenuItem) { this.pagesView.rotate(-1); } else if (menuItem == this.rotateRightMenuItem) { this.pagesView.rotate(1); } else if (menuItem == this.findTextMenuItem) { this.showFindDialog(); } else if (menuItem == this.clearFindTextMenuItem) { this.clearFind(); } else if (menuItem == this.chooseFileMenuItem) { startActivity(new Intent(this, ChooseFileActivity.class)); } else if (menuItem == this.optionsMenuItem) { startActivity(new Intent(this, Options.class)); } return false; } /** * Intercept touch events to handle the zoom buttons animation */ @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { showAnimated(); } return super.dispatchTouchEvent(event); }; public boolean dispatchKeyEvent(KeyEvent event) { int action = event.getAction(); if (action == KeyEvent.ACTION_UP || action == KeyEvent.ACTION_DOWN) { showAnimated(); } return super.dispatchKeyEvent(event); }; private void showZoom() { zoomLayout.clearAnimation(); zoomHandler.removeCallbacks(zoomRunnable); zoomHandler.postDelayed(zoomRunnable, fadeStartOffset); } private void fadeZoom() { zoomAnim.setStartOffset(0); zoomAnim.setFillAfter(true); zoomLayout.startAnimation(zoomAnim); } public void showPageNumber(boolean force) { String newText = ""+(this.pagesView.getCurrentPage()+1)+"/"+ this.pdfPagesProvider.getPageCount(); if (!force && newText.equals(pageNumberTextView.getText())) return; pageNumberTextView.setText(newText); pageNumberTextView.clearAnimation(); pageHandler.removeCallbacks(pageRunnable); pageHandler.postDelayed(pageRunnable, fadeStartOffset); } private void fadePage() { pageNumberAnim.setStartOffset(0); pageNumberAnim.setFillAfter(true); pageNumberTextView.startAnimation(pageNumberAnim); } /** * Show zoom buttons and page number */ private void showAnimated() { showZoom(); showPageNumber(true); } /** * Hide the find buttons */ private void clearFind() { this.currentFindResultPage = null; this.currentFindResultNumber = null; this.pagesView.setFindMode(false); this.findButtonsLayout.setVisibility(View.GONE); } /** * Show error message to user. * @param message message to show */ private void errorMessage(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog dialog = builder.setMessage(message).setTitle("Error").create(); dialog.show(); } /** * Called from menu when user want to go to specific page. */ private void showGotoPageDialog() { final Dialog d = new Dialog(this); d.setTitle(R.string.goto_page_dialog_title); LinearLayout contents = new LinearLayout(this); contents.setOrientation(LinearLayout.VERTICAL); TextView label = new TextView(this); final int pagecount = this.pdfPagesProvider.getPageCount(); label.setText("Page number from " + 1 + " to " + pagecount); this.pageNumberInputField = new EditText(this); this.pageNumberInputField.setInputType(InputType.TYPE_CLASS_NUMBER); this.pageNumberInputField.setText("" + (this.pagesView.getCurrentPage() + 1)); Button goButton = new Button(this); goButton.setText(R.string.goto_page_go_button); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { int pageNumber = -1; try { pageNumber = Integer.parseInt(OpenFileActivity.this.pageNumberInputField.getText().toString())-1; } catch (NumberFormatException e) { /* ignore */ } d.dismiss(); if (pageNumber >= 0 && pageNumber < pagecount) { OpenFileActivity.this.gotoPage(pageNumber); } else { OpenFileActivity.this.errorMessage("Invalid page number"); } } }); Button page1Button = new Button(this); page1Button.setText(getResources().getString(R.string.page) +" 1"); page1Button.setOnClickListener(new OnClickListener() { public void onClick(View v) { d.dismiss(); OpenFileActivity.this.gotoPage(0); } }); Button lastPageButton = new Button(this); lastPageButton.setText(getResources().getString(R.string.page) +" "+pagecount); lastPageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { d.dismiss(); OpenFileActivity.this.gotoPage(pagecount-1); } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = 5; params.rightMargin = 5; params.bottomMargin = 2; params.topMargin = 2; contents.addView(label, params); contents.addView(pageNumberInputField, params); contents.addView(goButton, params); contents.addView(page1Button, params); contents.addView(lastPageButton, params); d.setContentView(contents); d.show(); } private void gotoPage(int page) { Log.i(TAG, "rewind to page " + page); if (this.pagesView != null) { this.pagesView.scrollToPage(page); showAnimated(); } } /** * Save the last page in the bookmarks */ private void saveLastPage() { BookmarkEntry entry = this.pagesView.toBookmarkEntry(); Bookmark b = new Bookmark(this.getApplicationContext()).open(); b.setLast(filePath, entry); b.close(); Log.i(TAG, "last page saved for "+filePath); } /** * * Create options menu, called by Android system. * @param menu menu to populate * @return true meaning that menu was populated */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); this.gotoPageMenuItem = menu.add(R.string.goto_page); this.rotateRightMenuItem = menu.add(R.string.rotate_page_left); this.rotateLeftMenuItem = menu.add(R.string.rotate_page_right); this.clearFindTextMenuItem = menu.add(R.string.clear_find_text); this.chooseFileMenuItem = menu.add(R.string.choose_file); this.optionsMenuItem = menu.add(R.string.options); /* The following appear on the second page. The find item can safely be kept * there since it can also be accessed from the search key on most devices. */ this.findTextMenuItem = menu.add(R.string.find_text); this.aboutMenuItem = menu.add(R.string.about); return true; } /** * Prepare menu contents. * Hide or show "Clear find results" menu item depending on whether * we're in find mode. * @param menu menu that should be prepared */ @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); this.clearFindTextMenuItem.setVisible(this.pagesView.getFindMode()); return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(TAG, "onConfigurationChanged(" + newConfig + ")"); } /** * Show find dialog. * Very pretty UI code ;) */ public void showFindDialog() { Log.d(TAG, "find dialog..."); final Dialog dialog = new Dialog(this); dialog.setTitle(R.string.find_dialog_title); LinearLayout contents = new LinearLayout(this); contents.setOrientation(LinearLayout.VERTICAL); this.findTextInputField = new EditText(this); this.findTextInputField.setWidth(this.pagesView.getWidth() * 80 / 100); Button goButton = new Button(this); goButton.setText(R.string.find_go_button); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { String text = OpenFileActivity.this.findTextInputField.getText().toString(); OpenFileActivity.this.findText(text); dialog.dismiss(); } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = 5; params.rightMargin = 5; params.bottomMargin = 2; params.topMargin = 2; contents.addView(findTextInputField, params); contents.addView(goButton, params); dialog.setContentView(contents); dialog.show(); } private void setZoomLayout(SharedPreferences options) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int colorMode = Options.getColorMode(options); int mode = ZOOM_COLOR_NORMAL; if (colorMode == Options.COLOR_MODE_GREEN_ON_BLACK) { mode = ZOOM_COLOR_GREEN; } else if (colorMode == Options.COLOR_MODE_RED_ON_BLACK) { mode = ZOOM_COLOR_RED; } // the zoom buttons if (zoomLayout != null) { activityLayout.removeView(zoomLayout); } zoomLayout = new LinearLayout(this); zoomLayout.setOrientation(LinearLayout.HORIZONTAL); zoomDownButton = new ImageButton(this); zoomDownButton.setImageDrawable(getResources().getDrawable(zoomDownId[mode])); zoomDownButton.setBackgroundColor(Color.TRANSPARENT); zoomLayout.addView(zoomDownButton, (int)(80 * metrics.density), (int)(50 * metrics.density)); // TODO: remove hardcoded values zoomWidthButton = new ImageButton(this); zoomWidthButton.setImageDrawable(getResources().getDrawable(zoomWidthId[mode])); zoomWidthButton.setBackgroundColor(Color.TRANSPARENT); zoomLayout.addView(zoomWidthButton, (int)(58 * metrics.density), (int)(50 * metrics.density)); zoomUpButton = new ImageButton(this); zoomUpButton.setImageDrawable(getResources().getDrawable(zoomUpId[mode])); zoomUpButton.setBackgroundColor(Color.TRANSPARENT); zoomLayout.addView(zoomUpButton, (int)(80 * metrics.density), (int)(50 * metrics.density)); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.CENTER_HORIZONTAL); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); setZoomButtonHandlers(); activityLayout.addView(zoomLayout,lp); } private void findText(String text) { Log.d(TAG, "findText(" + text + ")"); this.findText = text; this.find(true); } /** * Called when user presses "next" button in find panel. */ private void findNext() { this.find(true); } /** * Called when user presses "prev" button in find panel. */ private void findPrev() { this.find(false); } /** * Called when user presses hide button in find panel. */ private void findHide() { if (this.pagesView != null) this.pagesView.setFindMode(false); this.currentFindResultNumber = null; this.currentFindResultPage = null; this.findButtonsLayout.setVisibility(View.GONE); } /** * Helper class that handles search progress, search cancelling etc. */ static class Finder implements Runnable, DialogInterface.OnCancelListener, DialogInterface.OnClickListener { private OpenFileActivity parent = null; private boolean forward; private AlertDialog dialog = null; private String text; private int startingPage; private int pageCount; private boolean cancelled = false; /** * Constructor for finder. * @param parent parent activity */ public Finder(OpenFileActivity parent, boolean forward) { this.parent = parent; this.forward = forward; this.text = parent.findText; this.pageCount = parent.pagesView.getPageCount(); if (parent.currentFindResultPage != null) { if (forward) { this.startingPage = (parent.currentFindResultPage + 1) % pageCount; } else { this.startingPage = (parent.currentFindResultPage - 1 + pageCount) % pageCount; } } else { this.startingPage = parent.pagesView.getCurrentPage(); } } public void setDialog(AlertDialog dialog) { this.dialog = dialog; } public void run() { int page = -1; this.createDialog(); this.showDialog(); for(int i = 0; i < this.pageCount; ++i) { if (this.cancelled) { this.dismissDialog(); return; } page = (startingPage + pageCount + (this.forward ? i : -i)) % this.pageCount; Log.d(TAG, "searching on " + page); this.updateDialog(page); List<FindResult> findResults = this.findOnPage(page); if (findResults != null && !findResults.isEmpty()) { Log.d(TAG, "found something at page " + page + ": " + findResults.size() + " results"); this.dismissDialog(); this.showFindResults(findResults, page); return; } } /* TODO: show "nothing found" message */ this.dismissDialog(); } /** * Called by finder thread to get find results for given page. * Routed to PDF instance. * If result is not empty, then finder loop breaks, current find position * is saved and find results are displayed. * @param page page to search on * @return results */ private List<FindResult> findOnPage(int page) { if (this.text == null) throw new IllegalStateException("text cannot be null"); return this.parent.pdf.find(this.text, page); } private void createDialog() { this.parent.runOnUiThread(new Runnable() { public void run() { String title = Finder.this.parent.getString(R.string.searching_for).replace("%1$s", Finder.this.text); String message = Finder.this.parent.getString(R.string.page_of).replace("%1$d", String.valueOf(Finder.this.startingPage)).replace("%2$d", String.valueOf(pageCount)); AlertDialog.Builder builder = new AlertDialog.Builder(Finder.this.parent); AlertDialog dialog = builder .setTitle(title) .setMessage(message) .setCancelable(true) .setNegativeButton(R.string.cancel, Finder.this) .create(); dialog.setOnCancelListener(Finder.this); Finder.this.dialog = dialog; } }); } public void updateDialog(final int page) { this.parent.runOnUiThread(new Runnable() { public void run() { String message = Finder.this.parent.getString(R.string.page_of).replace("%1$d", String.valueOf(page)).replace("%2$d", String.valueOf(pageCount)); Finder.this.dialog.setMessage(message); } }); } public void showDialog() { this.parent.runOnUiThread(new Runnable() { public void run() { Finder.this.dialog.show(); } }); } public void dismissDialog() { final AlertDialog dialog = this.dialog; this.parent.runOnUiThread(new Runnable() { public void run() { dialog.dismiss(); } }); } public void onCancel(DialogInterface dialog) { Log.d(TAG, "onCancel(" + dialog + ")"); this.cancelled = true; } public void onClick(DialogInterface dialog, int which) { Log.d(TAG, "onClick(" + dialog + ")"); this.cancelled = true; } private void showFindResults(final List<FindResult> findResults, final int page) { this.parent.runOnUiThread(new Runnable() { public void run() { int fn = Finder.this.forward ? 0 : findResults.size()-1; Finder.this.parent.currentFindResultPage = page; Finder.this.parent.currentFindResultNumber = fn; Finder.this.parent.pagesView.setFindResults(findResults); Finder.this.parent.pagesView.setFindMode(true); Finder.this.parent.pagesView.scrollToFindResult(fn); Finder.this.parent.findButtonsLayout.setVisibility(View.VISIBLE); Finder.this.parent.pagesView.invalidate(); } }); } }; /** * GUI for finding text. * Used both on initial search and for "next" and "prev" searches. * Displays dialog, handles cancel button, hides dialog as soon as * something is found. * @param */ private void find(boolean forward) { if (this.currentFindResultPage != null) { /* searching again */ int nextResultNum = forward ? this.currentFindResultNumber + 1 : this.currentFindResultNumber - 1; if (nextResultNum >= 0 && nextResultNum < this.pagesView.getFindResults().size()) { /* no need to really find - just focus on given result and exit */ this.currentFindResultNumber = nextResultNum; this.pagesView.scrollToFindResult(nextResultNum); this.pagesView.invalidate(); return; } } /* finder handles next/prev and initial search by itself */ Finder finder = new Finder(this, forward); Thread finderThread = new Thread(finder); finderThread.start(); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/OpenFileActivity.java
Java
gpl3
30,125
package cx.hell.android.pdfview; import java.io.File; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; public class Recent extends ArrayList<String> { /** * Default serial version identifier because base class is serializable. */ private static final long serialVersionUID = 1L; private final static int MAX_RECENT=5; /* must be at least 1 */ private final String PREF_TAG = "Recent"; private final String RECENT_PREFIX = "Recent."; private final String RECENT_COUNT = "count"; private Context context; public Recent(Context context) { super(); this.context = context; SharedPreferences pref = this.context.getSharedPreferences(PREF_TAG, 0); int count = pref.getInt(RECENT_COUNT, 0); for(int i=0; i<count; i++) { String fileName = pref.getString(RECENT_PREFIX + i, ""); File file = new File(fileName); if (file.exists()) { add(fileName); } } } private void write() { SharedPreferences.Editor edit = this.context.getSharedPreferences(PREF_TAG, 0).edit(); edit.putInt(RECENT_COUNT, size()); for(int i=0; i<size(); i++) { edit.putString(RECENT_PREFIX + i, get(i)); } edit.commit(); } void commit() { for(int i=size()-1; i>=0; i--) { for(int j=0; j<i; j++) { if (get(i).equals(get(j))) { remove(i); break; } } } for(int i=size()-1; i>=MAX_RECENT; i--) { remove(i); } write(); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/Recent.java
Java
gpl3
1,536
package cx.hell.android.pdfview; import android.app.Activity; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; public class Options extends PreferenceActivity { public final static String PREF_TAG = "Options"; public final static String PREF_PAGE_WITH_VOLUME = "pageWithVolume"; public final static String PREF_ZOOM_INCREMENT = "zoomIncrement"; public final static String PREF_INVERT = "invert"; public final static String PREF_ZOOM_ANIMATION = "zoomAnimation"; public final static String PREF_DIRS_FIRST = "dirsFirst"; public final static String PREF_SHOW_EXTENSION = "showExtension"; public final static String PREF_ORIENTATION = "orientation"; public final static String PREF_FULLSCREEN = "fullscreen"; public final static String PREF_PAGE_ANIMATION = "pageAnimation"; public final static String PREF_FADE_SPEED = "fadeSpeed"; public final static String PREF_RENDER_AHEAD = "renderAhead"; public final static String PREF_GRAY = "gray"; public final static String PREF_COLOR_MODE = "colorMode"; public final static String PREF_OMIT_IMAGES = "omitImages"; public final static String PREF_VERTICAL_SCROLL_LOCK = "verticalScrollLock"; public final static String PREF_BOX = "boxType"; public final static String PREF_SIDE_MARGINS = "sideMargins"; public final static String PREF_EXTRA_CACHE = "extraCache"; public final static int COLOR_MODE_NORMAL = 0; public final static int COLOR_MODE_INVERT = 1; public final static int COLOR_MODE_GRAY = 2; public final static int COLOR_MODE_INVERT_GRAY = 3; public final static int COLOR_MODE_BLACK_ON_YELLOWISH = 4; public final static int COLOR_MODE_GREEN_ON_BLACK = 5; public final static int COLOR_MODE_RED_ON_BLACK = 6; private final static int[] foreColors = { Color.BLACK, Color.WHITE, Color.BLACK, Color.WHITE, Color.BLACK, Color.GREEN, Color.RED }; private final static int[] backColors = { Color.WHITE, Color.BLACK, Color.WHITE, Color.BLACK, Color.rgb(239, 219, 189), Color.BLACK, Color.BLACK }; private static final float[][] colorMatrices = { null, /* COLOR_MODE_NORMAL */ {-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_INVERT */ 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 0.0f, 255.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_GRAY */ 0.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_INVERT_GRAY */ 0.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, -1.0f, 255.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 239.0f, /* COLOR_MODE_BLACK_ON_YELLOWISH */ 0.0f, 0.0f, 0.0f, 0.0f, 219.0f, 0.0f, 0.0f, 0.0f, 0.0f, 189.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 0f, /* COLOR_MODE_GREEN_ON_BLACK */ 0.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0f, 0.0f, 0.0f, 0.0f, -1.0f, 255.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 255.0f, /* COLOR_MODE_RED_ON_BLACK */ 0.0f, 0.0f, 0.0f, 0.0f, 0f, 0.0f, 0.0f, 0.0f, 0.0f, 0f, 0.0f, 0.0f, 0.0f, -1.0f, 255.0f} }; public static int getIntFromString(SharedPreferences pref, String option, int def) { return Integer.parseInt(pref.getString(option, ""+def)); } public static float[] getColorModeMatrix(int colorMode) { return colorMatrices[colorMode]; } public static boolean isGray(int colorMode) { return COLOR_MODE_GRAY <= colorMode; } public static int getForeColor(int colorMode) { return foreColors[colorMode]; } public static int getBackColor(int colorMode) { return backColors[colorMode]; } public static int getColorMode(SharedPreferences pref) { return getIntFromString(pref, PREF_COLOR_MODE, 0); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.options); } @Override public void onResume() { super.onResume(); setOrientation(this); } public static void setOrientation(Activity activity) { SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(activity); int orientation = Integer.parseInt(options.getString(PREF_ORIENTATION, "0")); switch(orientation) { case 0: activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); break; case 1: activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case 2: activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; default: break; } } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/Options.java
Java
gpl3
4,826
package cx.hell.android.pdfview; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; /** * Displays "About..." info. */ public class AboutPDFViewActivity extends Activity { @Override public void onCreate(Bundle state) { super.onCreate(state); this.setContentView(R.layout.about); WebView v = (WebView)this.findViewById(R.id.webview_about); android.content.res.Resources resources = this.getResources(); InputStream aboutHtmlInputStream = new BufferedInputStream(resources.openRawResource(R.raw.about)); String aboutHtml = null; try { aboutHtml = StreamUtils.readStringFully(aboutHtmlInputStream); aboutHtmlInputStream.close(); aboutHtmlInputStream = null; resources = null; } catch (IOException e) { throw new RuntimeException(e); } v.loadData( aboutHtml, "text/html", "utf-8" ); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/AboutPDFViewActivity.java
Java
gpl3
1,012
package cx.hell.android.pdfview; import java.io.IOException; import java.io.InputStream; import android.util.Log; import android.widget.ProgressBar; public class StreamUtils { public static byte[] readBytesFully(InputStream i) throws IOException { return StreamUtils.readBytesFully(i, 0, null); } public static byte[] readBytesFully(InputStream i, int max, ProgressBar progressBar) throws IOException { byte buf[] = new byte[4096]; int totalReadBytes = 0; while(true) { int readBytes = 0; readBytes = i.read(buf, totalReadBytes, buf.length-totalReadBytes); if (readBytes < 0) { // end of stream break; } totalReadBytes += readBytes; if (progressBar != null) progressBar.setProgress(totalReadBytes); if (max > 0 && totalReadBytes > max) { throw new IOException("Remote file is too big"); } if (totalReadBytes == buf.length) { // grow buf Log.d("cx.hell.android.pdfview", "readBytesFully: growing buffer from " + buf.length + " to " + (buf.length*2)); byte newbuf[] = new byte[buf.length*2]; System.arraycopy(buf, 0, newbuf, 0, totalReadBytes); buf = newbuf; } } byte result[] = new byte[totalReadBytes]; System.arraycopy(buf, 0, result, 0, totalReadBytes); return result; } public static String readStringFully(InputStream i) throws IOException { byte[] b = StreamUtils.readBytesFully(i); return new String(b, "utf-8"); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/StreamUtils.java
Java
gpl3
1,470
package cx.hell.android.pdfview; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; /** * Minimalistic file browser. */ public class ChooseFileActivity extends Activity implements OnItemClickListener { /** * Logging tag. */ private final static String TAG = "cx.hell.android.pdfview"; private final static String PREF_TAG = "ChooseFileActivity"; private final static String PREF_HOME = "Home"; private final static int[] recentIds = { R.id.recent1, R.id.recent2, R.id.recent3, R.id.recent4, R.id.recent5 }; private String currentPath; private TextView pathTextView = null; private ListView filesListView = null; private FileFilter fileFilter = null; private ArrayAdapter<FileListEntry> fileListAdapter = null; private ArrayList<FileListEntry> fileList = null; private Recent recent = null; private MenuItem aboutMenuItem = null; private MenuItem setAsHomeMenuItem = null; private MenuItem optionsMenuItem = null; private MenuItem deleteContextMenuItem = null; private MenuItem removeContextMenuItem = null; private MenuItem setAsHomeContextMenuItem = null; private Boolean dirsFirst = true; private Boolean showExtension = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); currentPath = getHome(); this.fileFilter = new FileFilter() { public boolean accept(File f) { return (f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf")); } }; this.setContentView(R.layout.filechooser); this.pathTextView = (TextView) this.findViewById(R.id.path); this.filesListView = (ListView) this.findViewById(R.id.files); final Activity activity = this; this.fileList = new ArrayList<FileListEntry>(); this.fileListAdapter = new ArrayAdapter<FileListEntry>(this, R.layout.onelinewithicon, fileList) { public View getView(int position, View convertView, ViewGroup parent) { View v; if (convertView == null) { v = View.inflate(activity, R.layout.onelinewithicon, null); } else { v = convertView; } FileListEntry entry = fileList.get(position); v.findViewById(R.id.home).setVisibility( entry.getType() == FileListEntry.HOME ? View.VISIBLE:View.GONE ); v.findViewById(R.id.upfolder).setVisibility( entry.isUpFolder() ? View.VISIBLE:View.GONE ); v.findViewById(R.id.folder).setVisibility( (entry.getType() == FileListEntry.NORMAL && entry.isDirectory() && ! entry.isUpFolder()) ? View.VISIBLE:View.GONE ); int r = entry.getRecentNumber(); for (int i=0; i < recentIds.length; i++) { v.findViewById(recentIds[i]).setVisibility( i == r ? View.VISIBLE : View.GONE); } TextView tv = (TextView)v.findViewById(R.id.text); tv.setText(entry.getLabel()); tv.setTypeface(tv.getTypeface(), entry.getType() == FileListEntry.RECENT ? Typeface.ITALIC : Typeface.NORMAL); return v; } }; this.filesListView.setAdapter(this.fileListAdapter); this.filesListView.setOnItemClickListener(this); registerForContextMenu(this.filesListView); } /** * Reset list view and list adapter to reflect change to currentPath. */ private void update() { this.pathTextView.setText(this.currentPath); this.fileListAdapter.clear(); FileListEntry entry; if (isHome(currentPath)) { recent = new Recent(this); for (int i = 0; i < recent.size() && i < recentIds.length; i++) { File file = new File(recent.get(i)); entry = new FileListEntry(FileListEntry.RECENT, i, file, showExtension); this.fileList.add(entry); } } else { recent = null; } entry = new FileListEntry(FileListEntry.HOME, getResources().getString(R.string.go_home)); this.fileListAdapter.add(entry); if (!this.currentPath.equals("/")) { File upFolder = new File(this.currentPath).getParentFile(); entry = new FileListEntry(FileListEntry.NORMAL, -1, upFolder, ".."); this.fileListAdapter.add(entry); } File files[] = new File(this.currentPath).listFiles(this.fileFilter); if (files != null) { try { Arrays.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { if (f1 == null) throw new RuntimeException("f1 is null inside sort"); if (f2 == null) throw new RuntimeException("f2 is null inside sort"); try { if (dirsFirst && f1.isDirectory() != f2.isDirectory()) { if (f1.isDirectory()) return -1; else return 1; } return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase()); } catch (NullPointerException e) { throw new RuntimeException("failed to compare " + f1 + " and " + f2, e); } } }); } catch (NullPointerException e) { throw new RuntimeException("failed to sort file list " + files + " for path " + this.currentPath, e); } for (File file:files) { entry = new FileListEntry(FileListEntry.NORMAL, -1, file, showExtension); this.fileListAdapter.add(entry); } } this.filesListView.setSelection(0); } public void pdfView(File f) { Log.i(TAG, "post intent to open file " + f); Intent intent = new Intent(); intent.setDataAndType(Uri.fromFile(f), "application/pdf"); intent.setClass(this, OpenFileActivity.class); intent.setAction("android.intent.action.VIEW"); this.startActivity(intent); } private String getHome() { String defaultHome = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = getSharedPreferences(PREF_TAG, 0).getString(PREF_HOME, defaultHome); if (path.length()>1 && path.endsWith("/")) { path = path.substring(0,path.length()-2); } File pathFile = new File(path); if (pathFile.exists() && pathFile.isDirectory()) return path; else return defaultHome; } @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { FileListEntry clickedEntry = this.fileList.get(position); File clickedFile; if (clickedEntry.getType() == FileListEntry.HOME) { clickedFile = new File(getHome()); } else { clickedFile = clickedEntry.getFile(); } if (!clickedFile.exists()) return; if (clickedFile.isDirectory()) { this.currentPath = clickedFile.getAbsolutePath(); this.update(); } else { pdfView(clickedFile); } } public void setAsHome() { SharedPreferences.Editor edit = getSharedPreferences(PREF_TAG, 0).edit(); edit.putString(PREF_HOME, currentPath); edit.commit(); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem == this.aboutMenuItem) { Intent intent = new Intent(); intent.setClass(this, AboutPDFViewActivity.class); this.startActivity(intent); return true; } else if (menuItem == this.setAsHomeMenuItem) { setAsHome(); return true; } else if (menuItem == this.optionsMenuItem){ startActivity(new Intent(this, Options.class)); } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { this.setAsHomeMenuItem = menu.add(R.string.set_as_home); this.optionsMenuItem = menu.add(R.string.options); this.aboutMenuItem = menu.add("About"); return true; } @Override public void onResume() { super.onResume(); Options.setOrientation(this); SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(this); dirsFirst = options.getBoolean(Options.PREF_DIRS_FIRST, true); showExtension = options.getBoolean(Options.PREF_SHOW_EXTENSION, false); this.update(); } @Override public boolean onContextItemSelected(MenuItem item) { int position = ((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position; if (item == deleteContextMenuItem) { FileListEntry entry = this.fileList.get(position); if (entry.getType() == FileListEntry.NORMAL && ! entry.isDirectory()) { entry.getFile().delete(); update(); } return true; } else if (item == removeContextMenuItem) { FileListEntry entry = this.fileList.get(position); if (entry.getType() == FileListEntry.RECENT) { recent.remove(entry.getRecentNumber()); recent.commit(); update(); } } else if (item == setAsHomeContextMenuItem) { setAsHome(); } return false; } private boolean isHome(String path) { File pathFile = new File(path); File homeFile = new File(getHome()); try { return pathFile.getCanonicalPath().equals(homeFile.getCanonicalPath()); } catch (IOException e) { return false; } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v == this.filesListView) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; if (info.position < 0) return; FileListEntry entry = this.fileList.get(info.position); if (entry.getType() == FileListEntry.HOME) { setAsHomeContextMenuItem = menu.add(R.string.set_as_home); } else if (entry.getType() == FileListEntry.RECENT) { removeContextMenuItem = menu.add(R.string.remove_from_recent); } else if (! entry.isDirectory()) { deleteContextMenuItem = menu.add(R.string.delete); } } } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/ChooseFileActivity.java
Java
gpl3
11,215
package cx.hell.android.pdfview; import android.graphics.Bitmap; public class BitmapCacheValue { public Bitmap bitmap; /* public long millisAdded; */ public long millisAccessed; public long priority; public BitmapCacheValue(Bitmap bitmap, long millisAdded, long priority) { this.bitmap = bitmap; /* this.millisAdded = millisAdded; */ this.millisAccessed = millisAdded; this.priority = priority; } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/BitmapCacheValue.java
Java
gpl3
434
package cx.hell.android.pdfview; import java.io.File; import java.io.FileDescriptor; import java.util.List; import cx.hell.android.lib.pagesview.FindResult; /** * Native PDF - interface to native code. */ public class PDF { static { System.loadLibrary("pdfview2"); } /** * Simple size class used in JNI to simplify parameter passing. * This shouldn't be used anywhere outide of pdf-related code. */ public static class Size implements Cloneable { public int width; public int height; public Size() { this.width = 0; this.height = 0; } public Size(int width, int height) { this.width = width; this.height = height; } public Size clone() { return new Size(this.width, this.height); } } /** * Holds pointer to native pdf_t struct. */ private int pdf_ptr = 0; /** * Parse bytes as PDF file and store resulting pdf_t struct in pdf_ptr. * @return error code */ /* synchronized private native int parseBytes(byte[] bytes, int box); */ /** * Parse PDF file. * @param fileName pdf file name * @return error code */ synchronized private native int parseFile(String fileName, int box); /** * Parse PDF file. * @param fd opened file descriptor * @return error code */ synchronized private native int parseFileDescriptor(FileDescriptor fd, int box); /** * Construct PDF structures from bytes stored in memory. */ /* public PDF(byte[] bytes, int box) { this.parseBytes(bytes, box); } */ /** * Construct PDF structures from file sitting on local filesystem. */ public PDF(File file, int box) { this.parseFile(file.getAbsolutePath(), box); } /** * Construct PDF structures from opened file descriptor. * @param file opened file descriptor */ public PDF(FileDescriptor file, int box) { this.parseFileDescriptor(file, box); } /** * Return page count from pdf_t struct. */ synchronized public native int getPageCount(); /** * Render a page. * @param n page number, starting from 0 * @param zoom page size scaling * @param left left edge * @param right right edge * @param passes requested size, used for size of resulting bitmap * @return bytes of bitmap in Androids format */ synchronized public native int[] renderPage(int n, int zoom, int left, int top, int rotation, boolean gray, boolean skipImages, PDF.Size rect); /** * Get PDF page size, store it in size struct, return error code. * @param n 0-based page number * @param size size struct that holds result * @return error code */ synchronized public native int getPageSize(int n, PDF.Size size); /** * Export PDF to a text file. */ // synchronized public native void export(); /** * Find text on given page, return list of find results. */ synchronized public native List<FindResult> find(String text, int page); /** * Clear search. */ synchronized public native void clearFindResult(); /** * Find text on page, return find results. */ synchronized public native List<FindResult> findOnPage(int page, String text); /** * Free memory allocated in native code. */ synchronized private native void freeMemory(); public void finalize() { try { super.finalize(); } catch (Throwable e) { } this.freeMemory(); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/PDF.java
Java
gpl3
3,432
package cx.hell.android.pdfview; /** * High level user-visible application exception. */ public class ApplicationException extends Exception { private static final long serialVersionUID = 3168318522532680977L; public ApplicationException(String message) { super(message); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/ApplicationException.java
Java
gpl3
299
package cx.hell.android.pdfview; public class BookmarkEntry { public int numberOfPages; public int page; public float absoluteZoomLevel; public int rotation; public int offsetX; public BookmarkEntry(int numberOfPages, int page, float absoluteZoomLevel, int rotation, int offsetX) { this.numberOfPages = numberOfPages; this.page = page; this.absoluteZoomLevel = absoluteZoomLevel; this.rotation = rotation; this.offsetX = offsetX; } public BookmarkEntry(String s) { String data[] = s.split(" "); if (0 < data.length) { this.numberOfPages = Integer.parseInt(data[0]); } else { this.numberOfPages = 0; } if (1 < data.length) { this.page = Integer.parseInt(data[1]); } else { this.page = 0; } if (2 < data.length) { this.absoluteZoomLevel = Float.parseFloat(data[2]); } else { this.absoluteZoomLevel = 0f; } if (3 < data.length) { this.rotation = Integer.parseInt(data[3]); } else { this.rotation = 0; } if (4 < data.length) { this.offsetX = Integer.parseInt(data[4]); } else { this.offsetX = 0; } } public String toString() { return ""+numberOfPages+" "+page+" "+absoluteZoomLevel+" "+rotation+" "+offsetX; } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/BookmarkEntry.java
Java
gpl3
1,291
package cx.hell.android.pdfview; import java.io.File; public class FileListEntry { private String label = null; private File file = null; private boolean isDirectory = false; private int type = NORMAL; private int recentNumber = -1; static final int NORMAL = 0; static final int HOME = 1; static final int RECENT = 2; public FileListEntry(int type, int recentNumber, File file, String label) { this.file = file; this.label = file.getName(); this.isDirectory = file.isDirectory(); this.type = type; this.label = label; this.recentNumber = recentNumber; } public FileListEntry(int type, int recentNumber, File file, Boolean showPDFExtension) { this(type, recentNumber, file, getLabel(file, showPDFExtension)); } public FileListEntry(int type, String label) { this.type = type; this.label = label; } private static String getLabel(File file, boolean showPDFExtension) { String label = file.getName(); if (!showPDFExtension && label.length() > 4 && ! file.isDirectory() && label.substring(label.length()-4, label.length()).equalsIgnoreCase(".pdf")) { return label.substring(0, label.length()-4); } else { return label; } } public int getRecentNumber() { return this.recentNumber; } public int getType() { return this.type; } public File getFile() { return this.file; } public String getLabel() { return this.label; } public boolean isDirectory() { return this.isDirectory; } public boolean isUpFolder() { return this.isDirectory && this.label.equals(".."); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/FileListEntry.java
Java
gpl3
1,637
/* * Copyright 2010 Ludovic Drolez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package cx.hell.android.pdfview; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Class to manage the last opened page and bookmarks of PDF files * * @author Ludovic Drolez * */ public class Bookmark { /** db fields */ public static final String KEY_ID = "_id"; public static final String KEY_BOOK = "book"; public static final String KEY_NAME = "name"; public static final String KEY_COMMENT = "comment"; public static final String KEY_TIME = "time"; public static final String KEY_ENTRY = "entry"; private static final int DB_VERSION = 1; private static final String DATABASE_CREATE = "create table bookmark " + "(_id integer primary key autoincrement, " + "book text not null, name text not null, " + "entry integer, comment text, time integer);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; /** * Constructor * * @param ctx * application context */ public Bookmark(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } /** * Database helper class */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, "bookmarks.db", null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } /** * open the bookmark database * * @return the Bookmark object * @throws SQLException */ public Bookmark open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } /** * close the database */ public void close() { DBHelper.close(); } /** * Set the last page seen for a file * * @param file * full file path * @param page * last page */ public void setLast(String file, BookmarkEntry entry) { String md5 = nameToMD5(file); ContentValues cv = new ContentValues(); cv.put(KEY_BOOK, md5); cv.put(KEY_ENTRY, entry.toString()); cv.put(KEY_NAME, "last"); cv.put(KEY_TIME, System.currentTimeMillis() / 1000); if (db.update("bookmark", cv, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null) == 0) { db.insert("bookmark", null, cv); } } public BookmarkEntry getLast(String file) { BookmarkEntry entry = null; String md5 = nameToMD5(file); Cursor cur = db.query(true, "bookmark", new String[] { KEY_ENTRY }, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null, null, null, null, "1"); if (cur != null) { if (cur.moveToFirst()) { entry = new BookmarkEntry(cur.getString(0)); } } cur.close(); return entry; } /** * Hash the file name to be sure that no strange characters will be in the * DB, and include file length. * * @param file * path * @return md5 */ private String nameToMD5(String file) { // Create MD5 Hash MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } String message = file + ":" + (new File(file)).length(); digest.update(message.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/Bookmark.java
Java
gpl3
4,514
package cx.hell.android.pdfview; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.app.Activity; import android.graphics.Bitmap; import android.os.SystemClock; import android.util.Log; import cx.hell.android.lib.pagesview.OnImageRenderedListener; import cx.hell.android.lib.pagesview.PagesProvider; import cx.hell.android.lib.pagesview.RenderingException; import cx.hell.android.lib.pagesview.Tile; /** * Provide rendered bitmaps of pages. */ public class PDFPagesProvider extends PagesProvider { /** * Const used by logging. */ private final static String TAG = "cx.hell.android.pdfview"; /* render a little more than twice the screen height, so the next page will be ready */ private float renderAhead = 2.1f; private boolean doRenderAhead = true; private boolean gray; private int extraCache = 0; private boolean omitImages; Activity activity = null; public void setGray(boolean gray) { if (this.gray == gray) return; this.gray = gray; if (this.bitmapCache != null) { this.bitmapCache.clearCache(); } setMaxCacheSize(); } public void setExtraCache(int extraCache) { this.extraCache = extraCache; setMaxCacheSize(); } /* also calculates renderAhead */ private void setMaxCacheSize() { int maxMax = (int)(7*1024*1024) + this.extraCache; /* at most allocate this much unless absolutely necessary */ int minMax = 4*1024*1024; /* at least allocate this much */ int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight(); int screenWidth = activity.getWindowManager().getDefaultDisplay().getWidth(); int displaySize = screenWidth * screenHeight; if (displaySize <= 320*240) displaySize = 320*240; if (!this.gray) displaySize *= 2; int m = (int)(displaySize * 1.25f * 1.0001f); if (doRenderAhead) { if ((int)(m * 2.1f) <= maxMax) { renderAhead = 2.1f; m = (int)(m * renderAhead); } else { renderAhead = 1.0001f; } } else { /* The extra little bit is to compensate for round-off */ renderAhead = 1.0001f; } if (m < minMax) m = minMax; if (m < maxMax) { m += this.extraCache; if (maxMax < m) m = maxMax; } Log.v(TAG, "Setting cache size="+m+ " renderAhead="+renderAhead+" for "+screenWidth+"x"+screenHeight); this.bitmapCache.setMaxCacheSizeBytes(m); } public void setOmitImages(boolean skipImages) { if (this.omitImages == skipImages) return; this.omitImages = skipImages; if (this.bitmapCache != null) { this.bitmapCache.clearCache(); } } /** * Smart page-bitmap cache. * Stores up to approx maxCacheSizeBytes of images. * Dynamically drops oldest unused bitmaps. * TODO: Return high resolution bitmaps if no exact res is available. * Bitmap images are tiled - tile size is specified in PagesView.TILE_SIZE. */ private static class BitmapCache { /** * Stores cached bitmaps. */ private Map<Tile, BitmapCacheValue> bitmaps; private int maxCacheSizeBytes = 4*1024*1024; /** * Stats logging - number of cache hits. */ private long hits; /** * Stats logging - number of misses. */ private long misses; BitmapCache() { this.bitmaps = new HashMap<Tile, BitmapCacheValue>(); this.hits = 0; this.misses = 0; } public void setMaxCacheSizeBytes(int maxCacheSizeBytes) { this.maxCacheSizeBytes = maxCacheSizeBytes; } /** * Get cached bitmap. Updates last access timestamp. * @param k cache key * @return bitmap found in cache or null if there's no matching bitmap */ Bitmap get(Tile k) { BitmapCacheValue v = this.bitmaps.get(k); Bitmap b = null; if (v != null) { // yeah b = v.bitmap; assert b != null; v.millisAccessed = System.currentTimeMillis(); this.hits += 1; } else { // le fu this.misses += 1; } if ((this.hits + this.misses) % 100 == 0 && (this.hits > 0 || this.misses > 0)) { Log.d("cx.hell.android.pdfview.pagecache", "hits: " + hits + ", misses: " + misses + ", hit ratio: " + (float)(hits) / (float)(hits+misses) + ", size: " + this.bitmaps.size()); } return b; } /** * Put rendered tile in cache. * @param tile tile definition (page, position etc), cache key * @param bitmap rendered tile contents, cache value */ synchronized void put(Tile tile, Bitmap bitmap) { while (this.willExceedCacheSize(bitmap) && !this.bitmaps.isEmpty()) { Log.v(TAG, "Removing oldest"); this.removeOldest(); } this.bitmaps.put(tile, new BitmapCacheValue(bitmap, System.currentTimeMillis(), 0)); } /** * Check if cache contains specified bitmap tile. Doesn't update last-used timestamp. * @return true if cache contains specified bitmap tile */ synchronized boolean contains(Tile tile) { return this.bitmaps.containsKey(tile); } /** * Estimate bitmap memory size. * This is just a guess. */ private static int getBitmapSizeInCache(Bitmap bitmap) { int numPixels = bitmap.getWidth() * bitmap.getHeight(); if (bitmap.getConfig() == Bitmap.Config.RGB_565) { return numPixels * 2; } else if (bitmap.getConfig() == Bitmap.Config.ALPHA_8) return numPixels; else return numPixels * 4; } /** * Get estimated sum of byte sizes of bitmaps stored in cache currently. */ private synchronized int getCurrentCacheSize() { int size = 0; Iterator<BitmapCacheValue> it = this.bitmaps.values().iterator(); while(it.hasNext()) { BitmapCacheValue bcv = it.next(); Bitmap bitmap = bcv.bitmap; size += getBitmapSizeInCache(bitmap); } Log.v(TAG, "Cache size: "+size); return size; } /** * Determine if adding this bitmap would grow cache size beyond max size. */ private synchronized boolean willExceedCacheSize(Bitmap bitmap) { return (this.getCurrentCacheSize() + BitmapCache.getBitmapSizeInCache(bitmap) > maxCacheSizeBytes); } /** * Remove oldest bitmap cache value. */ private void removeOldest() { Iterator<Tile> i = this.bitmaps.keySet().iterator(); long minmillis = 0; Tile oldest = null; while(i.hasNext()) { Tile k = i.next(); BitmapCacheValue v = this.bitmaps.get(k); if (oldest == null) { oldest = k; minmillis = v.millisAccessed; } else { if (minmillis > v.millisAccessed) { minmillis = v.millisAccessed; oldest = k; } } } if (oldest == null) throw new RuntimeException("couldnt find oldest"); BitmapCacheValue v = this.bitmaps.get(oldest); v.bitmap.recycle(); this.bitmaps.remove(oldest); } synchronized public void clearCache() { Iterator<Tile> i = this.bitmaps.keySet().iterator(); while(i.hasNext()) { Tile k = i.next(); Log.v("Deleting", k.toString()); this.bitmaps.get(k).bitmap.recycle(); i.remove(); } } } private static class RendererWorker implements Runnable { /** * Worker stops rendering if error was encountered. */ private boolean isFailed = false; private PDFPagesProvider pdfPagesProvider; private BitmapCache bitmapCache; private Collection<Tile> tiles; /** * Internal worker number for debugging. */ private static int workerThreadId = 0; /** * Used as a synchronized flag. * If null, then there's no designated thread to render tiles. * There might be other worker threads running, but those have finished * their work and will finish really soon. * Only this one should pick up new jobs. */ private Thread workerThread = null; /** * Create renderer worker. * @param pdfPagesProvider parent pages provider */ RendererWorker(PDFPagesProvider pdfPagesProvider) { this.tiles = null; this.pdfPagesProvider = pdfPagesProvider; } /** * Called by outside world to provide more work for worker. * This also starts rendering thread if one is needed. * @param tiles a collection of tile objects, they carry information about what should be rendered next */ synchronized void setTiles(Collection<Tile> tiles, BitmapCache bitmapCache) { this.tiles = tiles; this.bitmapCache = bitmapCache; if (this.workerThread == null) { Thread t = new Thread(this); t.setPriority(Thread.MIN_PRIORITY); t.setName("RendererWorkerThread#" + RendererWorker.workerThreadId++); this.workerThread = t; t.start(); Log.d(TAG, "started new worker thread"); } else { //Log.i(TAG, "setTiles notices tiles is not empty, that means RendererWorkerThread exists and there's no need to start new one"); } } /** * Get tiles that should be rendered next. May not block. * Also sets this.workerThread to null if there's no tiles to be rendered currently, * so that calling thread may finish. * If there are more tiles to be rendered, then this.workerThread is not reset. * @return some tiles */ synchronized Collection<Tile> popTiles() { if (this.tiles == null || this.tiles.isEmpty()) { this.workerThread = null; /* returning null, so calling thread will finish it's work */ return null; } Tile tile = this.tiles.iterator().next(); this.tiles.remove(tile); return Collections.singleton(tile); } /** * Thread's main routine. * There might be more than one running, but only one will get new tiles. Others * will get null returned by this.popTiles and will finish their work. */ public void run() { while(true) { if (this.isFailed) { Log.i(TAG, "RendererWorker is failed, exiting"); break; } Collection<Tile> tiles = this.popTiles(); /* this can't block */ if (tiles == null || tiles.size() == 0) break; try { Map<Tile,Bitmap> renderedTiles = this.pdfPagesProvider.renderTiles(tiles, bitmapCache); if (renderedTiles.size() > 0) this.pdfPagesProvider.publishBitmaps(renderedTiles); } catch (RenderingException e) { this.isFailed = true; this.pdfPagesProvider.publishRenderingException(e); } } } } private PDF pdf = null; private BitmapCache bitmapCache = null; private RendererWorker rendererWorker = null; private OnImageRenderedListener onImageRendererListener = null; public float getRenderAhead() { return this.renderAhead; } public PDFPagesProvider(Activity activity, PDF pdf, boolean gray, boolean skipImages, boolean doRenderAhead) { this.gray = gray; this.pdf = pdf; this.omitImages = skipImages; this.bitmapCache = new BitmapCache(); this.rendererWorker = new RendererWorker(this); this.activity = activity; this.doRenderAhead = doRenderAhead; setMaxCacheSize(); } public void setRenderAhead(boolean doRenderAhead) { this.doRenderAhead = doRenderAhead; setMaxCacheSize(); } /** * Render tiles. * Called by worker, calls PDF's methods that in turn call native code. * @param tiles job description - what to render * @return mapping of jobs and job results, with job results being Bitmap objects */ private Map<Tile,Bitmap> renderTiles(Collection<Tile> tiles, BitmapCache ignore) throws RenderingException { Map<Tile,Bitmap> renderedTiles = new HashMap<Tile,Bitmap>(); Iterator<Tile> i = tiles.iterator(); Tile tile = null; while(i.hasNext()) { tile = i.next(); Bitmap bitmap = this.renderBitmap(tile); if (bitmap != null) renderedTiles.put(tile, bitmap); } return renderedTiles; } /** * Really render bitmap. Takes time, should be done in background thread. Calls native code (through PDF object). */ private Bitmap renderBitmap(Tile tile) throws RenderingException { synchronized(tile) { /* last minute check to make sure some other thread hasn't rendered this tile */ if (this.bitmapCache.contains(tile)) return null; PDF.Size size = new PDF.Size(tile.getPrefXSize(), tile.getPrefYSize()); int[] pagebytes = null; long t1 =SystemClock.currentThreadTimeMillis(); pagebytes = pdf.renderPage(tile.getPage(), tile.getZoom(), tile.getX(), tile.getY(), tile.getRotation(), gray, omitImages, size); /* native */ Log.v(TAG, "Time:"+(SystemClock.currentThreadTimeMillis()-t1)); if (pagebytes == null) throw new RenderingException("Couldn't render page " + tile.getPage()); /* create a bitmap from the 32-bit color array */ if (gray) { Bitmap b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.ARGB_8888); Bitmap b2 = b.copy(Bitmap.Config.ALPHA_8, false); b.recycle(); this.bitmapCache.put(tile, b2); return b2; } else { Bitmap b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.RGB_565); this.bitmapCache.put(tile, b); return b; } } } /** * Called by worker. */ private void publishBitmaps(Map<Tile,Bitmap> renderedTiles) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onImagesRendered(renderedTiles); } else { Log.w(TAG, "we've got new bitmaps, but there's no one to notify about it!"); } } /** * Called by worker. */ private void publishRenderingException(RenderingException e) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onRenderingException(e); } } @Override public void setOnImageRenderedListener(OnImageRenderedListener l) { this.onImageRendererListener = l; } /** * Get tile bitmap if it's already rendered. * @param tile which bitmap * @return rendered tile; tile represents rect of TILE_SIZE x TILE_SIZE pixels, * but might be of different size (should be scaled when painting) */ @Override public Bitmap getPageBitmap(Tile tile) { Bitmap b = null; b = this.bitmapCache.get(tile); if (b != null) return b; return null; } /** * Get page count. * @return number of pages */ @Override public int getPageCount() { int c = this.pdf.getPageCount(); if (c <= 0) throw new RuntimeException("failed to load pdf file: getPageCount returned " + c); return c; } /** * Get page sizes from pdf file. * @return array of page sizes */ @Override public int[][] getPageSizes() { int cnt = this.getPageCount(); int[][] sizes = new int[cnt][]; PDF.Size size = new PDF.Size(); int err; for(int i = 0; i < cnt; ++i) { err = this.pdf.getPageSize(i, size); if (err != 0) { throw new RuntimeException("failed to getPageSize(" + i + ",...), error: " + err); } sizes[i] = new int[2]; sizes[i][0] = size.width; sizes[i][1] = size.height; } return sizes; } /** * View informs provider what's currently visible. * Compute what should be rendered and pass that info to renderer worker thread, possibly waking up worker. * @param tiles specs of whats currently visible */ synchronized public void setVisibleTiles(Collection<Tile> tiles) { List<Tile> newtiles = null; for(Tile tile: tiles) { if (!this.bitmapCache.contains(tile)) { if (newtiles == null) newtiles = new LinkedList<Tile>(); newtiles.add(tile); } } if (newtiles != null) { this.rendererWorker.setTiles(newtiles, this.bitmapCache); } } }
zzyangming-szyangming
pdfview/src/cx/hell/android/pdfview/PDFPagesProvider.java
Java
gpl3
15,785
package cx.hell.android.lib.pagesview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.graphics.Rect; import android.util.Log; /** * Find result. */ public class FindResult { /** * Logging tag. */ public static final String TAG = "cx.hell.android.pdfview"; /** * Page number. */ public int page; /** * List of rects that mark find result occurences. * In page dimensions (not scalled). */ public List<Rect> markers; /** * Add marker. */ public void addMarker(int x0, int y0, int x1, int y1) { if (x0 >= x1) throw new IllegalArgumentException("x0 must be smaller than x1: " + x0 + ", " + x1); if (y0 >= y1) throw new IllegalArgumentException("y0 must be smaller than y1: " + y0 + ", " + y1); if (this.markers == null) this.markers = new ArrayList<Rect>(); Rect nr = new Rect(x0, y0, x1, y1); if (this.markers.isEmpty()) { this.markers.add(nr); } else { this.markers.get(0).union(nr); } } public String toString() { StringBuilder b = new StringBuilder(); b.append("FindResult("); if (this.markers == null || this.markers.isEmpty()) { b.append("no markers"); } else { Iterator<Rect> i = this.markers.iterator(); Rect r = null; while(i.hasNext()) { r = i.next(); b.append(r); if (i.hasNext()) b.append(", "); } } b.append(")"); return b.toString(); } public void finalize() { Log.i(TAG, this + ".finalize()"); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/FindResult.java
Java
gpl3
1,538
package cx.hell.android.lib.pagesview; /** * Tile definition. * Can be used as a key in maps (hashable, comparable). */ public class Tile { /** * X position of tile in pixels. */ private int x; /** * Y position of tile in pixels. */ private int y; private int zoom; private int page; private int rotation; private int prefXSize; private int prefYSize; int _hashCode; public Tile(int page, int zoom, int x, int y, int rotation, int prefXSize, int prefYSize) { this.prefXSize = prefXSize; this.prefYSize = prefYSize; this.page = page; this.zoom = zoom; this.x = x; this.y = y; this.rotation = rotation; } public String toString() { return "Tile(" + this.page + ", " + this.zoom + ", " + this.x + ", " + this.y + ", " + this.rotation + ")"; } @Override public int hashCode() { return this._hashCode; } @Override public boolean equals(Object o) { if (! (o instanceof Tile)) return false; Tile t = (Tile) o; return ( this._hashCode == t._hashCode && this.page == t.page && this.zoom == t.zoom && this.x == t.x && this.y == t.y && this.rotation == t.rotation ); } public int getPage() { return this.page; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZoom() { return this.zoom; } public int getRotation() { return this.rotation; } public int getPrefXSize() { return this.prefXSize; } public int getPrefYSize() { return this.prefYSize; } }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/Tile.java
Java
gpl3
1,632
package cx.hell.android.lib.pagesview; public class RenderingException extends Exception { private static final long serialVersionUID = 1010978161527539002L; public RenderingException(String message) { super(message); } }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/RenderingException.java
Java
gpl3
239
package cx.hell.android.lib.pagesview; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import cx.hell.android.pdfview.Bookmark; import cx.hell.android.pdfview.BookmarkEntry; import cx.hell.android.pdfview.Options; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnDoubleTapListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.Scroller; /** * View that simplifies displaying of paged documents. * TODO: redesign zooms, pages, margins, layout * TODO: use more floats for better align, or use more ints for performance ;) (that is, really analyse what should be used when) */ public class PagesView extends View implements View.OnTouchListener, OnImageRenderedListener, View.OnKeyListener { /** * Logging tag. */ private static final String TAG = "cx.hell.android.pdfview"; /* Experiments show that larger tiles are faster, but the gains do drop off, * and must be balanced against the size of memory chunks being requested. */ private static final int MIN_TILE_WIDTH = 256; private static final int MAX_TILE_WIDTH = 640; private static final int MIN_TILE_HEIGHT = 128; private static final int MAX_TILE_PIXELS = 640*360; // private final static int MAX_ZOOM = 4000; // private final static int MIN_ZOOM = 100; /** * Space between screen edge and page and between pages. */ private int MARGIN_X = 0; private static final int MARGIN_Y = 10; /* zoom steps */ float step = 1.414f; /* volume keys page */ boolean pageWithVolume = true; private Activity activity = null; /** * Source of page bitmaps. */ private PagesProvider pagesProvider = null; @SuppressWarnings("unused") private long lastControlsUseMillis = 0; private int colorMode; private float maxRealPageSize[] = {0f, 0f}; private float realDocumentSize[] = {0f, 0f}; /** * Current width of this view. */ private int width = 0; /** * Current height of this view. */ private int height = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int left = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int top = 0; /** * Current zoom level. * 1000 is 100%. */ private int zoomLevel = 1000; /** * Current rotation of pages. */ private int rotation = 0; /** * Base scaling factor - how much shrink (or grow) page to fit it nicely to screen at zoomLevel = 1000. * For example, if we determine that 200x400 image fits screen best, but PDF's pages are 400x800, then * base scaling would be 0.5, since at base scaling, without any zoom, page should fit into screen nicely. */ private float scaling0 = 0f; /** * Page sized obtained from pages provider. * These do not change. */ private int pageSizes[][]; /** * Find mode. */ private boolean findMode = false; /** * Paint used to draw find results. */ private Paint findResultsPaint = null; /** * Currently displayed find results. */ private List<FindResult> findResults = null; /** * hold the currently displayed page */ private int currentPage = 0; /** * avoid too much allocations in rectsintersect() */ private static Rect r1 = new Rect(); /** * Bookmarked page to go to. */ private BookmarkEntry bookmarkToRestore = null; /** * Construct this view. * @param activity parent activity */ private boolean volumeUpIsDown = false; private boolean volumeDownIsDown = false; private GestureDetector gestureDetector = null; private Scroller scroller = null; private boolean verticalScrollLock = true; private boolean lockedVertically = false; private float downX = 0; private float downY = 0; private float lastX = 0; private float lastY = 0; private float maxExcursionY = 0; public PagesView(Activity activity) { super(activity); this.activity = activity; this.lastControlsUseMillis = System.currentTimeMillis(); this.findResultsPaint = new Paint(); this.findResultsPaint.setARGB(0xd0, 0xc0, 0, 0); this.findResultsPaint.setStyle(Paint.Style.FILL); this.findResultsPaint.setAntiAlias(true); this.findResultsPaint.setStrokeWidth(3); this.setOnTouchListener(this); this.setOnKeyListener(this); activity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); this.scroller = null; // new Scroller(activity); this.gestureDetector = new GestureDetector(activity, new GestureDetector.OnGestureListener() { public boolean onDown(MotionEvent e) { return false; } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (lockedVertically) velocityX = 0; doFling(velocityX, velocityY); return true; } public void onLongPress(MotionEvent e) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void onShowPress(MotionEvent e) { } public boolean onSingleTapUp(MotionEvent e) { return false; } }); gestureDetector.setOnDoubleTapListener(new OnDoubleTapListener() { public boolean onDoubleTap(MotionEvent e) { left += e.getX() - width/2; top += e.getY() - height/2; invalidate(); zoomUpBig(); return false; } public boolean onDoubleTapEvent(MotionEvent e) { return false; } public boolean onSingleTapConfirmed(MotionEvent e) { return false; }}); } public void setStartBookmark(Bookmark b, String bookmarkName) { if (b != null) { this.bookmarkToRestore = b.getLast(bookmarkName); if (this.bookmarkToRestore == null) return; if (this.bookmarkToRestore.numberOfPages != this.pageSizes.length) { this.bookmarkToRestore = null; return; } if (0<this.bookmarkToRestore.page) { this.currentPage = this.bookmarkToRestore.page; } } } /** * Handle size change event. * Update base scaling, move zoom controls to correct place etc. * @param w new width * @param h new height * @param oldw old width * @param oldh old height */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.width = w; this.height = h; if (this.scaling0 == 0f) { this.scaling0 = Math.min( ((float)this.height - 2*MARGIN_Y) / (float)this.pageSizes[0][1], ((float)this.width - 2*MARGIN_X) / (float)this.pageSizes[0][0]); } if (oldw == 0 && oldh == 0) { goToBookmark(); } } public void goToBookmark() { if (this.bookmarkToRestore == null) { this.top = this.height / 2; this.left = this.width / 2; } else { this.zoomLevel = (int)(this.bookmarkToRestore.absoluteZoomLevel / this.scaling0); this.rotation = this.bookmarkToRestore.rotation; Point pos = getPagePositionInDocumentWithZoom(this.bookmarkToRestore.page); this.currentPage = this.bookmarkToRestore.page; this.top = pos.y + this.height / 2; this.left = this.getCurrentPageWidth(this.currentPage)/2 + MARGIN_X + this.bookmarkToRestore.offsetX; this.bookmarkToRestore = null; } } public void setPagesProvider(PagesProvider pagesProvider) { this.pagesProvider = pagesProvider; if (this.pagesProvider != null) { this.pageSizes = this.pagesProvider.getPageSizes(); maxRealPageSize[0] = 0f; maxRealPageSize[1] = 0f; realDocumentSize[0] = 0f; realDocumentSize[1] = 0f; for (int i = 0; i < this.pageSizes.length; i++) for (int j = 0; j<2; j++) { if (pageSizes[i][j] > maxRealPageSize[j]) maxRealPageSize[j] = pageSizes[i][j]; realDocumentSize[j] += pageSizes[i][j]; } if (this.width > 0 && this.height > 0) { this.scaling0 = Math.min( ((float)this.height - 2*MARGIN_Y) / (float)this.pageSizes[0][1], ((float)this.width - 2*MARGIN_X) / (float)this.pageSizes[0][0]); this.left = this.width / 2; this.top = this.height / 2; } } else { this.pageSizes = null; } this.pagesProvider.setOnImageRenderedListener(this); } /** * Draw view. * @param canvas what to draw on */ int prevTop = -1; int prevLeft = -1; public void onDraw(Canvas canvas) { this.drawPages(canvas); if (this.findMode) this.drawFindResults(canvas); } /** * Get current maximum page width by page number taking into account zoom and rotation */ private int getCurrentMaxPageWidth() { float realpagewidth = this.maxRealPageSize[this.rotation % 2 == 0 ? 0 : 1]; return (int)(realpagewidth * scaling0 * (this.zoomLevel*0.001f)); } /** * Get current maximum page height by page number taking into account zoom and rotation */ /* private int getCurrentMaxPageHeight() { float realpageheight = this.maxRealPageSize[this.rotation % 2 == 0 ? 1 : 0]; return (int)(realpageheight * scaling0 * (this.zoomLevel*0.001f)); } */ /** * Get current maximum page width by page number taking into account zoom and rotation */ private int getCurrentDocumentHeight() { float realheight = this.realDocumentSize[this.rotation % 2 == 0 ? 1 : 0]; /* we add pageSizes.length to account for round-off issues */ return (int)(realheight * scaling0 * (this.zoomLevel*0.001f) + (pageSizes.length - 1) * this.getCurrentMarginY()); } /** * Get current page width by page number taking into account zoom and rotation * @param pageno 0-based page number */ private int getCurrentPageWidth(int pageno) { float realpagewidth = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 0 : 1]; float currentpagewidth = realpagewidth * scaling0 * (this.zoomLevel*0.001f); return (int)currentpagewidth; } /** * Get current page height by page number taking into account zoom and rotation. * @param pageno 0-based page number */ private float getCurrentPageHeight(int pageno) { float realpageheight = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 1 : 0]; float currentpageheight = realpageheight * scaling0 * (this.zoomLevel*0.001f); return currentpageheight; } private float getCurrentMarginX() { return (float)MARGIN_X * this.zoomLevel * 0.001f; } private float getCurrentMarginY() { return (float)MARGIN_Y * this.zoomLevel * 0.001f; } /** * This takes into account zoom level. */ private Point getPagePositionInDocumentWithZoom(int page) { float marginX = this.getCurrentMarginX(); float marginY = this.getCurrentMarginY(); float left = marginX; float top = 0; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } top += (page+1) * marginY; return new Point((int)left, (int)top); } /** * Calculate screens (viewports) top-left corner position over document. */ private Point getScreenPositionOverDocument() { float top = this.top - this.height / 2; float left = this.left - this.width / 2; return new Point((int)left, (int)top); } /** * Calculate current page position on screen in pixels. * @param page base-0 page number */ private Point getPagePositionOnScreen(int page) { if (page < 0) throw new IllegalArgumentException("page must be >= 0: " + page); if (page >= this.pageSizes.length) throw new IllegalArgumentException("page number too big: " + page); Point pagePositionInDocument = this.getPagePositionInDocumentWithZoom(page); Point screenPositionInDocument = this.getScreenPositionOverDocument(); return new Point( pagePositionInDocument.x - screenPositionInDocument.x, pagePositionInDocument.y - screenPositionInDocument.y ); } @Override public void computeScroll() { if (this.scroller == null) return; if (this.scroller.computeScrollOffset()) { left = this.scroller.getCurrX(); top = this.scroller.getCurrY(); ((cx.hell.android.pdfview.OpenFileActivity)activity).showPageNumber(false); postInvalidate(); } } /** * Draw pages. * Also collect info what's visible and push this info to page renderer. */ private void drawPages(Canvas canvas) { Rect src = new Rect(); /* TODO: move out of drawPages */ Rect dst = new Rect(); /* TODO: move out of drawPages */ int pageWidth = 0; int pageHeight = 0; float pagex0, pagey0, pagex1, pagey1; // in doc, counts zoom int x, y; // on screen int viewx0, viewy0; // view over doc LinkedList<Tile> visibleTiles = new LinkedList<Tile>(); float currentMarginX = this.getCurrentMarginX(); float currentMarginY = this.getCurrentMarginY(); float renderAhead = this.pagesProvider.getRenderAhead(); if (this.pagesProvider != null) { viewx0 = left - width/2; viewy0 = top - height/2; int pageCount = this.pageSizes.length; /* We now adjust the position to make sure we don't scroll too * far away from the document text. */ int oldviewx0 = viewx0; int oldviewy0 = viewy0; viewx0 = adjustPosition(viewx0, width, (int)currentMarginX, getCurrentMaxPageWidth()); viewy0 = adjustPosition(viewy0, height, (int)currentMarginY, (int)getCurrentDocumentHeight()); left += viewx0 - oldviewx0; top += viewy0 - oldviewy0; float currpageoff = currentMarginY; this.currentPage = -1; pagey0 = 0; int[] tileSizes = new int[2]; for(int i = 0; i < pageCount; ++i) { // is page i visible? pageWidth = this.getCurrentPageWidth(i); pageHeight = (int) this.getCurrentPageHeight(i); pagex0 = currentMarginX; pagex1 = (int)(currentMarginX + pageWidth); pagey0 = currpageoff; pagey1 = (int)(currpageoff + pageHeight); if (rectsintersect( (int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc viewx0, viewy0, viewx0 + this.width, viewy0 + (int)(renderAhead*this.height) // viewport rect in doc, or close enough to it )) { if (this.currentPage == -1) { // remember the currently displayed page this.currentPage = i; } x = (int)pagex0 - viewx0; y = (int)pagey0 - viewy0; getGoodTileSizes(tileSizes, pageWidth, pageHeight); for(int tileix = 0; tileix < (pageWidth + tileSizes[0]-1) / tileSizes[0]; ++tileix) for(int tileiy = 0; tileiy < (pageHeight + tileSizes[1]-1) / tileSizes[1]; ++tileiy) { dst.left = (int)(x + tileix*tileSizes[0]); dst.top = (int)(y + tileiy*tileSizes[1]); dst.right = dst.left + tileSizes[0]; dst.bottom = dst.top + tileSizes[1]; if (dst.intersects(0, 0, this.width, (int)(renderAhead*this.height))) { Tile tile = new Tile(i, (int)(this.zoomLevel * scaling0), tileix*tileSizes[0], tileiy*tileSizes[1], this.rotation, tileSizes[0], tileSizes[1]); if (dst.intersects(0, 0, this.width, this.height)) { Bitmap b = this.pagesProvider.getPageBitmap(tile); if (b != null) { //Log.d(TAG, " have bitmap: " + b + ", size: " + b.getWidth() + " x " + b.getHeight()); src.left = 0; src.top = 0; src.right = b.getWidth(); src.bottom = b.getHeight(); if (dst.right > x + pageWidth) { src.right = (int)(b.getWidth() * (float)((x+pageWidth)-dst.left) / (float)(dst.right - dst.left)); dst.right = (int)(x + pageWidth); } if (dst.bottom > y + pageHeight) { src.bottom = (int)(b.getHeight() * (float)((y+pageHeight)-dst.top) / (float)(dst.bottom - dst.top)); dst.bottom = (int)(y + pageHeight); } drawBitmap(canvas, b, src, dst); } } visibleTiles.add(tile); } } } /* move to next page */ currpageoff += currentMarginY + this.getCurrentPageHeight(i); } this.pagesProvider.setVisibleTiles(visibleTiles); } } private void drawBitmap(Canvas canvas, Bitmap b, Rect src, Rect dst) { if (colorMode != Options.COLOR_MODE_NORMAL) { Paint paint = new Paint(); Bitmap out; if (b.getConfig() == Bitmap.Config.ALPHA_8) { out = b.copy(Bitmap.Config.ARGB_8888, false); } else { out = b; } paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix( Options.getColorModeMatrix(this.colorMode)))); canvas.drawBitmap(out, src, dst, paint); if (b.getConfig() == Bitmap.Config.ALPHA_8) { out.recycle(); } } else { canvas.drawBitmap(b, src, dst, null); } } /** * Draw find results. * TODO prettier icons * TODO message if nothing was found * @param canvas drawing target */ private void drawFindResults(Canvas canvas) { if (!this.findMode) throw new RuntimeException("drawFindResults but not in find results mode"); if (this.findResults == null || this.findResults.isEmpty()) { Log.w(TAG, "nothing found"); return; } for(FindResult findResult: this.findResults) { if (findResult.markers == null || findResult.markers.isEmpty()) throw new RuntimeException("illegal FindResult: find result must have at least one marker"); Iterator<Rect> i = findResult.markers.iterator(); Rect r = null; Point pagePosition = this.getPagePositionOnScreen(findResult.page); float pagex = pagePosition.x; float pagey = pagePosition.y; float z = (this.scaling0 * (float)this.zoomLevel * 0.001f); while(i.hasNext()) { r = i.next(); canvas.drawLine( r.left * z + pagex, r.top * z + pagey, r.left * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.left * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.right * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.top * z + pagey, this.findResultsPaint); // canvas.drawRect( // r.left * z + pagex, // r.top * z + pagey, // r.right * z + pagex, // r.bottom * z + pagey, // this.findResultsPaint); // Log.d(TAG, "marker lands on: " + // (r.left * z + pagex) + ", " + // (r.top * z + pagey) + ", " + // (r.right * z + pagex) + ", " + // (r.bottom * z + pagey) + ", "); } } } private boolean unlocksVerticalLock(MotionEvent e) { float dx; float dy; dx = Math.abs(e.getX()-downX); dy = Math.abs(e.getY()-downY); if (dy > 0.25 * dx || maxExcursionY > 0.8 * dx) return false; return dx > width/5 || dx > height/5; } /** * Handle touch event coming from Android system. */ public boolean onTouch(View v, MotionEvent event) { this.lastControlsUseMillis = System.currentTimeMillis(); if (!gestureDetector.onTouchEvent(event)) { if (event.getAction() == MotionEvent.ACTION_DOWN) { downX = event.getX(); downY = event.getY(); lastX = downX; lastY = downY; lockedVertically = verticalScrollLock; maxExcursionY = 0; scroller = null; } else if (event.getAction() == MotionEvent.ACTION_MOVE){ if (lockedVertically && unlocksVerticalLock(event)) lockedVertically = false; float dx = event.getX() - lastX; float dy = event.getY() - lastY; float excursionY = Math.abs(event.getY() - downY); if (excursionY > maxExcursionY) maxExcursionY = excursionY; if (lockedVertically) dx = 0; doScroll((int)-dx, (int)-dy); lastX = event.getX(); lastY = event.getY(); } } return true; } /** * Handle keyboard events */ public boolean onKey(View v, int keyCode, KeyEvent event) { if (this.pageWithVolume && event.getAction() == KeyEvent.ACTION_UP) { /* repeat is a little too fast sometimes, so trap these on up */ switch(keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: volumeUpIsDown = false; return true; case KeyEvent.KEYCODE_VOLUME_DOWN: volumeDownIsDown = false; return true; } } if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_SEARCH: ((cx.hell.android.pdfview.OpenFileActivity)activity).showFindDialog(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: if (!this.pageWithVolume) return false; if (!volumeDownIsDown) { /* Disable key repeat as on some devices the keys are a little too * sticky for key repeat to work well. TODO: Maybe key repeat disabling * should be an option? */ this.top += this.getHeight() - 16; this.invalidate(); } volumeDownIsDown = true; return true; case KeyEvent.KEYCODE_VOLUME_UP: if (!this.pageWithVolume) return false; if (!volumeUpIsDown) { this.top -= this.getHeight() - 16; this.invalidate(); } volumeUpIsDown = true; return true; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_K: this.top -= this.getHeight() - 16; this.invalidate(); return true; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_J: this.top += this.getHeight() - 16; this.invalidate(); return true; case KeyEvent.KEYCODE_H: this.left -= this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_L: this.left += this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_DPAD_LEFT: scrollToPage(currentPage - 1); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: scrollToPage(currentPage + 1); return true; case KeyEvent.KEYCODE_O: this.zoomLevel /= 1.1f; this.left /= 1.1f; this.top /= 1.1f; this.invalidate(); return true; case KeyEvent.KEYCODE_P: this.zoomLevel *= 1.1f; this.left *= 1.1f; this.top *= 1.1f; this.invalidate(); return true; } } return false; } /** * Test if specified rectangles intersect with each other. * Uses Androids standard Rect class. */ private static boolean rectsintersect( int r1x0, int r1y0, int r1x1, int r1y1, int r2x0, int r2y0, int r2x1, int r2y1) { r1.set(r1x0, r1y0, r1x1, r1y1); return r1.intersects(r2x0, r2y0, r2x1, r2y1); } /** * Used as a callback from pdf rendering code. * TODO: only invalidate what needs to be painted, not the whole view */ public void onImagesRendered(Map<Tile,Bitmap> renderedTiles) { Rect rect = new Rect(); /* TODO: move out of onImagesRendered */ int viewx0 = left - width/2; int viewy0 = top - height/2; int pageCount = this.pageSizes.length; float currentMarginX = this.getCurrentMarginX(); float currentMarginY = this.getCurrentMarginY(); viewx0 = adjustPosition(viewx0, width, (int)currentMarginX, getCurrentMaxPageWidth()); viewy0 = adjustPosition(viewy0, height, (int)currentMarginY, (int)getCurrentDocumentHeight()); float currpageoff = currentMarginY; float renderAhead = this.pagesProvider.getRenderAhead(); float pagex0; float pagex1; float pagey0 = 0; float pagey1; float x; float y; int pageWidth; int pageHeight; for(int i = 0; i < pageCount; ++i) { // is page i visible? pageWidth = this.getCurrentPageWidth(i); pageHeight = (int) this.getCurrentPageHeight(i); pagex0 = currentMarginX; pagex1 = (int)(currentMarginX + pageWidth); pagey0 = currpageoff; pagey1 = (int)(currpageoff + pageHeight); if (rectsintersect( (int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc viewx0, viewy0, viewx0 + this.width, viewy0 + this.height )) { x = pagex0 - viewx0; y = pagey0 - viewy0; for (Tile tile: renderedTiles.keySet()) { if (tile.getPage() == i) { Bitmap b = renderedTiles.get(tile); rect.left = (int)(x + tile.getX()); rect.top = (int)(y + tile.getY()); rect.right = rect.left + b.getWidth(); rect.bottom = rect.top + b.getHeight(); if (rect.intersects(0, 0, this.width, (int)(renderAhead*this.height))) { Log.v(TAG, "New bitmap forces redraw"); postInvalidate(); return; } } } } currpageoff += currentMarginY + this.getCurrentPageHeight(i); } Log.v(TAG, "New bitmap does not require redraw"); } /** * Handle rendering exception. * Show error message and then quit parent activity. * TODO: find a proper way to finish an activity when something bad happens in view. */ public void onRenderingException(RenderingException reason) { final Activity activity = this.activity; final String message = reason.getMessage(); this.post(new Runnable() { public void run() { AlertDialog errorMessageDialog = new AlertDialog.Builder(activity) .setTitle("Error") .setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { activity.finish(); } }) .create(); errorMessageDialog.show(); } }); } /** * Move current viewport over n-th page. * Page is 0-based. * @param page 0-based page number */ synchronized public void scrollToPage(int page) { this.left = this.width / 2; float top = this.height / 2; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } if (page > 0) top += (float)MARGIN_Y * this.zoomLevel * 0.001f * (float)(page); this.top = (int)top; this.currentPage = page; this.invalidate(); } // /** // * Compute what's currently visible. // * @return collection of tiles that define what's currently visible // */ // private Collection<Tile> computeVisibleTiles() { // LinkedList<Tile> tiles = new LinkedList<Tile>(); // float viewx = this.left + (this.dragx1 - this.dragx); // float viewy = this.top + (this.dragy1 - this.dragy); // float pagex = MARGIN; // float pagey = MARGIN; // float pageWidth; // float pageHeight; // int tileix; // int tileiy; // int thisPageTileCountX; // int thisPageTileCountY; // float tilex; // float tiley; // for(int page = 0; page < this.pageSizes.length; ++page) { // // pageWidth = this.getCurrentPageWidth(page); // pageHeight = this.getCurrentPageHeight(page); // // thisPageTileCountX = (int)Math.ceil(pageWidth / TILE_SIZE); // thisPageTileCountY = (int)Math.ceil(pageHeight / TILE_SIZE); // // if (viewy + this.height < pagey) continue; /* before first visible page */ // if (viewx > pagey + pageHeight) break; /* after last page */ // // for(tileix = 0; tileix < thisPageTileCountX; ++tileix) { // for(tileiy = 0; tileiy < thisPageTileCountY; ++tileiy) { // tilex = pagex + tileix * TILE_SIZE; // tiley = pagey + tileiy * TILE_SIZE; // if (rectsintersect(viewx, viewy, viewx+this.width, viewy+this.height, // tilex, tiley, tilex+TILE_SIZE, tiley+TILE_SIZE)) { // tiles.add(new Tile(page, this.zoomLevel, (int)tilex, (int)tiley, this.rotation)); // } // } // } // // /* move to next page */ // pagey += this.getCurrentPageHeight(page) + MARGIN; // } // return tiles; // } // synchronized Collection<Tile> getVisibleTiles() { // return this.visibleTiles; // } /** * Rotate pages. * Updates rotation variable, then invalidates view. * @param rotation rotation */ synchronized public void rotate(int rotation) { this.rotation = (this.rotation + rotation) % 4; this.invalidate(); } /** * Set find mode. * @param m true if pages view should display find results and find controls */ synchronized public void setFindMode(boolean m) { if (this.findMode != m) { this.findMode = m; if (!m) { this.findResults = null; } } } /** * Return find mode. * @return find mode - true if view is currently in find mode */ public boolean getFindMode() { return this.findMode; } // /** // * Ask pages provider to focus on next find result. // * @param forward direction of search - true for forward, false for backward // */ // public void findNext(boolean forward) { // this.pagesProvider.findNext(forward); // this.scrollToFindResult(); // this.invalidate(); // } /** * Move viewport position to find result (if any). * Does not call invalidate(). */ public void scrollToFindResult(int n) { if (this.findResults == null || this.findResults.isEmpty()) return; Rect center = new Rect(); FindResult findResult = this.findResults.get(n); for(Rect marker: findResult.markers) { center.union(marker); } int page = findResult.page; int x = 0; int y = 0; for(int p = 0; p < page; ++p) { Log.d(TAG, "adding page " + p + " to y: " + this.pageSizes[p][1]); y += this.pageSizes[p][1]; } x += (center.left + center.right) / 2; y += (center.top + center.bottom) / 2; float marginX = this.getCurrentMarginX(); float marginY = this.getCurrentMarginX(); this.left = (int)(x * scaling0 * this.zoomLevel * 0.001f + marginX); this.top = (int)(y * scaling0 * this.zoomLevel * 0.001f + (page+1)*marginY); } /** * Get the current page number * * @return the current page. 0-based */ public int getCurrentPage() { return currentPage; } /** * Get the current zoom level * * @return the current zoom level */ public int getCurrentAbsoluteZoom() { return zoomLevel; } /** * Get the current rotation * * @return the current rotation */ public int getRotation() { return rotation; } /** * Get page count. */ public int getPageCount() { return this.pageSizes.length; } /** * Set find results. */ public void setFindResults(List<FindResult> results) { this.findResults = results; } /** * Get current find results. */ public List<FindResult> getFindResults() { return this.findResults; } private void doFling(float vx, float vy) { float avx = vx > 0 ? vx : -vx; float avy = vy > 0 ? vy : -vy; if (avx < .25 * avy) { vx = 0; } else if (avy < .25 * avx) { vy = 0; } int marginX = (int)getCurrentMarginX(); int marginY = (int)getCurrentMarginY(); int minx = this.width/2 + getLowerBound(this.width, marginX, getCurrentMaxPageWidth()); int maxx = this.width/2 + getUpperBound(this.width, marginX, getCurrentMaxPageWidth()); int miny = this.height/2 + getLowerBound(this.width, marginY, getCurrentDocumentHeight()); int maxy = this.height/2 + getUpperBound(this.width, marginY, getCurrentDocumentHeight()); this.scroller = new Scroller(activity); this.scroller.fling(this.left, this.top, (int)-vx, (int)-vy, minx, maxx, miny, maxy); invalidate(); } private void doScroll(int dx, int dy) { this.left += dx; this.top += dy; invalidate(); } /** * Zoom down one level */ public void zoomDown() { this.zoomLevel /= step; this.left /= step; this.top /= step; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /** * Zoom down big */ public void zoomDownBig() { this.zoomLevel /= 2; this.left /= 2; this.top /= 2; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /** * Zoom up one level */ public void zoomUp() { this.zoomLevel *= step; this.left *= step; this.top *= step; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /** * Zoom up big level */ public void zoomUpBig() { this.zoomLevel *= 2; this.left *= 2; this.top *= 2; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /* zoom to width */ public void zoomWidth() { int page = currentPage < 0 ? 0 : currentPage; int pageWidth = getCurrentPageWidth(page); this.top = (this.top - this.height / 2) * this.width / pageWidth + this.height / 2; this.zoomLevel = this.zoomLevel * (this.width - 2*MARGIN_X) / pageWidth; this.left = (int) (this.width/2); this.invalidate(); } /* zoom to fit */ public void zoomFit() { int page = currentPage < 0 ? 0 : currentPage; int z1 = this.zoomLevel * this.width / getCurrentPageWidth(page); int z2 = (int)(this.zoomLevel * this.height / getCurrentPageHeight(page)); this.zoomLevel = z2 < z1 ? z2 : z1; Point pos = getPagePositionInDocumentWithZoom(page); this.left = this.width/2 + pos.x; this.top = this.height/2 + pos.y; this.invalidate(); } /** * Set zoom */ public void setZoomLevel(int zoomLevel) { if (this.zoomLevel == zoomLevel) return; this.zoomLevel = zoomLevel; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /** * Set rotation */ public void setRotation(int rotation) { if (this.rotation == rotation) return; this.rotation = rotation; Log.d(TAG, "rotation changed to " + this.rotation); this.invalidate(); } public void setVerticalScrollLock(boolean verticalScrollLock) { this.verticalScrollLock = verticalScrollLock; } public void setColorMode(int colorMode) { this.colorMode = colorMode; this.invalidate(); } public void setZoomIncrement(float step) { this.step = step; } public void setPageWithVolume(boolean pageWithVolume) { this.pageWithVolume = pageWithVolume; } private void getGoodTileSizes(int[] sizes, int pageWidth, int pageHeight) { sizes[0] = getGoodTileSize(pageWidth, MIN_TILE_WIDTH, MAX_TILE_WIDTH); sizes[1] = getGoodTileSize(pageHeight, MIN_TILE_HEIGHT, MAX_TILE_PIXELS / sizes[0]); } private int getGoodTileSize(int pageSize, int minSize, int maxSize) { if (pageSize <= 2) return 2; if (pageSize <= maxSize) return pageSize; int numInPageSize = (pageSize + maxSize - 1) / maxSize; int proposedSize = (pageSize + numInPageSize - 1) / numInPageSize; if (proposedSize < minSize) return minSize; else return proposedSize; } /* Get the upper and lower bounds for the viewpoint. The document itself is * drawn from margin to margin+docDim. */ private int getLowerBound(int screenDim, int margin, int docDim) { if (docDim <= screenDim) { /* all pages can and do fit */ return margin + docDim - screenDim; } else { /* document is too wide/tall to fit */ return 0; } } private int getUpperBound(int screenDim, int margin, int docDim) { if (docDim <= screenDim) { /* all pages can and do fit */ return margin; } else { /* document is too wide/tall to fit */ return 2 * margin + docDim - screenDim; } } private int adjustPosition(int pos, int screenDim, int margin, int docDim) { int min = getLowerBound(screenDim, margin, docDim); int max = getUpperBound(screenDim, margin, docDim); if (pos < min) return min; else if (max < pos) return max; else return pos; } public BookmarkEntry toBookmarkEntry() { return new BookmarkEntry(this.pageSizes.length, this.currentPage, scaling0*zoomLevel, rotation, this.left - this.getCurrentPageWidth(this.currentPage)/2 - MARGIN_X); } public void setSideMargins(Boolean sideMargins) { if (sideMargins) this.MARGIN_X = MARGIN_Y; else this.MARGIN_X = 0; } }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/PagesView.java
Java
gpl3
36,892
package cx.hell.android.lib.pagesview; import java.util.Map; import android.graphics.Bitmap; /** * Allow renderer to notify view that new bitmaps are ready. * Implemented by PagesView. */ public interface OnImageRenderedListener { void onImagesRendered(Map<Tile,Bitmap> renderedImages); void onRenderingException(RenderingException reason); }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/OnImageRenderedListener.java
Java
gpl3
365
package cx.hell.android.lib.pagesview; import java.util.Collection; import android.graphics.Bitmap; /** * Provide content of pages rendered by PagesView. */ public abstract class PagesProvider { /** * Get page image tile for drawing. */ public abstract Bitmap getPageBitmap(Tile tile); /** * Get page count. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int getPageCount(); /** * Get page sizes. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int[][] getPageSizes(); /** * Set notify target. * Usually page rendering takes some time. If image cannot be provided * immediately, provider may return null. * Then it's up to provider to notify view that requested image has arrived * and is ready to be drawn. * This function, if overridden, can be used to inform provider who * should be notifed. * Default implementation does nothing. */ public void setOnImageRenderedListener(OnImageRenderedListener listener) { /* to be overridden when needed */ } public abstract void setVisibleTiles(Collection<Tile> tiles); public abstract float getRenderAhead(); }
zzyangming-szyangming
pdfview/src/cx/hell/android/lib/pagesview/PagesProvider.java
Java
gpl3
1,310
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_CFLAGS := -O3 LOCAL_ARM_MODE := arm LOCAL_MODULE := openjpeg LOCAL_SRC_FILES := \ bio.c \ cio.c \ dwt.c \ event.c \ image.c \ j2k.c \ j2k_lib.c \ jp2.c \ jpt.c \ mct.c \ mqc.c \ openjpeg.c \ pi.c \ raw.c \ t1.c \ t1_generate_luts.c \ t2.c \ tcd.c \ tgt.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
zzyangming-szyangming
pdfview/jni/openjpeg/Android.mk
Makefile
gpl3
405
/* * This file registers the FreeType modules compiled into the library. * * If you use GNU make, this file IS NOT USED! Instead, it is created in * the objects directory (normally `<topdir>/objs/') based on information * from `<topdir>/modules.cfg'. * * Please read `docs/INSTALL.ANY' and `docs/CUSTOMIZE' how to compile * FreeType without GNU make. * */ FT_USE_MODULE( FT_Module_Class, autofit_module_class ) FT_USE_MODULE( FT_Driver_ClassRec, tt_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, t1_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, cff_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, t1cid_driver_class ) /* FT_USE_MODULE( FT_Driver_ClassRec, pfr_driver_class ) */ /* FT_USE_MODULE( FT_Driver_ClassRec, t42_driver_class ) */ /* FT_USE_MODULE( FT_Driver_ClassRec, winfnt_driver_class ) */ /* FT_USE_MODULE( FT_Driver_ClassRec, pcf_driver_class ) */ FT_USE_MODULE( FT_Module_Class, psaux_module_class ) FT_USE_MODULE( FT_Module_Class, psnames_module_class ) FT_USE_MODULE( FT_Module_Class, pshinter_module_class ) FT_USE_MODULE( FT_Renderer_Class, ft_raster1_renderer_class ) FT_USE_MODULE( FT_Module_Class, sfnt_module_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_renderer_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcd_renderer_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcdv_renderer_class ) /* FT_USE_MODULE( FT_Driver_ClassRec, bdf_driver_class ) */ /* EOF */
zzyangming-szyangming
pdfview/jni/freetype-overlay/include/freetype/config/ftmodule.h
C
gpl3
1,429
#ifdef PDFVIEW2_H__ #error PDFVIEW2_H__ can be included only once #endif #define PDFVIEW2_H__ #include "fitz.h" #include "mupdf.h" #define MAX_BOX_NAME 8 /** * Holds pdf info. */ typedef struct { int last_pageno; pdf_xref *xref; pdf_outline *outline; int fileno; /* used only when opening by file descriptor */ pdf_page **pages; /* lazy-loaded pages */ fz_glyph_cache *glyph_cache; char box[MAX_BOX_NAME + 1]; } pdf_t; /* * Declarations */ pdf_t* create_pdf_t(); pdf_t* parse_pdf_file(const char *filename, int fileno); pdf_t* get_pdf_from_this(JNIEnv *env, jobject this); void get_size(JNIEnv *env, jobject size, int *width, int *height); void save_size(JNIEnv *env, jobject size, int width, int height); void fix_samples(unsigned char *bytes, unsigned int w, unsigned int h); void rgb_to_alpha(unsigned char *bytes, unsigned int w, unsigned int h); int get_page_size(pdf_t *pdf, int pageno, int *width, int *height); void pdf_android_loghandler(const char *m); jobject create_find_result(JNIEnv *env); void set_find_result_page(JNIEnv *env, jobject findResult, int page); void add_find_result_marker(JNIEnv *env, jobject findResult, int x0, int y0, int x1, int y1); void add_find_result_to_list(JNIEnv *env, jobject *list, jobject find_result); int convert_point_pdf_to_apv(pdf_t *pdf, int page, int *x, int *y); int convert_box_pdf_to_apv(pdf_t *pdf, int page, fz_bbox *bbox); int find_next(JNIEnv *env, jobject this, int direction); pdf_page* get_page(pdf_t *pdf, int pageno);
zzyangming-szyangming
pdfview/jni/pdfview2/pdfview2.h
C
gpl3
1,521
#include <string.h> #include <wctype.h> #include <jni.h> #include "android/log.h" #include "pdfview2.h" #define PDFVIEW_LOG_TAG "cx.hell.android.pdfview" #define PDFVIEW_MAX_PAGES_LOADED 16 #define BITMAP_STORE_MAX_AGE 1 #define FIND_STORE_MAX_AGE 4 #define TEXT_STORE_MAX_AGE 4 static jintArray get_page_image_bitmap(JNIEnv *env, pdf_t *pdf, int pageno, int zoom_pmil, int left, int top, int rotation, int gray, int skipImages, int *width, int *height); static void copy_alpha(unsigned char* out, unsigned char *in, unsigned int w, unsigned int h); extern char fz_errorbuf[150*20]; /* defined in fitz/apv_base_error.c */ #define NUM_BOXES 5 const char boxes[NUM_BOXES][MAX_BOX_NAME+1] = { "ArtBox", "BleedBox", "CropBox", "MediaBox", "TrimBox" }; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { __android_log_print(ANDROID_LOG_INFO, PDFVIEW_LOG_TAG, "JNI_OnLoad"); fz_accelerate(); /* pdf_setloghandler(pdf_android_loghandler); */ return JNI_VERSION_1_2; } /** * Implementation of native method PDF.parseFile. * Opens file and parses at least some bytes - so it could take a while. * @param file_name file name to parse. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_parseFile( JNIEnv *env, jobject jthis, jstring file_name, jint box_type) { const char *c_file_name = NULL; jboolean iscopy; jclass this_class; jfieldID pdf_field_id; pdf_t *pdf = NULL; c_file_name = (*env)->GetStringUTFChars(env, file_name, &iscopy); this_class = (*env)->GetObjectClass(env, jthis); pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); pdf = parse_pdf_file(c_file_name, 0); if (NUM_BOXES <= box_type) strcpy(pdf->box, "CropBox"); else strcpy(pdf->box, boxes[box_type]); (*env)->ReleaseStringUTFChars(env, file_name, c_file_name); (*env)->SetIntField(env, jthis, pdf_field_id, (int)pdf); __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "Loading %s in page mode %s.", c_file_name, pdf->box); } /** * Create pdf_t struct from opened file descriptor. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_parseFileDescriptor( JNIEnv *env, jobject jthis, jobject fileDescriptor, jint box_type ) { int fileno; jclass this_class; jfieldID pdf_field_id; pdf_t *pdf = NULL; jboolean iscopy; this_class = (*env)->GetObjectClass(env, jthis); pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); fileno = get_descriptor_from_file_descriptor(env, fileDescriptor); pdf = parse_pdf_file(NULL, fileno); if (NUM_BOXES <= box_type) strcpy(pdf->box, "CropBox"); else strcpy(pdf->box, boxes[box_type]); (*env)->SetIntField(env, jthis, pdf_field_id, (int)pdf); } /** * Implementation of native method PDF.getPageCount - return page count of this PDF file. * Returns -1 on error, eg if pdf_ptr is NULL. * @param env JNI Environment * @param this PDF object * @return page count or -1 on error */ JNIEXPORT jint JNICALL Java_cx_hell_android_pdfview_PDF_getPageCount( JNIEnv *env, jobject this) { pdf_t *pdf = NULL; pdf = get_pdf_from_this(env, this); if (pdf == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "pdf is null"); return -1; } return pdf_count_pages(pdf->xref); } JNIEXPORT jintArray JNICALL Java_cx_hell_android_pdfview_PDF_renderPage( JNIEnv *env, jobject this, jint pageno, jint zoom, jint left, jint top, jint rotation, jboolean gray, jboolean skipImages, jobject size) { jint *buf; /* rendered page, freed before return, as bitmap */ jintArray jints; /* return value */ pdf_t *pdf; /* parsed pdf data, extracted from java's "this" object */ int width, height; get_size(env, size, &width, &height); __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "jni renderPage(pageno: %d, zoom: %d, left: %d, top: %d, width: %d, height: %d) start", (int)pageno, (int)zoom, (int)left, (int)top, (int)width, (int)height); pdf = get_pdf_from_this(env, this); jints = get_page_image_bitmap(env, pdf, pageno, zoom, left, top, rotation, gray, skipImages, &width, &height); if (jints != NULL) save_size(env, size, width, height); return jints; } JNIEXPORT jint JNICALL Java_cx_hell_android_pdfview_PDF_getPageSize( JNIEnv *env, jobject this, jint pageno, jobject size) { int width, height, error; pdf_t *pdf; pdf = get_pdf_from_this(env, this); if (pdf == NULL) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "this.pdf is null"); return 1; } error = get_page_size(pdf, pageno, &width, &height); if (error != 0) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "get_page_size error: %d", (int)error); /* __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fitz error is:\n%s", fz_errorbuf); */ return 2; } save_size(env, size, width, height); return 0; } /** * Free resources allocated in native code. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_freeMemory( JNIEnv *env, jobject this) { pdf_t *pdf = NULL; jclass this_class = (*env)->GetObjectClass(env, this); jfieldID pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "jni freeMemory()"); pdf = (pdf_t*) (*env)->GetIntField(env, this, pdf_field_id); (*env)->SetIntField(env, this, pdf_field_id, 0); if (pdf->pages) { int i; int pagecount; pagecount = pdf_count_pages(pdf->xref); for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) { pdf_free_page(pdf->pages[i]); pdf->pages[i] = NULL; } } free(pdf->pages); } /* if (pdf->textlines) { int i; int pagecount; pagecount = pdf_getpagecount(pdf->xref); for(i = 0; i < pagecount; ++i) { if (pdf->textlines[i]) { pdf_droptextline(pdf->textlines[i]); } } free(pdf->textlines); pdf->textlines = NULL; } */ /* if (pdf->drawcache) { fz_freeglyphcache(pdf->drawcache); pdf->drawcache = NULL; } */ /* pdf->fileno is dup()-ed in parse_pdf_fileno */ if (pdf->fileno >= 0) close(pdf->fileno); if (pdf->glyph_cache) fz_free_glyph_cache(pdf->glyph_cache); if (pdf->xref) pdf_free_xref(pdf->xref); free(pdf); } #if 0 JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_export( JNIEnv *env, jobject this) { pdf_t *pdf = NULL; jobject results = NULL; pdf_page *page = NULL; fz_text_span *text_span = NULL, *ln = NULL; fz_device *dev = NULL; char *textlinechars; char *found = NULL; fz_error error = 0; jobject find_result = NULL; int pageno = 0; int pagecount; int fd; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "export to txt"); pdf = get_pdf_from_this(env, this); pagecount = pdf_count_pages(pdf->xref); fd = open("/tmp/pdfview-export.txt", O_WRONLY|O_CREAT, 0666); if (fd < 0) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "Error opening /tmp/pdfview-export.txt"); return; } for(pageno = 0; pageno < pagecount ; pageno++) { page = get_page(pdf, pageno); if (pdf->last_pageno != pageno && NULL != pdf->xref->store) { pdf_age_store(pdf->xref->store, TEXT_STORE_MAX_AGE); pdf->last_pageno = pageno; } text_span = fz_new_text_span(); dev = fz_new_text_device(text_span); error = pdf_run_page(pdf->xref, page, dev, fz_identity); if (error) { /* TODO: cleanup */ fz_rethrow(error, "text extraction failed"); return; } /* TODO: Detect paragraph breaks using bbox field */ for(ln = text_span; ln; ln = ln->next) { int i; textlinechars = (char*)malloc(ln->len + 1); for(i = 0; i < ln->len; ++i) textlinechars[i] = ln->text[i].c; textlinechars[i] = '\n'; write(fd, textlinechars, ln->len+1); free(textlinechars); } fz_free_device(dev); fz_free_text_span(text_span); } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "export complete"); close(fd); } #endif /* wcsstr() seems broken--it matches too much */ wchar_t* widestrstr(wchar_t* haystack, int haystack_length, wchar_t* needle, int needle_length) { char* found; int byte_haystack_length; int byte_needle_length; if (needle_length == 0) return haystack; byte_haystack_length = haystack_length * sizeof(wchar_t); byte_needle_length = needle_length * sizeof(wchar_t); while(haystack_length >= needle_length && NULL != (found = memmem(haystack, byte_haystack_length, needle, byte_needle_length))) { int delta = found - (char*)haystack; int new_offset; /* Check if the find is wchar_t-aligned */ if (delta % sizeof(wchar_t) == 0) return (wchar_t*)found; new_offset = (delta + sizeof(wchar_t) - 1) / sizeof(wchar_t); haystack += new_offset; haystack_length -= new_offset; byte_haystack_length = haystack_length * sizeof(wchar_t); } return NULL; } /* TODO: Specialcase searches for 7-bit text to make them faster */ JNIEXPORT jobject JNICALL Java_cx_hell_android_pdfview_PDF_find( JNIEnv *env, jobject this, jstring text, jint pageno) { pdf_t *pdf = NULL; const jchar *jtext = NULL; wchar_t *ctext = NULL; jboolean is_copy; jobject results = NULL; pdf_page *page = NULL; fz_text_span *text_span = NULL, *ln = NULL; fz_device *dev = NULL; wchar_t *textlinechars; wchar_t *found = NULL; fz_error error = 0; jobject find_result = NULL; int length; int i; jtext = (*env)->GetStringChars(env, text, &is_copy); if (jtext == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "text cannot be null"); (*env)->ReleaseStringChars(env, text, jtext); return NULL; } length = (*env)->GetStringLength(env, text); ctext = malloc((length+1) * sizeof(wchar_t)); for (i=0; i<length; i++) { ctext[i] = towlower(jtext[i]); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "find(%x)", ctext[i]); } ctext[length] = 0; /* This will be needed if wcsstr() ever starts to work */ pdf = get_pdf_from_this(env, this); page = get_page(pdf, pageno); if (pdf->last_pageno != pageno && NULL != pdf->xref->store) { pdf_age_store(pdf->xref->store, FIND_STORE_MAX_AGE); pdf->last_pageno = pageno; } text_span = fz_new_text_span(); dev = fz_new_text_device(text_span); error = pdf_run_page(pdf->xref, page, dev, fz_identity); if (error) { /* TODO: cleanup */ fz_rethrow(error, "text extraction failed"); return NULL; } for(ln = text_span; ln; ln = ln->next) { if (length <= ln->len) { textlinechars = (wchar_t*)malloc((ln->len + 1)*sizeof(wchar_t)); for(i = 0; i < ln->len; ++i) textlinechars[i] = towlower(ln->text[i].c); textlinechars[ln->len] = 0; /* will be needed if wccstr starts to work */ found = widestrstr(textlinechars, ln->len, ctext, length); if (found) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found something, creating empty find result"); find_result = create_find_result(env); if (find_result == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "tried to create empty find result, but got NULL instead"); /* TODO: free resources */ free(ctext); (*env)->ReleaseStringChars(env, text, jtext); pdf_age_store(pdf->xref->store, 0); return; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found something, empty find result created"); set_find_result_page(env, find_result, pageno); /* now add markers to this find result */ { int i = 0; int i0, i1; /* int x, y; */ fz_bbox charbox; i0 = (found-textlinechars); i1 = i0 + length; for(i = i0; i < i1; ++i) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding marker for letter %d: %c", i, textlinechars[i]); /* x = ln->text[i].x; y = ln->text[i].y; convert_point_pdf_to_apv(pdf, pageno, &x, &y); */ charbox = ln->text[i].bbox; convert_box_pdf_to_apv(pdf, pageno, &charbox); /* add_find_result_marker(env, find_result, x-2, y-2, x+2, y+2); */ add_find_result_marker(env, find_result, charbox.x0-2, charbox.y0-2, charbox.x1+2, charbox.y1+2); /* TODO: check errors */ } /* TODO: obviously this sucks massively, good God please forgive me for writing this; if only I had more time... */ /* x = ((float)(ln->text[i1-1].x - ln->text[i0].x)) / (float)strlen(ctext) + ln->text[i1-1].x; y = ((float)(ln->text[i1-1].y - ln->text[i0].y)) / (float)strlen(ctext) + ln->text[i1-1].y; convert_point_pdf_to_apv(pdf, pageno, &x, &y); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding final marker"); add_find_result_marker(env, find_result, x-2, y-2, x+2, y+2 ); */ } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding find result to list"); add_find_result_to_list(env, &results, find_result); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "added find result to list"); } free(textlinechars); } } fz_free_device(dev); fz_free_text_span(text_span); free(ctext); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "releasing text back to jvm"); (*env)->ReleaseStringChars(env, text, jtext); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "returning results"); pdf_age_store(pdf->xref->store, 0); return results; } /** * Create empty FindResult object. * @param env JNI Environment * @return newly created, empty FindResult object */ jobject create_find_result(JNIEnv *env) { static jmethodID constructorID; jclass findResultClass = NULL; static int jni_ids_cached = 0; jobject findResultObject = NULL; findResultClass = (*env)->FindClass(env, "cx/hell/android/lib/pagesview/FindResult"); if (findResultClass == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "create_find_result: FindClass returned NULL"); return NULL; } if (jni_ids_cached == 0) { constructorID = (*env)->GetMethodID(env, findResultClass, "<init>", "()V"); if (constructorID == NULL) { (*env)->DeleteLocalRef(env, findResultClass); __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "create_find_result: couldn't get method id for FindResult constructor"); return NULL; } jni_ids_cached = 1; } findResultObject = (*env)->NewObject(env, findResultClass, constructorID); return findResultObject; } void add_find_result_to_list(JNIEnv *env, jobject *list, jobject find_result) { static int jni_ids_cached = 0; static jmethodID list_add_method_id = NULL; jclass list_class = NULL; if (list == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "list cannot be null - it must be a pointer jobject variable"); return; } if (find_result == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "find_result cannot be null"); return; } if (*list == NULL) { jmethodID list_constructor_id; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "creating ArrayList"); list_class = (*env)->FindClass(env, "java/util/ArrayList"); if (list_class == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't find class java/util/ArrayList"); return; } list_constructor_id = (*env)->GetMethodID(env, list_class, "<init>", "()V"); if (!list_constructor_id) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "couldn't find ArrayList constructor"); return; } *list = (*env)->NewObject(env, list_class, list_constructor_id); if (*list == NULL) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "failed to create ArrayList: NewObject returned NULL"); return; } } if (!jni_ids_cached) { if (list_class == NULL) { list_class = (*env)->FindClass(env, "java/util/ArrayList"); if (list_class == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't find class java/util/ArrayList"); return; } } list_add_method_id = (*env)->GetMethodID(env, list_class, "add", "(Ljava/lang/Object;)Z"); if (list_add_method_id == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't get ArrayList.add method id"); return; } jni_ids_cached = 1; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "calling ArrayList.add"); (*env)->CallBooleanMethod(env, *list, list_add_method_id, find_result); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "add_find_result_to_list done"); } /** * Set find results page member. * @param JNI environment * @param findResult find result object that should be modified * @param page new value for page field */ void set_find_result_page(JNIEnv *env, jobject findResult, int page) { static char jni_ids_cached = 0; static jfieldID page_field_id = 0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "trying to set find results page number"); if (jni_ids_cached == 0) { jclass findResultClass = (*env)->GetObjectClass(env, findResult); page_field_id = (*env)->GetFieldID(env, findResultClass, "page", "I"); jni_ids_cached = 1; } (*env)->SetIntField(env, findResult, page_field_id, page); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "find result page number set"); } /** * Add marker to find result. */ void add_find_result_marker(JNIEnv *env, jobject findResult, int x0, int y0, int x1, int y1) { static jmethodID addMarker_methodID = 0; static unsigned char jni_ids_cached = 0; if (!jni_ids_cached) { jclass findResultClass = NULL; findResultClass = (*env)->FindClass(env, "cx/hell/android/lib/pagesview/FindResult"); if (findResultClass == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "add_find_result_marker: FindClass returned NULL"); return; } addMarker_methodID = (*env)->GetMethodID(env, findResultClass, "addMarker", "(IIII)V"); if (addMarker_methodID == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "add_find_result_marker: couldn't find FindResult.addMarker method ID"); return; } jni_ids_cached = 1; } (*env)->CallVoidMethod(env, findResult, addMarker_methodID, x0, y0, x1, y1); /* TODO: is always really int jint? */ } /** * Get pdf_ptr field value, cache field address as a static field. * @param env Java JNI Environment * @param this object to get "pdf_ptr" field from * @return pdf_ptr field value */ pdf_t* get_pdf_from_this(JNIEnv *env, jobject this) { static jfieldID field_id = 0; static unsigned char field_is_cached = 0; pdf_t *pdf = NULL; if (! field_is_cached) { jclass this_class = (*env)->GetObjectClass(env, this); field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); field_is_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached pdf_ptr field id %d", (int)field_id); } pdf = (pdf_t*) (*env)->GetIntField(env, this, field_id); return pdf; } /** * Get descriptor field value from FileDescriptor class, cache field offset. * This is undocumented private field. * @param env JNI Environment * @param this FileDescriptor object * @return file descriptor field value */ int get_descriptor_from_file_descriptor(JNIEnv *env, jobject this) { static jfieldID field_id = 0; static unsigned char is_cached = 0; if (!is_cached) { jclass this_class = (*env)->GetObjectClass(env, this); field_id = (*env)->GetFieldID(env, this_class, "descriptor", "I"); is_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached descriptor field id %d", (int)field_id); } __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "will get descriptor field..."); return (*env)->GetIntField(env, this, field_id); } void get_size(JNIEnv *env, jobject size, int *width, int *height) { static jfieldID width_field_id = 0; static jfieldID height_field_id = 0; static unsigned char fields_are_cached = 0; if (! fields_are_cached) { jclass size_class = (*env)->GetObjectClass(env, size); width_field_id = (*env)->GetFieldID(env, size_class, "width", "I"); height_field_id = (*env)->GetFieldID(env, size_class, "height", "I"); fields_are_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached Size fields"); } *width = (*env)->GetIntField(env, size, width_field_id); *height = (*env)->GetIntField(env, size, height_field_id); } /** * Store width and height values into PDF.Size object, cache field ids in static members. * @param env JNI Environment * @param width width to store * @param height height field value to be stored * @param size target PDF.Size object */ void save_size(JNIEnv *env, jobject size, int width, int height) { static jfieldID width_field_id = 0; static jfieldID height_field_id = 0; static unsigned char fields_are_cached = 0; if (! fields_are_cached) { jclass size_class = (*env)->GetObjectClass(env, size); width_field_id = (*env)->GetFieldID(env, size_class, "width", "I"); height_field_id = (*env)->GetFieldID(env, size_class, "height", "I"); fields_are_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached Size fields"); } (*env)->SetIntField(env, size, width_field_id, width); (*env)->SetIntField(env, size, height_field_id, height); } /** * pdf_t "constructor": create empty pdf_t with default values. * @return newly allocated pdf_t struct with fields set to default values */ pdf_t* create_pdf_t() { pdf_t *pdf = NULL; pdf = (pdf_t*)malloc(sizeof(pdf_t)); pdf->xref = NULL; pdf->outline = NULL; pdf->fileno = -1; pdf->pages = NULL; pdf->glyph_cache = NULL; } #if 0 /** * Parse bytes into PDF struct. * @param bytes pointer to bytes that should be parsed * @param len length of byte buffer * @return initialized pdf_t struct; or NULL if loading failed */ pdf_t* parse_pdf_bytes(unsigned char *bytes, size_t len, jstring box_name) { pdf_t *pdf; const char* c_box_name; fz_error error; pdf = create_pdf_t(); c_box_name = (*env)->GetStringUTFChars(env, box_name, &iscopy); strncpy(pdf->box, box_name, 9); pdf->box[MAX_BOX_NAME] = 0; pdf->xref = pdf_newxref(); error = pdf_loadxref_mem(pdf->xref, bytes, len); if (error) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "got err from pdf_loadxref_mem: %d", (int)error); __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fz errors:\n%s", fz_errorbuf); /* TODO: free resources */ return NULL; } error = pdf_decryptxref(pdf->xref); if (error) { return NULL; } if (pdf_needspassword(pdf->xref)) { int authenticated = 0; authenticated = pdf_authenticatepassword(pdf->xref, ""); if (!authenticated) { /* TODO: ask for password */ __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "failed to authenticate with empty password"); return NULL; } } pdf->xref->root = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Root")); fz_keepobj(pdf->xref->root); pdf->xref->info = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Info")); fz_keepobj(pdf->xref->info); pdf->outline = pdf_loadoutline(pdf->xref); return pdf; } #endif /** * Parse file into PDF struct. * Use filename if it's not null, otherwise use fileno. */ pdf_t* parse_pdf_file(const char *filename, int fileno) { pdf_t *pdf; fz_error error; int fd; fz_stream *file; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "parse_pdf_file(%s, %d)", filename, fileno); pdf = create_pdf_t(); if (filename) { fd = open(filename, O_BINARY | O_RDONLY, 0666); if (fd < 0) { return NULL; } } else { pdf->fileno = dup(fileno); fd = pdf->fileno; } file = fz_open_fd(fd); error = pdf_open_xref_with_stream(&(pdf->xref), file, NULL); if (!pdf->xref) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "got NULL from pdf_openxref"); /* __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "fz errors:\n%s", fz_errorbuf); */ return NULL; } /* error = pdf_decryptxref(pdf->xref); if (error) { return NULL; } */ if (pdf_needs_password(pdf->xref)) { int authenticated = 0; authenticated = pdf_authenticate_password(pdf->xref, ""); if (!authenticated) { /* TODO: ask for password */ __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "failed to authenticate with empty password"); return NULL; } } /* pdf->xref->root = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Root")); fz_keepobj(pdf->xref->root); pdf->xref->info = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Info")); if (pdf->xref->info) fz_keepobj(pdf->xref->info); */ pdf->outline = pdf_load_outline(pdf->xref); error = pdf_load_page_tree(pdf->xref); if (error) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "pdf_loadpagetree failed: %d", error); /* TODO: clean resources */ return NULL; } { int c = 0; c = pdf_count_pages(pdf->xref); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page count: %d", c); } pdf->last_pageno = -1; return pdf; } /** * Calculate zoom to best match given dimensions. * There's no guarantee that page zoomed by resulting zoom will fit rectangle max_width x max_height exactly. * @param max_width expected max width * @param max_height expected max height * @param page original page * @return zoom required to best fit page into max_width x max_height rectangle */ /*double get_page_zoom(pdf_page *page, int max_width, int max_height) { double page_width, page_height; double zoom_x, zoom_y; double zoom; page_width = page->mediabox.x1 - page->mediabox.x0; page_height = page->mediabox.y1 - page->mediabox.y0; zoom_x = max_width / page_width; zoom_y = max_height / page_height; zoom = (zoom_x < zoom_y) ? zoom_x : zoom_y; return zoom; }*/ /** * Lazy get-or-load page. * Only PDFVIEW_MAX_PAGES_LOADED pages can be loaded at the time. * @param pdf pdf struct * @param pageno 0-based page number * @return pdf_page */ pdf_page* get_page(pdf_t *pdf, int pageno) { fz_error error = 0; int loaded_pages = 0; int pagecount; pagecount = pdf_count_pages(pdf->xref); if (!pdf->pages) { int i; pdf->pages = (pdf_page**)malloc(pagecount * sizeof(pdf_page*)); for(i = 0; i < pagecount; ++i) pdf->pages[i] = NULL; } if (!pdf->pages[pageno]) { pdf_page *page = NULL; int loaded_pages = 0; int i = 0; for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) loaded_pages++; } #if 0 if (loaded_pages >= PDFVIEW_MAX_PAGES_LOADED) { int page_to_drop = 0; /* not the page number */ int j = 0; __android_log_print(ANDROID_LOG_INFO, PDFVIEW_LOG_TAG, "already loaded %d pages, going to drop random one", loaded_pages); page_to_drop = rand() % loaded_pages; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "will drop %d-th loaded page", page_to_drop); /* search for page_to_drop-th loaded page and then drop it */ for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) { /* one of loaded pages, the j-th one */ if (j == page_to_drop) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found %d-th loaded page, it's %d-th in document, dropping now", page_to_drop, i); pdf_droppage(pdf->pages[i]); pdf->pages[i] = NULL; break; } else { j++; } } } } #endif error = pdf_load_page(&page, pdf->xref, pageno); if (error) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "pdf_loadpage -> %d", (int)error); /* __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fitz error is:\n%s", fz_errorbuf); */ return NULL; } pdf->pages[pageno] = page; } return pdf->pages[pageno]; } /** * Get part of page as bitmap. * Parameters left, top, width and height are interprted after scalling, so if we have 100x200 page scalled by 25% and * request 0x0 x 25x50 tile, we should get 25x50 bitmap of whole page content. * pageno is 0-based. */ static jintArray get_page_image_bitmap(JNIEnv *env, pdf_t *pdf, int pageno, int zoom_pmil, int left, int top, int rotation, int gray, int skipImages, int *width, int *height) { unsigned char *bytes = NULL; fz_matrix ctm; double zoom; fz_rect bbox; fz_error error = 0; pdf_page *page = NULL; fz_pixmap *image = NULL; static int runs = 0; fz_device *dev = NULL; int num_pixels; jintArray jints; /* return value */ int *jbuf; /* pointer to internal jint */ fz_obj *pageobj; fz_obj *trimobj; fz_rect trimbox; zoom = (double)zoom_pmil / 1000.0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "get_page_image_bitmap(pageno: %d) start", (int)pageno); if (!pdf->glyph_cache) { pdf->glyph_cache = fz_new_glyph_cache(); if (!pdf->glyph_cache) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "failed to create glyphcache"); return NULL; } } if (pdf->last_pageno != pageno && NULL != pdf->xref->store) { pdf_age_store(pdf->xref->store, BITMAP_STORE_MAX_AGE); pdf->last_pageno = pageno; } page = get_page(pdf, pageno); if (!page) return NULL; /* TODO: handle/propagate errors */ ctm = fz_identity; pageobj = pdf->xref->page_objs[pageno]; trimobj = fz_dict_gets(pageobj, pdf->box); if (trimobj != NULL) trimbox = pdf_to_rect(trimobj); else trimbox = page->mediabox; ctm = fz_concat(ctm, fz_translate(-trimbox.x0, -trimbox.y1)); ctm = fz_concat(ctm, fz_scale(zoom, -zoom)); rotation = page->rotate + rotation * -90; if (rotation != 0) ctm = fz_concat(ctm, fz_rotate(rotation)); bbox = fz_transform_rect(ctm, trimbox); /* not bbox holds page after transform, but we only need tile at (left,right) from top-left corner */ bbox.x0 = bbox.x0 + left; bbox.y0 = bbox.y0 + top; bbox.x1 = bbox.x0 + *width; bbox.y1 = bbox.y0 + *height; #if 0 error = fz_rendertree(&image, pdf->renderer, page->tree, ctm, fz_roundrect(bbox), 1); if (error) { fz_rethrow(error, "rendering failed"); /* TODO: cleanup mem on error, so user can try to open many files without causing memleaks; also report errors nicely to user */ return NULL; } #endif image = fz_new_pixmap(gray ? fz_device_gray : fz_device_bgr, *width, *height); image->x = bbox.x0; image->y = bbox.y0; fz_clear_pixmap_with_color(image, gray ? 0 : 0xff); memset(image->samples, gray ? 0 : 0xff, image->h * image->w * image->n); dev = fz_new_draw_device(pdf->glyph_cache, image); if (skipImages) dev->hints |= FZ_IGNORE_IMAGE; error = pdf_run_page(pdf->xref, page, dev, ctm); if (error) { /* TODO: cleanup */ fz_rethrow(error, "rendering failed"); return NULL; } fz_free_device(dev); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "got image %d x %d, asked for %d x %d", (int)(image->w), (int)(image->h), *width, *height); /* TODO: learn jni and avoid copying bytes ;) */ num_pixels = image->w * image->h; jints = (*env)->NewIntArray(env, num_pixels); jbuf = (*env)->GetIntArrayElements(env, jints, NULL); if (gray) { copy_alpha((unsigned char*)jbuf, image->samples, image->w, image->h); } else { memcpy(jbuf, image->samples, num_pixels * 4); } (*env)->ReleaseIntArrayElements(env, jints, jbuf, 0); *width = image->w; *height = image->h; fz_drop_pixmap(image); runs += 1; return jints; } void copy_alpha(unsigned char* out, unsigned char *in, unsigned int w, unsigned int h) { unsigned int count = w*h; while(count--) { out+= 3; *out++ = 255-((255-in[0]) * in[1])/255; in += 2; } } /** * Get page size in APV's convention. * @param page 0-based page number * @param pdf pdf struct * @param width target for width value * @param height target for height value * @return error code - 0 means ok */ int get_page_size(pdf_t *pdf, int pageno, int *width, int *height) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *sizeobj = NULL; fz_rect bbox; fz_obj *rotateobj = NULL; int rotate = 0; pageobj = pdf->xref->page_objs[pageno]; sizeobj = fz_dict_gets(pageobj, pdf->box); if (sizeobj == NULL) sizeobj = fz_dict_gets(pageobj, "MediaBox"); rotateobj = fz_dict_gets(pageobj, "Rotate"); if (fz_is_int(rotateobj)) { rotate = fz_to_int(rotateobj); } else { rotate = 0; } bbox = pdf_to_rect(sizeobj); if (rotate != 0 && (rotate % 180) == 90) { *width = bbox.y1 - bbox.y0; *height = bbox.x1 - bbox.x0; } else { *width = bbox.x1 - bbox.x0; *height = bbox.y1 - bbox.y0; } return 0; } #if 0 /** * Convert coordinates from pdf to APVs. * TODO: faster? lazy? * @return error code, 0 means ok */ int convert_point_pdf_to_apv(pdf_t *pdf, int page, int *x, int *y) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *rotateobj = NULL; fz_obj *sizeobj = NULL; fz_rect bbox; int rotate = 0; fz_point p; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "convert_point_pdf_to_apv()"); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "trying to convert %d x %d to APV coords", *x, *y); pageobj = pdf_getpageobject(pdf->xref, page+1); if (!pageobj) return -1; sizeobj = fz_dictgets(pageobj, pdf->box); if (sizeobj == NULL) sizeobj = fz_dictgets(pageobj, "MediaBox"); if (!sizeobj) return -1; bbox = pdf_torect(sizeobj); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page bbox is %.1f, %.1f, %.1f, %.1f", bbox.x0, bbox.y0, bbox.x1, bbox.y1); rotateobj = fz_dictgets(pageobj, "Rotate"); if (fz_isint(rotateobj)) { rotate = fz_toint(rotateobj); } else { rotate = 0; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "rotate is %d", (int)rotate); p.x = *x; p.y = *y; if (rotate != 0) { fz_matrix m; m = fz_rotate(-rotate); bbox = fz_transformrect(m, bbox); p = fz_transformpoint(m, p); } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate bbox is: %.1f, %.1f, %.1f, %.1f", bbox.x0, bbox.y0, bbox.x1, bbox.y1); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate point is: %.1f, %.1f", p.x, p.y); *x = p.x - MIN(bbox.x0,bbox.x1); *y = MAX(bbox.y1, bbox.y0) - p.y; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "result is: %d, %d", *x, *y); return 0; } #endif /** * Convert coordinates from pdf to APV. * Result is stored in location pointed to by bbox param. * This function has to get page TrimBox relative to which bbox is located. * This function should not allocate any memory. * @return error code, 0 means ok */ int convert_box_pdf_to_apv(pdf_t *pdf, int page, fz_bbox *bbox) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *rotateobj = NULL; fz_obj *sizeobj = NULL; fz_rect page_bbox; fz_rect param_bbox; int rotate = 0; float height = 0; float width = 0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "convert_box_pdf_to_apv(page: %d, bbox: %d %d %d %d)", page, bbox->x0, bbox->y0, bbox->x1, bbox->y1); /* copying field by field becuse param_bbox is fz_rect (floats) and *bbox is fz_bbox (ints) */ param_bbox.x0 = bbox->x0; param_bbox.y0 = bbox->y0; param_bbox.x1 = bbox->x1; param_bbox.y1 = bbox->y1; pageobj = pdf->xref->page_objs[page]; if (!pageobj) return -1; sizeobj = fz_dict_gets(pageobj, pdf->box); if (sizeobj == NULL) sizeobj = fz_dict_gets(pageobj, "MediaBox"); if (!sizeobj) return -1; page_bbox = pdf_to_rect(sizeobj); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page bbox is %.1f, %.1f, %.1f, %.1f", page_bbox.x0, page_bbox.y0, page_bbox.x1, page_bbox.y1); rotateobj = fz_dict_gets(pageobj, "Rotate"); if (fz_is_int(rotateobj)) { rotate = fz_to_int(rotateobj); } else { rotate = 0; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "rotate is %d", (int)rotate); if (rotate != 0) { fz_matrix m; m = fz_rotate(-rotate); param_bbox = fz_transform_rect(m, param_bbox); page_bbox = fz_transform_rect(m, page_bbox); } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate page bbox is: %.1f, %.1f, %.1f, %.1f", page_bbox.x0, page_bbox.y0, page_bbox.x1, page_bbox.y1); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate param bbox is: %.1f, %.1f, %.1f, %.1f", param_bbox.x0, param_bbox.y0, param_bbox.x1, param_bbox.y1); /* set result: param bounding box relative to left-top corner of page bounding box */ /* bbox->x0 = MIN(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1); bbox->y0 = MIN(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1); bbox->x1 = MAX(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1); bbox->y1 = MAX(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1); */ width = ABS(page_bbox.x0 - page_bbox.x1); height = ABS(page_bbox.y0 - page_bbox.y1); bbox->x0 = (MIN(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1)); bbox->y1 = height - (MIN(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1)); bbox->x1 = (MAX(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1)); bbox->y0 = height - (MAX(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1)); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "result after transformations: %d, %d, %d, %d", bbox->x0, bbox->y0, bbox->x1, bbox->y1); return 0; } void pdf_android_loghandler(const char *m) { __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview.mupdf", m); } /* vim: set sts=4 ts=4 sw=4 et: */
zzyangming-szyangming
pdfview/jni/pdfview2/pdfview2.c
C
gpl3
41,387
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_CFLAGS := -O3 LOCAL_ARM_MODE := arm LOCAL_C_INCLUDES += $(LOCAL_PATH)/../mupdf/fitz $(LOCAL_PATH)/../mupdf/pdf $(LOCAL_PATH)/../freetype-overlay/include $(LOCAL_PATH)/../freetype/include $(LOCAL_PATH)/pdfview2/include LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -lz -llog LOCAL_STATIC_LIBRARIES := pdf fitz fitzdraw jpeg jbig2dec openjpeg freetype LOCAL_MODULE := pdfview2 LOCAL_SRC_FILES := pdfview2.c include $(BUILD_SHARED_LIBRARY)
zzyangming-szyangming
pdfview/jni/pdfview2/Android.mk
Makefile
gpl3
492