code
stringlengths
3
1.18M
language
stringclasses
1 value
package queries; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public final class EMF { private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional"); private EMF() {} public static EntityManagerFactory get() { return emfInstance; } }
Java
package queries; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.SimpleTimeZone; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.servlet.http.*; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.KeyFactory.Builder; import queries.Book; import queries.EMF; @SuppressWarnings("serial") public class JPAQueriesServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); EntityManagerFactory emf = EMF.get(); EntityManager em = null; try { em = emf.createEntityManager(); Book book = new Book("978-0141185064"); book.setTitle("The Grapes of Wrath"); book.setAuthor("John Steinbeck"); book.setCopyrightYear(1939); Date authorBirthdate = new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime(); book.setAuthorBirthdate(authorBirthdate); em.persist(book); } finally { em.close(); } try { em = emf.createEntityManager(); Book book = new Book("978-0141185101"); book.setTitle("Of Mice and Men"); book.setAuthor("John Steinbeck"); book.setCopyrightYear(1937); Date authorBirthdate = new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime(); book.setAuthorBirthdate(authorBirthdate); em.persist(book); } finally { em.close(); } try { em = emf.createEntityManager(); Book book = new Book("978-0684801469"); book.setTitle("A Farewell to Arms"); book.setAuthor("Ernest Hemmingway"); book.setCopyrightYear(1929); Date authorBirthdate = new GregorianCalendar(1899, Calendar.JULY, 21).getTime(); book.setAuthorBirthdate(authorBirthdate); em.persist(book); } finally { em.close(); } try { em = emf.createEntityManager(); Book book = new Book("978-0684830483"); book.setTitle("For Whom the Bell Tolls"); book.setAuthor("Ernest Hemmingway"); book.setCopyrightYear(1940); Date authorBirthdate = new GregorianCalendar(1899, Calendar.JULY, 21).getTime(); book.setAuthorBirthdate(authorBirthdate); em.persist(book); } finally { em.close(); } try { em = emf.createEntityManager(); Query query = null; List<Book> results = null; // Query for all entities of a kind query = em.createQuery("SELECT b FROM Book b"); out.println("<p>Every book:</p><ul>"); results = (List<Book>) query.getResultList(); for (Book b : results) { out.println("<li><i>" + b.getTitle() + "</i>, " + b.getAuthor() + ", " + b.getCopyrightYear() + "</li>"); } out.println("</ul>"); // Query with a property filter query = em.createQuery( "SELECT b FROM Book b WHERE copyrightYear >= :earliestYear"); query.setParameter("earliestYear", 1937); out.println("<p>Every book published in or after 1937:</p><ul>"); results = (List<Book>) query.getResultList(); for (Book b : results) { out.println("<li><i>" + b.getTitle() + "</i>, " + b.getAuthor() + ", " + b.getCopyrightYear() + "</li>"); } out.println("</ul>"); // Getting just the first result of a query query = em.createQuery( "SELECT b FROM Book b WHERE title = \"A Farewell to Arms\""); Book singleResult = (Book) query.getSingleResult(); if (singleResult != null) { out.println("<p>Found: <i>" + singleResult.getTitle() + "</i>, " + singleResult.getAuthor() + "</p>"); } else { out.println("<p>Could not find that book I was looking for...</p>"); } // Getting specific results in the result list query = em.createQuery("SELECT b FROM Book b"); out.println("<p>Books #3-#4:</p><ul>"); query.setFirstResult(2); query.setMaxResults(2); results = (List<Book>) query.getResultList(); for (Book b : results) { out.println("<li><i>" + b.getTitle() + "</i>, " + b.getAuthor() + ", " + b.getCopyrightYear() + "</li>"); } out.println("</ul>"); // A keys-only query query = em.createQuery("SELECT isbn FROM Book b"); out.println("<p>Keys-only query:</p><ul>"); List<String> resultKeys = (List<String>) query.getResultList(); for (String k : resultKeys) { out.println("<li>" + k + "</li>"); } out.println("</ul>"); // JPA field selection query = em.createQuery("SELECT isbn, title, author FROM Book"); out.println("<p>Field selection:</p><ul>"); List<Object[]> resultsFields = (List<Object[]>) query.getResultList(); for (Object[] result : resultsFields) { String isbn = (String) result[0]; String title = (String) result[1]; String author = (String) result[2]; out.println("<li><i>" + title + "</i>, " + author + " (" + isbn + ")</li>"); } out.println("</ul>"); query = em.createQuery("DELETE FROM Book b"); query.executeUpdate(); out.println("<p>Entities deleted.</p>"); } finally { em.close(); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package sendingmail; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.SimpleTimeZone; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; @SuppressWarnings("serial") public class SendingMailServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); User user = UserServiceFactory.getUserService().getCurrentUser(); String recipientAddress = user.getEmail(); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String messageBody = "Thank you for purchasing The Example App, the best\n" + "example on the market! Your registration key is attached\n" + "to this email.\n\n" + "To install your key, download the attachment, then select\n" + "\"Register...\" from the Help menu. Select the key file, then click\n" + "\"Register\".\n\n" + "You can download the app at any time from:\n" + " http://www.example.com/downloads/\n\n" + "[This is not a real website.]\n\n" + "Thanks again!\n\n" + "The Example Team\n"; String htmlMessageBody = "<p>Thank you for purchasing The Example App, the best " + "example on the market! Your registration key is attached " + "to this email.</p>" + "<p>To install your key, download the attachment, then select " + "<b>Register...</b> from the <b>Help</b> menu. Select the key file, then " + "click <b>Register</b>.</p>" + "<p>You can download the app at any time from:</p>" + "<p>" + "<a href=\"http://www.example.com/downloads/\">" + "http://www.example.com/downloads/" + "</a>" + "</p>" + "<p>[This is not a real website.]</p>" + "<p>Thanks again!</p>" + "<p>The Example Team<br />" + "<img src=\"http://www.example.com/images/logo_email.gif\" /></p>"; String softwareKeyData = "REGKEY-12345"; try { // Replace "admin@example.com" with the email address of a // Google Account registered as a developer for this // app. Message message = new MimeMessage(session); message.setFrom(new InternetAddress("admin@example.com", "The Example Team")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress)); message.setSubject("Welcome to Example.com!"); Multipart multipart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(messageBody, "text/plain"); multipart.addBodyPart(textPart); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlMessageBody, "text/html"); multipart.addBodyPart(htmlPart); String fileName = "example_key.txt"; String fileType = "text/plain"; MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setContent(softwareKeyData, fileType); attachmentPart.setFileName(fileName); multipart.addBodyPart(attachmentPart); message.setContent(multipart); Transport.send(message); out.println("<p>Email sent to " + recipientAddress + ".</p>"); } catch (AddressException e) { out.println("<p>AddressException: " + e + "</p>"); } catch (MessagingException e) { out.println("<p>MessagingException: " + e + "</p>"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package receivingmail; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.utils.SystemProperty; import com.google.apphosting.api.ApiProxy; @SuppressWarnings("serial") public class ReceivingMailServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) { out.println("<p>You are running on the development server. " + "You can use <a href=\"/_ah/admin/inboundmail\">" + "the development server console</a> to send email " + "to this application.</p>"); } else { String appId = ApiProxy.getCurrentEnvironment().getAppId(); String appEmailAddress = "support@" + appId + ".appspotmail.com"; out.println("<p>You are running on App Engine. You can " + "<a href=\"mailto:" + appEmailAddress + "\">" + "send email to " + appEmailAddress+ "</a> to " + "send a message to the application.</p>"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package receivingmail; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; import javax.mail.Session; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.MimeMessage; import javax.servlet.http.*; public class MailReceiverServlet extends HttpServlet { private static final Logger log = Logger.getLogger(MailReceiverServlet.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { MimeMessage message = new MimeMessage(session, req.getInputStream()); Object content = message.getContent(); if (content instanceof String) { // A plain text body. log.info("Received email message from " + message.getSender() + " (" + message.getContentType() + "): " + content); } else if (content instanceof Multipart) { // A multipart body. log.info("Received multi-part email message (" + ((Multipart) content).getCount() + " parts)"); for (int i = 0; i < ((Multipart) content).getCount(); i++) { Part part = ((Multipart) content).getBodyPart(i); String partText = (String) part.getContent(); log.info("Part " + i + ": " + " (" + message.getContentType() + "): " + partText); } } } catch (MessagingException e) { log.info("MessagingException: " + e); } } }
Java
package xmpp; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.utils.SystemProperty; import com.google.apphosting.api.ApiProxy; @SuppressWarnings("serial") public class XMPPServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String appId = ApiProxy.getCurrentEnvironment().getAppId(); if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) { out.println("<p>You are running on the development server. " + "You can use <a href=\"/_ah/admin/xmpp\">the " + "development server console</a> to send an XMPP " + "chat message to this application.</p>" + "<p><i>Be sure to use <b>" + appId + "@appspot.com</b> or <b>anything@" + appId + ".appspotchat.com</b> as the \"To\" address.</i></p>"); } else { out.println("<p>You are running on App Engine. You can " + "send an XMPP chat message to " + appId + "@appspot.com to communicate with this application.</p>"); } out.println("<p>This app responds to messages that contain simple " + "two-term arithmetic expressions, such as <code>2 + 3</code> " + "or <code>144 / 4</code>.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package xmpp; import java.io.IOException; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.*; import com.google.appengine.api.xmpp.Message; import com.google.appengine.api.xmpp.MessageBuilder; import com.google.appengine.api.xmpp.SendResponse; import com.google.appengine.api.xmpp.XMPPService; import com.google.appengine.api.xmpp.XMPPServiceFactory; public class XMPPReceiverServlet extends HttpServlet { private static final Logger log = Logger.getLogger(XMPPReceiverServlet.class.getName()); private String doArithmetic(String question) { Pattern exprPat = Pattern.compile("\\s*(-?\\d+(?:\\.\\d+)?)\\s*([\\+\\-\\*\\/])\\s*(-?\\d+(?:\\.\\d+)?)"); Matcher m = exprPat.matcher(question); if (!m.matches()) { return null; } Float first = Float.valueOf(m.group(1)); String op = m.group(2); Float second = Float.valueOf(m.group(3)); Float answer = 0f; if (op.equals("+")) { answer = first + second; } else if (op.equals("-")) { answer = first - second; } else if (op.equals("*")) { answer = first * second; } else { // op.equals("/") if (second == 0) { return "Inf"; } else { answer = first / second; } } return answer.toString(); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { XMPPService xmpp = XMPPServiceFactory.getXMPPService(); Message message = xmpp.parseMessage(req); String answer = doArithmetic(message.getBody()); if (answer == null) { answer = "I didn't understand: " + message.getBody(); } Message reply = new MessageBuilder() .withRecipientJids(message.getFromJid()) .withBody(answer) .build(); SendResponse success = xmpp.sendMessage(reply); if (success.getStatusMap().get(message.getFromJid()) != SendResponse.Status.SUCCESS) { log.warning("Could not send XMPP reply to " + message.getFromJid()); } } }
Java
package memcache; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.memcache.Expiration; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheService.SetPolicy; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.appengine.api.memcache.Stats; import com.google.appengine.api.memcache.StrictErrorHandler; @SuppressWarnings("serial") public class MemcacheDemoServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); List<String> headlines = new ArrayList(Arrays.asList("...", "...", "...")); MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); memcache.put("headlines", headlines); headlines = (List<String>) memcache.get("headlines"); memcache.delete("headlines"); memcache.put("headlines", headlines, Expiration.byDeltaSeconds(300)); memcache.put("headlines", headlines, null, SetPolicy.ADD_ONLY_IF_NOT_PRESENT); boolean headlinesAreCached = memcache.contains("headlines"); memcache.put("tempnode91512", "..."); memcache.delete("tempnode91512", 5); memcache.put("tempnode91512", "..."); // fails within the 5 second add-lock Map<Object, Object> articleSummaries = new HashMap<Object, Object>(); articleSummaries.put("article00174", "..."); articleSummaries.put("article05234", "..."); articleSummaries.put("article15280", "..."); memcache.putAll(articleSummaries); List<Object> articleSummaryKeys = Arrays.<Object>asList( "article00174", "article05234", "article15820"); articleSummaries = memcache.getAll(articleSummaryKeys); memcache.deleteAll(articleSummaryKeys); memcache.setNamespace("News"); memcache.put("headlines", headlines); List<String> userHeadlines = new ArrayList(Arrays.asList("...", "...", "...")); memcache.setNamespace("User"); memcache.put("headlines", userHeadlines); // Get User:"headlines" userHeadlines = (List<String>) memcache.get("headlines"); // Get News:"headlines" memcache.setNamespace("News"); headlines = (List<String>) memcache.get("headlines"); memcache.put("work_done", 0); Long workDone = memcache.increment("work_done", 1); Stats stats = memcache.getStatistics(); int ageOfOldestItemMillis = stats.getMaxTimeWithoutAccess(); memcache.setErrorHandler(new StrictErrorHandler()); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package queries; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; @SuppressWarnings("serial") public class QueriesServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); // Create some entities. Entity book1 = new Entity("Book"); book1.setProperty("title", "The Grapes of Wrath"); book1.setProperty("copyrightYear", 1939); ds.put(book1); Entity book2 = new Entity("Book"); book2.setProperty("title", "Of Mice and Men"); book2.setProperty("copyrightYear", 1937); ds.put(book2); Entity book3 = new Entity("Book"); book3.setProperty("title", "East of Eden"); book3.setProperty("copyrightYear", 1952); ds.put(book3); // Prepare a query. Query q = new Query("Book"); q.addFilter("copyrightYear", Query.FilterOperator.LESS_THAN_OR_EQUAL, 1939); q.addSort("copyrightYear"); q.addSort("title"); // Perform the query. PreparedQuery pq = ds.prepare(q); for (Entity result : pq.asIterable()) { String title = (String) result.getProperty("title"); out.println("<p>Query result: title = " + title + "</p>"); } ds.delete(book1.getKey(), book2.getKey(), book3.getKey()); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package showfiles; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class ShowFilesServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); File appDir = new File("."); String dirContents[] = appDir.list(); if (dirContents == null) { out.println("<p>There was a problem getting the app directory.</p>"); } else { out.println("<p>The following files and directories are in the app's " + "root directory on the application server:</p><pre>"); for (int i = 0; i < dirContents.length; i++) { out.println(dirContents[i]); } out.println("</pre>"); } out.println("<p>The \"static\" directory appears in this list in the " + "development server, but not when running on App Engine.</p>" + "<p>Links to static files:</p><ul>" + "<li><a href=\"staticexpires.txt\">staticexpires.txt</a> (text)</li>" + "<li><a href=\"static/statictext.txt\">static/statictext.txt</a> (text)</li>" + "<li><a href=\"static/statictext.xxx\">static/statictext.xxx</a> (text)</li>" + "<li><a href=\"static/staticdownload.yyy\">static/staticdownload.yyy</a> (download)</li>" + "</ul>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>" + fmt.format(new Date()) + "</p>"); } }
Java
package environment; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.utils.SystemProperty; @SuppressWarnings("serial") public class PrintEnvironmentServlet extends HttpServlet { public static String escapeHtmlChars(String inStr) { return inStr.replaceAll("&", "&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } public static void printDirectoryListing(PrintWriter out, File dir, String indent) { if (dir.isDirectory()) { out.println(indent + escapeHtmlChars(dir.getName()) + "/"); String[] contents = dir.list(); for (int i = 0; i < contents.length; i++) { printDirectoryListing(out, new File(dir, contents[i]), indent + " "); } } else { out.println(indent + escapeHtmlChars(dir.getName())); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String[] nameArray; out.println("<ul>" + "<li><a href=\"#env\">Environment Variables</a></li>" + "<li><a href=\"#props\">System Properties</a></li>" + "<li><a href=\"#filesystem\">File System</a></li>" + "<li><a href=\"#request\">Request Data</a></li>" + "</ul>"); out.println("<hr noshade><h2 id=\"servlet\">Servlet Information</h2><table>"); out.println("<tr><td valign=\"top\">this.getServletContext().getServerInfo()</td>" + "<td valign=\"top\">" + escapeHtmlChars(this.getServletContext().getServerInfo()) + "</td></tr>"); out.println("<tr><td>SystemProperty.environment</td>"); if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) { out.println("<td>SystemProperty.Environment.Value.Production</td>"); } else { out.println("<td>SystemProperty.Environment.Value.Development</td>"); } out.println("</tr>"); out.println("<tr><td>SystemProperty.version</td><td><code>" + escapeHtmlChars(SystemProperty.version.get()) + "</code></td></tr>"); out.println("</table>"); // TODO: servlet context attributes // TODO: servlet context init parameters out.println("<hr noshade><h2 id=\"env\">Environment Variables</h2><table>"); Map<String, String> environment = System.getenv(); nameArray = environment.keySet().toArray(new String[] {}); Arrays.sort(nameArray); for (String name : nameArray) { out.println("<tr><td valign=\"top\"><code>" + escapeHtmlChars(name) + "</code></td><td valign=\"top\"><code>" + escapeHtmlChars(environment.get(name)) + "</code></td></tr>"); } out.println("</table>"); out.println("<hr noshade><h2 id=\"props\">System Properties</h2><table>"); Properties systemProperties = System.getProperties(); nameArray = Collections.list(systemProperties.propertyNames()).toArray(new String[] {}); Arrays.sort(nameArray); for (String name : nameArray) { out.println("<tr><td valign=\"top\"><code>" + escapeHtmlChars(name) + "</code></td><td valign=\"top\"><code>" + escapeHtmlChars(systemProperties.getProperty(name)) + "</code></td></tr>"); } out.println("</table>"); out.println("<hr noshade><h2 id=\"filesystem\">File System</h2><pre>"); printDirectoryListing(out, new File("."), ""); out.println("</pre>"); out.println("<hr noshade><h2 id=\"request\">Request Data</h2><pre>"); BufferedReader reader = req.getReader(); String line; while ((line = reader.readLine()) != null) { out.println(escapeHtmlChars(line)); } out.println("</pre>"); // TODO: servlet request attributes // TODO: request parameters SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<hr noshade><p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package loggingtest; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import java.util.logging.Logger; import javax.servlet.http.*; @SuppressWarnings("serial") public class LoggingServlet extends HttpServlet { private static final Logger log = Logger.getLogger(LoggingServlet.class.getName()); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); log.finest("finest level"); log.finer("finer level"); log.fine("fine level"); log.config("config level"); log.info("info level"); log.warning("warning level"); log.severe("severe level"); System.out.println("stdout level"); System.err.println("stderr level"); out.println("<p>Messages logged.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package googleaccounts; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @SuppressWarnings("serial") public class AccountStatusServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); UserService userService = UserServiceFactory.getUserService(); if (userService.isUserLoggedIn()) { User user = userService.getCurrentUser(); out.println("<p>You are signed in as " + user.getNickname() + ". "); if (userService.isUserAdmin()) { out.println("You are an administrator. "); } out.println("<a href=\"" + userService.createLogoutURL("/") + "\">Sign out</a>.</p>"); } else { out.println("<p>You are not signed in to Google Accounts. " + "<a href=\"" + userService.createLoginURL(req.getRequestURI()) + "\">Sign in</a>.</p>"); } out.println("<ul>" + "<li><a href=\"/\">/</a></li>" + "<li><a href=\"/required\">/required</a></li>" + "<li><a href=\"/admin\">/admin</a></li>" + "</ul>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package jsptest; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class JspTestServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<p>This page is served by a regular servlet.</p>" + "<p><a href=\"/main.jsp\">Go to main.jsp</a>.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package showsecure; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class ShowSecureServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); if (req.getScheme() == "https") { out.println("<p>This page was accessed over a secure connection.</p>"); } else { out.println("<p>This page was accessed over a normal (non-secure) connection.</p>"); } String httpNormalUrl = "http://" + req.getServerName() + "/normal"; String httpsNormalUrl = "https://" + req.getServerName() + "/normal"; String httpSecureUrl = "http://" + req.getServerName() + "/secure/url"; String httpsSecureUrl = "https://" + req.getServerName() + "/secure/url"; out.println("<ul>" + "<li><a href=\"" + httpNormalUrl + "\">" + httpNormalUrl + "</a></li>" + "<li><a href=\"" + httpsNormalUrl + "\">" + httpsNormalUrl + "</a></li>" + "<li><a href=\"" + httpSecureUrl + "\">" + httpSecureUrl + "</a> (redirects to https)</li>" + "<li><a href=\"" + httpsSecureUrl + "\">" + httpsSecureUrl + "</a></li>" + "</ul>"); out.println("<p>The development server does not support HTTPS, only HTTP.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package remoteapi; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class MainServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<p>This application is configured with the remote " + "API entry point at <code>/remote_api</code>. See " + "<code>web.xml</code> for the configuration, and see " + "the <code>python/ch12/</code> directory for Python " + "code that configures the bulk loader tools.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package transactions; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import java.util.logging.Logger; import javax.servlet.http.*; import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Transaction; @SuppressWarnings("serial") public class TransactionsServlet extends HttpServlet { private static final Logger log = Logger.getLogger(TransactionsServlet.class.getName()); // Hard code the message board name for simplicity. Could support // multiple boards by getting this from the URL. private String boardName = "messageBoard"; public static String escapeHtmlChars(String inStr) { return inStr.replaceAll("&", "&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); // Display information about a message board and its messages. Key boardKey = KeyFactory.createKey("MessageBoard", boardName); try { Entity messageBoard = ds.get(boardKey); long count = (Long) messageBoard.getProperty("count"); resp.getWriter().println("<p>Latest messages posted to " + boardName + " (" + count + " total):</p>"); Query q = new Query("Message", boardKey); PreparedQuery pq = ds.prepare(q); for (Entity result : pq.asIterable()) { resp.getWriter().println( "<h3>" + escapeHtmlChars((String) result.getProperty("message_title")) + "</h3></p>" + escapeHtmlChars((String) result.getProperty("message_text")) + "</p>"); } } catch (EntityNotFoundException e) { resp.getWriter().println("<p>No messages.</p>"); } // Display a web form for creating new messages. resp.getWriter().println( "<p>Post a message:</p>" + "<form action=\"/\" method=\"POST\">" + "<label for=\"title\">Title:</label>" + "<input type=\"text\" name=\"title\" id=\"title\" /><br />" + "<label for=\"body\">Message:</label>" + "<textarea name=\"body\" id=\"body\"></textarea><br />" + "<input type=\"submit\" />" + "</form>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Save the message and update the board count in a // transaction, retrying up to 3 times. DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); String messageTitle = req.getParameter("title"); String messageText = req.getParameter("body"); Date postDate = new Date(); int retries = 3; boolean success = false; while (!success && retries > 0) { --retries; try { Transaction txn = ds.beginTransaction(); Key boardKey; Entity messageBoard; try { boardKey = KeyFactory.createKey("MessageBoard", boardName); messageBoard = ds.get(boardKey); } catch (EntityNotFoundException e) { messageBoard = new Entity("MessageBoard", boardName); messageBoard.setProperty("count", 0L); boardKey = ds.put(messageBoard); } Entity message = new Entity("Message", boardKey); message.setProperty("message_title", messageTitle); message.setProperty("message_text", messageText); message.setProperty("post_date", postDate); ds.put(message); long count = (Long) messageBoard.getProperty("count"); ++count; messageBoard.setProperty("count", count); ds.put(messageBoard); log.info("Posting msg, updating count to " + count + "; " + retries + " retries remaining"); txn.commit(); // Break out of retry loop. success = true; } catch (DatastoreFailureException e) { // Allow retry to occur. } } if (!success) { resp.getWriter().println ("<p>A new message could not be posted. Try again later." + "<a href=\"/\">Return to the board.</a></p>"); } else { resp.sendRedirect("/"); } } }
Java
package urlfetch; import com.google.appengine.api.urlfetch.FetchOptions; import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.ResponseTooLargeException; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class URLFetchServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); try { URL url = new URL("http://ae-book.appspot.com/blog/atom.xml/"); FetchOptions options = FetchOptions.Builder .doNotFollowRedirects() .disallowTruncate(); HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, options); URLFetchService service = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = service.fetch(request); byte[] content = response.getContent(); out.println("<p>Read PGAE blog feed (" + content.length + " characters).</p>"); } catch (ResponseTooLargeException e) { out.println("<p>ResponseTooLargeException: " + e + "</p>"); } catch (MalformedURLException e) { out.println("<p>MalformedURLException: " + e + "</p>"); } catch (IOException e) { out.println("<p>IOException: " + e + "</p>"); } out.println("<p>Try <a href=\"/urlconnection\">/urlconnection</a>.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package urlfetch; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class URLConnectionServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); try { URL url = new URL("http://ae-book.appspot.com/blog/atom.xml/"); InputStream inStream = url.openStream(); InputStreamReader inStreamReader = new InputStreamReader(inStream); BufferedReader reader = new BufferedReader(inStreamReader); // A useless use of the data just to prove it was read. int length = 0; while (reader.read() != -1) { length++; } out.println("<p>Read PGAE blog feed (" + length + " characters).</p>"); reader.close(); } catch (MalformedURLException e) { out.println("<p>MalformedURLException: " + e + "</p>"); } catch (IOException e) { out.println("<p>IOException: " + e + "</p>"); } out.println("<p>Try <a href=\"/urlfetch\">/urlfetch</a>.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package clock; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public final class EMF { private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional"); private EMF() {} public static EntityManagerFactory get() { return emfInstance; } }
Java
package clock; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @SuppressWarnings("serial") public class ClockServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String navBar; String tzForm; if (user == null) { navBar = "<p>Welcome! <a href=\"" + userService.createLoginURL("/") + "\">Sign in or register</a> to customize.</p>"; tzForm = ""; fmt.setTimeZone(new SimpleTimeZone(0, "")); } else { UserPrefs userPrefs = UserPrefs.getPrefsForUser(user); int tzOffset = 0; if (userPrefs != null) { tzOffset = userPrefs.getTzOffset(); } navBar = "<p>Welcome, " + user.getNickname() + "! You can <a href=\"" + userService.createLogoutURL("/") + "\">sign out</a>.</p>"; tzForm = "<form action=\"/prefs\" method=\"post\">" + "<label for=\"tz_offset\">" + "Timezone offset from UTC (can be negative):" + "</label>" + "<input name=\"tz_offset\" id=\"tz_offset\" type=\"text\" size=\"4\" " + "value=\"" + tzOffset + "\" />" + "<input type=\"submit\" value=\"Set\" />" + "</form>"; fmt.setTimeZone(new SimpleTimeZone(tzOffset * 60 * 60 * 1000, "")); } resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println(navBar); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); out.println(tzForm); } }
Java
package clock; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import clock.UserPrefs; @SuppressWarnings("serial") public class PrefsServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); UserPrefs userPrefs = UserPrefs.getPrefsForUser(user); try { int tzOffset = new Integer(req.getParameter("tz_offset")).intValue(); userPrefs.setTzOffset(tzOffset); userPrefs.save(); } catch (NumberFormatException nfe) { // User entered a value that wasn't an integer. Ignore for now. } resp.sendRedirect("/"); } }
Java
package clock; import java.io.Serializable; import java.util.logging.*; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.Id; import javax.persistence.Transient; import com.google.appengine.api.users.User; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceException; import com.google.appengine.api.memcache.MemcacheServiceFactory; import clock.EMF; import clock.UserPrefs; @SuppressWarnings("serial") @Entity(name = "UserPrefs") public class UserPrefs implements Serializable { @Transient private static Logger logger = Logger.getLogger(UserPrefs.class.getName()); @Id private String userId; private int tzOffset; @Basic private User user; public UserPrefs(User user) { this.userId = user.getUserId(); this.user = user; } public String getUserId() { return userId; } public int getTzOffset() { return tzOffset; } public void setTzOffset(int tzOffset) { this.tzOffset = tzOffset; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @SuppressWarnings("unchecked") public static UserPrefs getPrefsForUser(User user) { UserPrefs userPrefs = null; String cacheKey = getCacheKeyForUser(user); try { MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); if (memcache.contains(cacheKey)) { logger.warning("CACHE HIT: " + cacheKey); userPrefs = (UserPrefs) memcache.get(cacheKey); return userPrefs; } logger.warning("CACHE MISS: " + cacheKey); // If the UserPrefs object isn't in memcache, // fall through to the datastore. } catch (MemcacheServiceException e) { // If there is a problem with the cache, // fall through to the datastore. } EntityManager em = EMF.get().createEntityManager(); try { userPrefs = em.find(UserPrefs.class, user.getUserId()); if (userPrefs == null) { userPrefs = new UserPrefs(user); } else { userPrefs.cacheSet(); } } finally { em.close(); } return userPrefs; } public static String getCacheKeyForUser(User user) { return "UserPrefs:" + user.getUserId(); } public String getCacheKey() { return getCacheKeyForUser(this.getUser()); } public void save() { EntityManager em = EMF.get().createEntityManager(); try { em.merge(this); cacheSet(); } finally { em.close(); } } public void cacheSet() { try { MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); memcache.put(getCacheKey(), this); } catch (MemcacheServiceException e) { // Ignore cache problems, nothing we can do. } } }
Java
package clock; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public final class EMF { private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional"); private EMF() {} public static EntityManagerFactory get() { return emfInstance; } }
Java
package clock; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @SuppressWarnings("serial") public class ClockServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String navBar; String tzForm; if (user == null) { navBar = "<p>Welcome! <a href=\"" + userService.createLoginURL("/") + "\">Sign in or register</a> to customize.</p>"; tzForm = ""; fmt.setTimeZone(new SimpleTimeZone(0, "")); } else { UserPrefs userPrefs = UserPrefs.getPrefsForUser(user); int tzOffset = 0; if (userPrefs != null) { tzOffset = userPrefs.getTzOffset(); } navBar = "<p>Welcome, " + user.getNickname() + "! You can <a href=\"" + userService.createLogoutURL("/") + "\">sign out</a>.</p>"; tzForm = "<form action=\"/prefs\" method=\"post\">" + "<label for=\"tz_offset\">" + "Timezone offset from UTC (can be negative):" + "</label>" + "<input name=\"tz_offset\" id=\"tz_offset\" type=\"text\" size=\"4\" " + "value=\"" + tzOffset + "\" />" + "<input type=\"submit\" value=\"Set\" />" + "</form>"; fmt.setTimeZone(new SimpleTimeZone(tzOffset * 60 * 60 * 1000, "")); } resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println(navBar); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); out.println(tzForm); } }
Java
package clock; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import clock.UserPrefs; @SuppressWarnings("serial") public class PrefsServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); UserPrefs userPrefs = UserPrefs.getPrefsForUser(user); try { int tzOffset = new Integer(req.getParameter("tz_offset")).intValue(); userPrefs.setTzOffset(tzOffset); userPrefs.save(); } catch (NumberFormatException nfe) { // User entered a value that wasn't an integer. Ignore for now. } resp.sendRedirect("/"); } }
Java
package clock; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.Id; import com.google.appengine.api.users.User; import clock.EMF; import clock.UserPrefs; @Entity(name = "UserPrefs") public class UserPrefs { @Id private String userId; private int tzOffset; @Basic private User user; public UserPrefs(String userId) { this.userId = userId; } public String getUserId() { return userId; } public int getTzOffset() { return tzOffset; } public void setTzOffset(int tzOffset) { this.tzOffset = tzOffset; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public static UserPrefs getPrefsForUser(User user) { UserPrefs userPrefs = null; EntityManager em = EMF.get().createEntityManager(); try { userPrefs = em.find(UserPrefs.class, user.getUserId()); if (userPrefs == null) { userPrefs = new UserPrefs(user.getUserId()); userPrefs.setUser(user); } } finally { em.close(); } return userPrefs; } public void save() { EntityManager em = EMF.get().createEntityManager(); try { em.merge(this); } finally { em.close(); } } }
Java
package clock; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; @SuppressWarnings("serial") public class ClockServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package clock; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @SuppressWarnings("serial") public class ClockServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String navBar; if (user != null) { navBar = "<p>Welcome, " + user.getNickname() + "! You can <a href=\"" + userService.createLogoutURL("/") + "\">sign out</a>.</p>"; } else { navBar = "<p>Welcome! <a href=\"" + userService.createLoginURL("/") + "\">Sign in or register</a> to customize.</p>"; } resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println(navBar); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package bookjpa; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.google.appengine.api.datastore.Key; @Entity public class Book { // Using Long as the type of the ID works for system-assigned IDs, // but not for app-assigned key names. Also, an additional field // is needed to support ancestors. Using datastore.Key as the ID // field type supports all features of keys. @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Key key; private String title; private String author; private int copyrightYear; private Date authorBirthdate; public Key getKey() { return key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getCopyrightYear() { return copyrightYear; } public void setCopyrightYear(int copyrightYear) { this.copyrightYear = copyrightYear; } public Date getAuthorBirthdate() { return authorBirthdate; } public void setAuthorBirthdate(Date authorBirthdate) { this.authorBirthdate = authorBirthdate; } }
Java
package bookjpa; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public final class EMF { private static final EntityManagerFactory emfInstance = Persistence.createEntityManagerFactory("transactions-optional"); private EMF() {} public static EntityManagerFactory get() { return emfInstance; } }
Java
package bookjpa; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import javax.persistence.EntityManager; import javax.servlet.http.*; import com.google.appengine.api.datastore.KeyFactory; import bookjpa.EMF; import bookjpa.Book; @SuppressWarnings("serial") public class BookJpaServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); EntityManager em = EMF.get().createEntityManager(); Book book = new Book(); book.setTitle("The Grapes of Wrath"); book.setAuthor("John Steinbeck"); book.setCopyrightYear(1939); Date authorBirthdate = new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime(); book.setAuthorBirthdate(authorBirthdate); try { em.persist(book); } finally { em.close(); } // Because we're asking for a system-assigned ID in the key, // we can't access the Book's key until after the // EntityManager has closed and the Book has been saved. For // this example, we allow an exception thrown by the datastore // to propagate to the runtime environment and assume that if // we got here the Book was saved properly. out.println("<p>Added a Book entity to the datastore via JPA, key: " + KeyFactory.keyToString(book.getKey())); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package booklowlevel; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.KeyFactory; @SuppressWarnings("serial") public class BookLowLevelServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity book = new Entity("Book"); book.setProperty("title", "The Grapes of Wrath"); book.setProperty("author", "John Steinbeck"); book.setProperty("copyrightYear", 1939); Date authorBirthdate = new GregorianCalendar(1902, Calendar.FEBRUARY, 27).getTime(); book.setProperty("authorBirthdate", authorBirthdate); ds.put(book); out.println("<p>Added a Book entity to the datastore via the low-level API, key: " + KeyFactory.keyToString(book.getKey()) + "</p>"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package types; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.datastore.Blob; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.GeoPt; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.ShortBlob; import com.google.appengine.api.datastore.Text; @SuppressWarnings({ "serial", "unchecked" }) public class TypesServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity e1 = new Entity("Kind"); e1.setProperty("stringProp", "string value, limited to 500 bytes"); Text textValue = new Text("text value, can be up to 1 megabyte"); e1.setProperty("textProp", textValue); byte[] someBytes = { 107, 116, 104, 120, 98, 121, 101 }; ShortBlob shortBlobValue = new ShortBlob(someBytes); e1.setProperty("shortBlobProp", shortBlobValue); Blob blobValue = new Blob(someBytes); e1.setProperty("blobProp", blobValue); e1.setProperty("booleanProp", true); // returned as a long by the datastore e1.setProperty("integerProp", 99); e1.setProperty("floatProp", 3.14159); e1.setProperty("dateProp", new Date()); e1.setProperty("nullProp", null); GeoPt geoPtValue = new GeoPt(47.620339f, -122.349629f); e1.setProperty("geoptProp", geoPtValue); ArrayList<Object> mvp = new ArrayList<Object>(); mvp.add("string value"); mvp.add(true); mvp.add(3.14159); e1.setProperty("multivaluedProp", mvp); ds.put(e1); out.println("<p>Created an entity, key: " + KeyFactory.keyToString(e1.getKey()) + "</p>"); Entity e2 = new Entity("Kind"); e2.setProperty("keyProp", e1.getKey()); ds.put(e2); out.println("<p>Created an entity, key: " + KeyFactory.keyToString(e2.getKey()) + "</p>"); try { Entity result = ds.get(e1.getKey()); // All integer types returned as Long. Long resultIntegerPropValue = (Long) result.getProperty("integerProp"); if (resultIntegerPropValue == null) { out.println("<p>Entity didn't have a property named integerProp.</p>"); } else { out.println("<p>Entity property integerProp = " + resultIntegerPropValue + "</p>"); } // Multivalued properties returned as List. List<Object> resultMvp = (List<Object>) result.getProperty("multivaluedProp"); if (resultMvp == null) { out.println("<p>Entity didn't have a property named multivaluedProp.</p>"); } else { out.println("<p>Multivalued property values:</p><ul>"); for (Object v : resultMvp) { out.println("<li>" + v + "</li>"); } out.println("</ul>"); } } catch (EntityNotFoundException e) { out.println("<p>Attempted to get an entity, but couldn't find it: " + e + "</p>"); } ds.delete(e1.getKey()); ds.delete(e2.getKey()); out.println("<p>Entities deleted.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package entities; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Map; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; @SuppressWarnings("serial") public class EntitiesServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); // Put a new entity with a system ID Entity e1 = new Entity("Kind"); e1.setProperty("prop1", 1); ds.put(e1); out.println("<p>Created an entity with a system ID, key: " + KeyFactory.keyToString(e1.getKey()) + "</p>"); // Put a new entity with a key name Entity e2 = new Entity("Kind", "keyName"); e2.setProperty("prop1", 2); ds.put(e2); out.println("<p>Created an entity with a key name, key: " + KeyFactory.keyToString(e2.getKey()) + "</p>"); // Batch put Entity e3 = new Entity("Kind"); e3.setProperty("prop1", 3); Entity e4 = new Entity("Kind"); e4.setProperty("prop1", 4); ds.put(new ArrayList(Arrays.asList(e3, e4))); try { // Get by key Entity result; result = ds.get(e1.getKey()); out.println("<p>Retrieved an entity via key " + KeyFactory.keyToString(e1.getKey()) + ", " + "prop1 = " + result.getProperty("prop1") + "</p>"); result = ds.get(e2.getKey()); out.println("<p>Retrieved an entity via key " + KeyFactory.keyToString(e2.getKey()) + ", " + "prop1 = " + result.getProperty("prop1") + "</p>"); // Batch get Map<Key, Entity> results = ds.get(new ArrayList(Arrays.asList(e3.getKey(), e3.getKey()))); result = results.get(e3.getKey()); out.println("<p>Retrieved an entity via key " + KeyFactory.keyToString(e3.getKey()) + ", " + "prop1 = " + result.getProperty("prop1") + "</p>"); } catch (EntityNotFoundException e) { out.println("<p>Attempted to get an entity, but couldn't find it: " + e + "</p>"); } // Delete by key ds.delete(e1.getKey()); ds.delete(e2.getKey()); // Batch delete ds.delete(new ArrayList(Arrays.asList(e3.getKey(), e4.getKey()))); out.println("<p>Deleted all entities.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package tasks; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.*; @SuppressWarnings("serial") public class TaskServlet extends HttpServlet { private static final Logger log = Logger.getLogger(TaskServlet.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter("address") == null) { log.info("Task ran, no parameters"); } else { log.info("Task ran, address = " + req.getParameter("address") + ", firstname = " + req.getParameter("firstname")); } } }
Java
package tasks; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import javax.servlet.http.*; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; import com.google.appengine.api.labs.taskqueue.TaskOptions; @SuppressWarnings("serial") public class TaskEnqueueServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); /* Note: As of release 1.3.0, the Java development server has * a bug where it cannot execute tasks with default task URLs. * If you run this sample with 1.3.0, the tasks below will * enqueue fine, but will log an IllegalArgumentException: * Host name may not be null. This example runs fine on App * Engine. */ Queue queue = QueueFactory.getDefaultQueue(); queue.add(); queue.add(); queue.add(); out.println("<p>Enqueued 3 tasks to the default queue.</p>"); TaskOptions taskOptions = TaskOptions.Builder.url("/send_invitation_task") .param("address", "juliet@example.com") .param("firstname", "Juliet"); queue.add(taskOptions); out.println("<p>Enqueued 1 task to the default queue with parameters.</p>"); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS"); fmt.setTimeZone(new SimpleTimeZone(0, "")); out.println("<p>The time is: " + fmt.format(new Date()) + "</p>"); } }
Java
package cron; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.*; @SuppressWarnings("serial") public class CronDemoServlet extends HttpServlet { private static final Logger log = Logger.getLogger(CronDemoServlet.class.getName()); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("Scheduled task ran."); } }
Java
package vcard.io; import java.io.IOException; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> * 2009-02-25 ducktayp:<br> * &nbsp; New method mimeEncode(Appendable, byte[], int, String) for creating mime-compatible output.<br> * &nbsp; New method decodeInPlace(StringBuffer) for whitespace-tolerant decoding without allocating memory.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a byte array into Base64 format. * A separator is inserted after every linelength chars * @param out an StringBuffer into which output is appended. * @param in an array containing the data bytes to be encoded. * @param linelength number of characters per line * @param sep Separator placed every linelength characters. * */ public static void mimeEncode(Appendable out, byte[] in, int linelength, String sep) throws IOException { int pos = 0; int bits = 0; int val = 0; for (byte b : in) { val <<= 8; val |= ((int) b) & 0xff; bits += 8; if (bits == 24) { for (int i = 0; i < 4; ++i) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } bits = 0; val = 0; } } int pad = (3 - (bits / 8)) % 3; while (bits > 0) { out.append((char) map1[(val >>> 18) & 0x3f]); val <<= 6; bits -= 6; pos++; if (pos % linelength == 0) { out.append(sep); } } while (pad-- > 0) out.append('='); } /** * Decodes data in Base64 format in a StringBuffer. * Whitespace and invalid characters are ignored in the Base64 encoded data; * @param inout a StringBuffer containing the Base64 encoded data; Buffer is modified to contain decoded data (one byte per char) * @return new length of the StringBuffer */ public static int decodeInPlace (StringBuffer inout) { final int n = inout.length(); int pos = 0; // Writer position int val = 0; // Current byte contents int pad = 0; // Number of padding chars int bits = 0; // Number of bits decoded in val for (int i = 0; i < n; ++i) { char ch = inout.charAt(i); switch (ch) { case ' ': case '\t': case '\n': case '\r': continue; // whitespace case '=': // Padding ++pad; ch = 'A'; default: if (ch > 127) continue; // invalid char int ch2 = map2[ch]; if (ch2 < 0) continue; // invalid char // Shift val and put decoded bits into val's MSB val <<= 6; val |= ch2; bits += 6; // If we have 24 bits write them out. if (bits == 24) { bits -= 8 * pad; pad = 0; while (bits > 0) { inout.setCharAt(pos++, (char) ((val >>> 16) & 0xff)); val <<= 8; bits -= 8; } val = 0; } } } inout.setLength(pos); return pos; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". * * 2009-02-25 ducktayp: Modified to parse and format more Vcard fields, including PHOTO. * No attempt was made to preserve compatibility with previous code. * */ package vcard.io; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.UUID; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.net.Uri.Builder; import android.provider.Contacts; import android.provider.Contacts.ContactMethodsColumns; import com.funambol.util.Log; import com.funambol.util.QuotedPrintable; import com.funambol.util.StringUtil; /** * A Contact item */ public class Contact { static final String NL = "\r\n"; // Property name for Instant-message addresses static final String IMPROP = "X-IM-NICK"; // Property parameter name for custom labels static final String LABEL_PARAM = "LABEL"; // Property parameter for IM protocol static final String PROTO_PARAM = "PROTO"; // Protocol labels static final String[] PROTO = { "AIM", // ContactMethods.PROTOCOL_AIM = 0 "MSN", // ContactMethods.PROTOCOL_MSN = 1 "YAHOO", // ContactMethods.PROTOCOL_YAHOO = 2 "SKYPE", // ContactMethods.PROTOCOL_SKYPE = 3 "QQ", // ContactMethods.PROTOCOL_QQ = 4 "GTALK", // ContactMethods.PROTOCOL_GOOGLE_TALK = 5 "ICQ", // ContactMethods.PROTOCOL_ICQ = 6 "JABBER" // ContactMethods.PROTOCOL_JABBER = 7 }; long parseLen; static final String BIRTHDAY_FIELD = "Birthday:"; /** * Contact fields declaration */ // Contact identifier String _id; String syncid; // Contact displayed name String displayName; // Contact first name String firstName; // Contact last name String lastName; static class RowData { RowData(int type, String data, boolean preferred, String customLabel) { this.type = type; this.data = data; this.preferred = preferred; this.customLabel = customLabel; auxData = null; } RowData(int type, String data, boolean preferred) { this(type, data, preferred, null); } int type; String data; boolean preferred; String customLabel; String auxData; } static class OrgData { OrgData(int type, String title, String company, String customLabel) { this.type = type; this.title = title; this.company = company; this.customLabel = customLabel; } int type; // Contact title String title; // Contact company name String company; String customLabel; } // Phones dictionary; keys are android Contact Column ids List<RowData> phones; // Emails dictionary; keys are android Contact Column ids List<RowData> emails; // Address dictionary; keys are android Contact Column ids List<RowData> addrs; // Instant message addr dictionary; keys are android Contact Column ids List<RowData> ims; // Organizations list List<OrgData> orgs; // Compressed photo byte[] photo; // Contact note String notes; // Contact's birthday String birthday; Hashtable<String, handleProp> propHandlers; interface handleProp { void parseProp(final String propName, final Vector<String> propVec, final String val); } // Initializer block { reset(); propHandlers = new Hashtable<String, handleProp>(); handleProp simpleValue = new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { if (propName.equals("FN")) { displayName = val; } else if (propName.equals("NOTE")) { notes = val; } else if (propName.equals("BDAY")) { birthday = val; } else if (propName.equals("X-IRMC-LUID") || propName.equals("UID")) { syncid = val; } else if (propName.equals("N")) { String[] names = StringUtil.split(val, ";"); // We set only the first given name. // The others are ignored in input and will not be // overridden on the server in output. if (names.length >= 2) { firstName = names[1]; lastName = names[0]; } else { String[] names2 = StringUtil.split(names[0], " "); firstName = names2[0]; if (names2.length > 1) lastName = names2[1]; } } } }; propHandlers.put("FN", simpleValue); propHandlers.put("NOTE", simpleValue); propHandlers.put("BDAY", simpleValue); propHandlers.put("X-IRMC-LUID", simpleValue); propHandlers.put("UID", simpleValue); propHandlers.put("N", simpleValue); handleProp orgHandler = new handleProp() { @Override public void parseProp(String propName, Vector<String> propVec, String val) { String label = null; for (String prop : propVec) { String[] propFields = StringUtil.split(prop, "="); if (propFields[0].equalsIgnoreCase(LABEL_PARAM) && propFields.length > 1) { label = propFields[1]; } } if (propName.equals("TITLE")) { boolean setTitle = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.title == null) { org.title = val; setTitle = true; break; } } if (!setTitle) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, val, null, label)); } } else if (propName.equals("ORG")) { String[] orgFields = StringUtil.split(val, ";"); boolean setCompany = false; for (OrgData org : orgs) { if (label == null && org.customLabel != null) continue; if (label != null && !label.equals(org.customLabel)) continue; if (org.company == null) { org.company = val; setCompany = true; break; } } if (!setCompany) { orgs.add(new OrgData(label == null ? ContactMethodsColumns.TYPE_WORK : ContactMethodsColumns.TYPE_CUSTOM, null, orgFields[0], label)); } } } }; propHandlers.put("ORG", orgHandler); propHandlers.put("TITLE", orgHandler); propHandlers.put("TEL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { String label = null; int subtype = Contacts.PhonesColumns.TYPE_OTHER; boolean preferred = false; for (String prop : propVec) { if (prop.equalsIgnoreCase("HOME") || prop.equalsIgnoreCase("VOICE")) { if (subtype != Contacts.PhonesColumns.TYPE_FAX_HOME) subtype = Contacts.PhonesColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("WORK")) { if (subtype == Contacts.PhonesColumns.TYPE_FAX_HOME) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("CELL")) { subtype = Contacts.PhonesColumns.TYPE_MOBILE; } else if (prop.equalsIgnoreCase("FAX")) { if (subtype == Contacts.PhonesColumns.TYPE_WORK) { subtype = Contacts.PhonesColumns.TYPE_FAX_WORK; } else subtype = Contacts.PhonesColumns.TYPE_FAX_HOME; } else if (prop.equalsIgnoreCase("PAGER")) { subtype = Contacts.PhonesColumns.TYPE_PAGER; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } phones.add(new RowData(subtype, toCanonicalPhone(val), preferred, label)); } }); propHandlers.put("ADR", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_WORK; // vCard spec says default is WORK for (String prop : propVec) { if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else if (prop.equalsIgnoreCase("HOME")) { subtype = Contacts.ContactMethodsColumns.TYPE_HOME; } else if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } String[] addressFields = StringUtil.split(val, ";"); StringBuffer addressBuf = new StringBuffer(val.length()); if (addressFields.length > 2) { addressBuf.append(addressFields[2]); int maxLen = Math.min(7, addressFields.length); for (int i = 3; i < maxLen; ++i) { addressBuf.append(", ").append(addressFields[i]); } } String address = addressBuf.toString(); addrs.add(new RowData(subtype, address, preferred, label)); } }); propHandlers.put("EMAIL", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1 && propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; subtype = Contacts.ContactMethodsColumns.TYPE_CUSTOM; } } } emails.add(new RowData(subtype, val, preferred, label)); } }); propHandlers.put(IMPROP, new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean preferred = false; String label = null; String proto = null; int subtype = Contacts.ContactMethodsColumns.TYPE_HOME; for (String prop : propVec) { if (prop.equalsIgnoreCase("PREF")) { preferred = true; } else if (prop.equalsIgnoreCase("WORK")) { subtype = Contacts.ContactMethodsColumns.TYPE_WORK; } else { String[] propFields = StringUtil.split(prop, "="); if (propFields.length > 1) { if (propFields[0].equalsIgnoreCase(PROTO_PARAM)) { proto = propFields[1]; } else if (propFields[0].equalsIgnoreCase(LABEL_PARAM)) { label = propFields[1]; } } } } RowData newRow = new RowData(subtype, val, preferred, label); newRow.auxData = proto; ims.add(newRow); } }); propHandlers.put("PHOTO", new handleProp() { public void parseProp(final String propName, final Vector<String> propVec, final String val) { boolean isUrl = false; photo = new byte[val.length()]; for (int i = 0; i < photo.length; ++i) photo[i] = (byte) val.charAt(i); for (String prop : propVec) { if (prop.equalsIgnoreCase("VALUE=URL")) { isUrl = true; } } if (isUrl) { // TODO: Deal with photo URLS } } }); } private void reset() { _id = null; syncid = null; parseLen = 0; displayName = null; notes = null; birthday = null; photo = null; firstName = null; lastName = null; if (phones == null) phones = new ArrayList<RowData>(); else phones.clear(); if (emails == null) emails = new ArrayList<RowData>(); else emails.clear(); if (addrs == null) addrs = new ArrayList<RowData>(); else addrs.clear(); if (orgs == null) orgs = new ArrayList<OrgData>(); else orgs.clear(); if (ims == null) ims = new ArrayList<RowData>(); else ims.clear(); } SQLiteStatement querySyncId; SQLiteStatement queryPersonId; SQLiteStatement insertSyncId; // Constructors------------------------------------------------ public Contact(SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this.querySyncId = querySyncId; this.queryPersonId = queryPersionId; this.insertSyncId = insertSyncId; } public Contact(String vcard, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); BufferedReader vcardReader = new BufferedReader(new StringReader(vcard)); try { parseVCard(vcardReader); } catch (IOException e) { e.printStackTrace(); } } public Contact(BufferedReader vcfReader, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) throws IOException { this(querySyncId, queryPersionId, insertSyncId); parseVCard(vcfReader); } public Contact(Cursor peopleCur, ContentResolver cResolver, SQLiteStatement querySyncId, SQLiteStatement queryPersionId, SQLiteStatement insertSyncId) { this(querySyncId, queryPersionId, insertSyncId); populate(peopleCur, cResolver); } final static Pattern[] phonePatterns = { Pattern.compile("[+](1)(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), Pattern.compile("[+](972)(2|3|4|8|9|50|52|54|57|59|77)(\\d\\d\\d)(\\d\\d\\d\\d.*)"), }; /** * Change the phone to canonical format (with dashes, etc.) if it's in a supported country. * @param phone * @return */ String toCanonicalPhone(String phone) { for (final Pattern phonePattern : phonePatterns) { Matcher m = phonePattern.matcher(phone); if (m.matches()) { return "+" + m.group(1) + "-" + m.group(2) + "-" + m.group(3) + "-" + m.group(4); } } return phone; } /** * Set the person identifier */ public void setId(String id) { _id = id; } /** * Get the person identifier */ public long getId() { return Long.parseLong(_id); } final static Pattern beginPattern = Pattern.compile("BEGIN:VCARD",Pattern.CASE_INSENSITIVE); final static Pattern propPattern = Pattern.compile("([^:]+):(.*)"); final static Pattern propParamPattern = Pattern.compile("([^;=]+)(=([^;]+))?(;|$)"); final static Pattern base64Pattern = Pattern.compile("\\s*([a-zA-Z0-9+/]+={0,2})\\s*$"); final static Pattern namePattern = Pattern.compile("(([^,]+),(.*))|((.*?)\\s+(\\S+))"); // Parse birthday in notes final static Pattern birthdayPattern = Pattern.compile("^" + BIRTHDAY_FIELD + ":\\s*([^;]+)(;\\s*|\\s*$)",Pattern.CASE_INSENSITIVE); /** * Parse the vCard string into the contacts fields */ public long parseVCard(BufferedReader vCard) throws IOException { // Reset the currently read values. reset(); // Find Begin. String line = vCard.readLine(); if (line != null) parseLen += line.length(); else return -1; while (line != null && !beginPattern.matcher(line).matches()) { line = vCard.readLine(); parseLen += line.length(); } if (line == null) return -1; boolean skipRead = false; while (line != null) { if (!skipRead) line = vCard.readLine(); if (line == null) { return 0; } skipRead = false; // do multi-line unfolding (cr lf with whitespace immediately following is removed, joining the two lines). vCard.mark(1); for (int ch = vCard.read(); ch == (int) ' ' || ch == (int) '\t'; ch = vCard.read()) { vCard.reset(); String newLine = vCard.readLine(); if (newLine != null) line += newLine; vCard.mark(1); } vCard.reset(); parseLen += line.length(); // TODO: doesn't include CR LFs Matcher pm = propPattern.matcher(line); if (pm.matches()) { String prop = pm.group(1); String val = pm.group(2); if (prop.equalsIgnoreCase("END") && val.equalsIgnoreCase("VCARD")) { // End of vCard return parseLen; } Matcher ppm = propParamPattern.matcher(prop); if (!ppm.find()) // Doesn't seem to be a valid vCard property continue; String propName = ppm.group(1).toUpperCase(); Vector<String> propVec = new Vector<String>(); String charSet = "UTF-8"; String encoding = ""; while (ppm.find()) { String param = ppm.group(1); String paramVal = ppm.group(3); propVec.add(param + (paramVal != null ? "=" + paramVal : "")); if (param.equalsIgnoreCase("CHARSET")) charSet = paramVal; else if (param.equalsIgnoreCase("ENCODING")) encoding = paramVal; } if (encoding.equalsIgnoreCase("QUOTED-PRINTABLE")) { try { val = QuotedPrintable.decode(val.getBytes(charSet), "UTF-8"); } catch (UnsupportedEncodingException uee) { } } else if (encoding.equalsIgnoreCase("BASE64")) { StringBuffer tmpVal = new StringBuffer(val); do { line = vCard.readLine(); if ((line == null) || (line.length() == 0) || (!base64Pattern.matcher(line).matches())) { //skipRead = true; break; } tmpVal.append(line); } while (true); Base64Coder.decodeInPlace(tmpVal); val = tmpVal.toString(); } handleProp propHandler = propHandlers.get(propName); if (propHandler != null) propHandler.parseProp(propName, propVec, val); } } return 0; } public long getParseLen() { return parseLen; } /** * Format an email as a vCard field. * * @param cardBuff Formatted email will be appended to this buffer * @param email The rowdata containing the actual email data. */ public static void formatEmail(Appendable cardBuff, RowData email) throws IOException { cardBuff.append("EMAIL;INTERNET"); if (email.preferred) cardBuff.append(";PREF"); if (email.customLabel != null) { cardBuff.append(";" + LABEL_PARAM + "="); cardBuff.append(email.customLabel); } switch (email.type) { case Contacts.ContactMethodsColumns.TYPE_WORK: cardBuff.append(";WORK"); break; } if (!StringUtil.isASCII(email.data)) cardBuff.append(";CHARSET=UTF-8"); cardBuff.append(":").append(email.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param phone The rowdata containing the actual phone data. */ public static void formatPhone(Appendable formatted, RowData phone) throws IOException { formatted.append("TEL"); if (phone.preferred) formatted.append(";PREF"); if (phone.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(phone.customLabel); } switch (phone.type) { case Contacts.PhonesColumns.TYPE_HOME: formatted.append(";VOICE"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";VOICE;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_WORK: formatted.append(";FAX;WORK"); break; case Contacts.PhonesColumns.TYPE_FAX_HOME: formatted.append(";FAX;HOME"); break; case Contacts.PhonesColumns.TYPE_MOBILE: formatted.append(";CELL"); break; case Contacts.PhonesColumns.TYPE_PAGER: formatted.append(";PAGER"); break; } if (!StringUtil.isASCII(phone.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(phone.data.trim()).append(NL); } /** * Format a phone as a vCard field. * * @param formatted Formatted phone will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatAddr(Appendable formatted, RowData addr) throws IOException { formatted.append("ADR"); if (addr.preferred) formatted.append(";PREF"); if (addr.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(addr.customLabel); } switch (addr.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.PhonesColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (!StringUtil.isASCII(addr.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":;;").append(addr.data.replace(", ", ";").trim()).append(NL); } /** * Format an IM contact as a vCard field. * * @param formatted Formatted im contact will be appended to this buffer * @param addr The rowdata containing the actual phone data. */ public static void formatIM(Appendable formatted, RowData im) throws IOException { formatted.append(IMPROP); if (im.preferred) formatted.append(";PREF"); if (im.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(im.customLabel); } switch (im.type) { case Contacts.ContactMethodsColumns.TYPE_HOME: formatted.append(";HOME"); break; case Contacts.ContactMethodsColumns.TYPE_WORK: formatted.append(";WORK"); break; } if (im.auxData != null) { formatted.append(";").append(PROTO_PARAM).append("=").append(im.auxData); } if (!StringUtil.isASCII(im.data)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(im.data.trim()).append(NL); } /** * Format Organization fields. * * * * @param formatted Formatted organization info will be appended to this buffer * @param addr The rowdata containing the actual organization data. */ public static void formatOrg(Appendable formatted, OrgData org) throws IOException { if (org.company != null) { formatted.append("ORG"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.company)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.company.trim()).append(NL); if (org.title == null) formatted.append("TITLE:").append(NL); } if (org.title != null) { if (org.company == null) formatted.append("ORG:").append(NL); formatted.append("TITLE"); if (org.customLabel != null) { formatted.append(";" + LABEL_PARAM + "="); formatted.append(org.customLabel); } if (!StringUtil.isASCII(org.title)) formatted.append(";CHARSET=UTF-8"); formatted.append(":").append(org.title.trim()).append(NL); } } public String toString() { StringWriter out = new StringWriter(); try { writeVCard(out); } catch (IOException e) { // Should never happen } return out.toString(); } /** * Write the contact vCard to an appendable stream. */ public void writeVCard(Appendable vCardBuff) throws IOException { // Start vCard vCardBuff.append("BEGIN:VCARD").append(NL); vCardBuff.append("VERSION:2.1").append(NL); appendField(vCardBuff, "X-IRMC-LUID", syncid); vCardBuff.append("N"); if (!StringUtil.isASCII(lastName) || !StringUtil.isASCII(firstName)) vCardBuff.append(";CHARSET=UTF-8"); vCardBuff.append(":").append((lastName != null) ? lastName.trim() : "") .append(";").append((firstName != null) ? firstName.trim() : "") .append(";").append(";").append(";").append(NL); for (RowData email : emails) { formatEmail(vCardBuff, email); } for (RowData phone : phones) { formatPhone(vCardBuff, phone); } for (OrgData org : orgs) { formatOrg(vCardBuff, org); } for (RowData addr : addrs) { formatAddr(vCardBuff, addr); } for (RowData im : ims) { formatIM(vCardBuff, im); } appendField(vCardBuff, "NOTE", notes); appendField(vCardBuff, "BDAY", birthday); if (photo != null) { appendField(vCardBuff, "PHOTO;TYPE=JPEG;ENCODING=BASE64", " "); Base64Coder.mimeEncode(vCardBuff, photo, 76, NL); vCardBuff.append(NL); vCardBuff.append(NL); } // End vCard vCardBuff.append("END:VCARD").append(NL); } /** * Append the field to the StringBuffer out if not null. */ private static void appendField(Appendable out, String name, String val) throws IOException { if(val != null && val.length() > 0) { out.append(name); if (!StringUtil.isASCII(val)) out.append(";CHARSET=UTF-8"); out.append(":").append(val).append(NL); } } /** * Populate the contact fields from a cursor */ public void populate(Cursor peopleCur, ContentResolver cResolver) { reset(); setPeopleFields(peopleCur); String personID = _id; if (querySyncId != null) { querySyncId.bindString(1, personID); try { syncid = querySyncId.simpleQueryForString(); } catch (SQLiteDoneException e) { if (insertSyncId != null) { // Create a new syncid syncid = UUID.randomUUID().toString(); // Write the new syncid insertSyncId.bindString(1, personID); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } } } Cursor organization = cResolver.query(Contacts.Organizations.CONTENT_URI, null, Contacts.OrganizationColumns.PERSON_ID + "=" + personID, null, null); // Set the organization fields if (organization.moveToFirst()) { do { setOrganizationFields(organization); } while (organization.moveToNext()); } organization.close(); Cursor phones = cResolver.query(Contacts.Phones.CONTENT_URI, null, Contacts.Phones.PERSON_ID + "=" + personID, null, null); // Set all the phone numbers if (phones.moveToFirst()) { do { setPhoneFields(phones); } while (phones.moveToNext()); } phones.close(); Cursor contactMethods = cResolver.query(Contacts.ContactMethods.CONTENT_URI, null, Contacts.ContactMethods.PERSON_ID + "=" + personID, null, null); // Set all the contact methods (emails, addresses, ims) if (contactMethods.moveToFirst()) { do { setContactMethodsFields(contactMethods); } while (contactMethods.moveToNext()); } contactMethods.close(); // Load a photo if one exists. Cursor contactPhoto = cResolver.query(Contacts.Photos.CONTENT_URI, null, Contacts.PhotosColumns.PERSON_ID + "=" + personID, null, null); if (contactPhoto.moveToFirst()) { photo = contactPhoto.getBlob(contactPhoto.getColumnIndex(Contacts.PhotosColumns.DATA)); } contactPhoto.close(); } /** * Retrieve the People fields from a Cursor */ private void setPeopleFields(Cursor cur) { int selectedColumn; // Set the contact id selectedColumn = cur.getColumnIndex(Contacts.People._ID); long nid = cur.getLong(selectedColumn); _id = String.valueOf(nid); // // Get PeopleColumns fields // selectedColumn = cur.getColumnIndex(Contacts.PeopleColumns.NAME); displayName = cur.getString(selectedColumn); if (displayName != null) { Matcher m = namePattern.matcher(displayName); if (m.matches()) { if (m.group(1) != null) { lastName = m.group(2); firstName = m.group(3); } else { firstName = m.group(5); lastName = m.group(6); } } else { firstName = displayName; lastName = ""; } } else { firstName = lastName = ""; } selectedColumn = cur.getColumnIndex(Contacts.People.NOTES); notes = cur.getString(selectedColumn); if (notes != null) { Matcher ppm = birthdayPattern.matcher(notes); if (ppm.find()) { birthday = ppm.group(1); notes = ppm.replaceFirst(""); } } } /** * Retrieve the organization fields from a Cursor */ private void setOrganizationFields(Cursor cur) { int selectedColumn; // // Get Organizations fields // selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.COMPANY); String company = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TITLE); String title = cur.getString(selectedColumn); selectedColumn = cur.getColumnIndex(Contacts.OrganizationColumns.TYPE); int orgType = cur.getInt(selectedColumn); String customLabel = null; if (orgType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumn); } orgs.add(new OrgData(orgType, title, company, customLabel)); } /** * Retrieve the Phone fields from a Cursor */ private void setPhoneFields(Cursor cur) { int selectedColumn; int selectedColumnType; int preferredColumn; int phoneType; String customLabel = null; // // Get PhonesColums fields // selectedColumn = cur.getColumnIndex(Contacts.PhonesColumns.NUMBER); selectedColumnType = cur.getColumnIndex(Contacts.PhonesColumns.TYPE); preferredColumn = cur.getColumnIndex(Contacts.PhonesColumns.ISPRIMARY); phoneType = cur.getInt(selectedColumnType); String phone = cur.getString(selectedColumn); boolean preferred = cur.getInt(preferredColumn) != 0; if (phoneType == Contacts.PhonesColumns.TYPE_CUSTOM) { customLabel = cur.getString(cur.getColumnIndex(Contacts.PhonesColumns.LABEL)); } phones.add(new RowData(phoneType, phone, preferred, customLabel)); } /** * Retrieve the email fields from a Cursor */ private void setContactMethodsFields(Cursor cur) { int selectedColumn; int selectedColumnType; int selectedColumnKind; int selectedColumnPrimary; int selectedColumnLabel; int methodType; int kind; String customLabel = null; String auxData = null; // // Get ContactsMethodsColums fields // selectedColumn = cur .getColumnIndex(Contacts.ContactMethodsColumns.DATA); selectedColumnType = cur .getColumnIndex(Contacts.ContactMethodsColumns.TYPE); selectedColumnKind = cur .getColumnIndex(Contacts.ContactMethodsColumns.KIND); selectedColumnPrimary = cur .getColumnIndex(Contacts.ContactMethodsColumns.ISPRIMARY); kind = cur.getInt(selectedColumnKind); methodType = cur.getInt(selectedColumnType); String methodData = cur.getString(selectedColumn); boolean preferred = cur.getInt(selectedColumnPrimary) != 0; if (methodType == Contacts.ContactMethodsColumns.TYPE_CUSTOM) { selectedColumnLabel = cur .getColumnIndex(Contacts.ContactMethodsColumns.LABEL); customLabel = cur.getString(selectedColumnLabel); } switch (kind) { case Contacts.KIND_EMAIL: emails.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_POSTAL: addrs.add(new RowData(methodType, methodData, preferred, customLabel)); break; case Contacts.KIND_IM: RowData newRow = new RowData(methodType, methodData, preferred, customLabel); selectedColumn = cur.getColumnIndex(Contacts.ContactMethodsColumns.AUX_DATA); auxData = cur.getString(selectedColumn); if (auxData != null) { String[] auxFields = StringUtil.split(auxData, ":"); if (auxFields.length > 1) { if (auxFields[0].equalsIgnoreCase("pre")) { int protval = 0; try { protval = Integer.decode(auxFields[1]); } catch (NumberFormatException e) { // Do nothing; protval = 0 } if (protval < 0 || protval >= PROTO.length) protval = 0; newRow.auxData = PROTO[protval]; } else if (auxFields[0].equalsIgnoreCase("custom")) { newRow.auxData = auxFields[1]; } } else { newRow.auxData = auxData; } } ims.add(newRow); break; } } public ContentValues getPeopleCV() { ContentValues cv = new ContentValues(); StringBuffer fullname = new StringBuffer(); if (displayName != null) fullname.append(displayName); else { if (firstName != null) fullname.append(firstName); if (lastName != null) { if (firstName != null) fullname.append(" "); fullname.append(lastName); } } // Use company name if only the company is given. if (fullname.length() == 0 && orgs.size() > 0 && orgs.get(0).company != null) fullname.append(orgs.get(0).company); cv.put(Contacts.People.NAME, fullname.toString()); if (!StringUtil.isNullOrEmpty(_id)) { cv.put(Contacts.People._ID, _id); } StringBuffer allnotes = new StringBuffer(); if (birthday != null) { allnotes.append(BIRTHDAY_FIELD).append(" ").append(birthday); } if (notes != null) { if (birthday != null) { allnotes.append(";\n"); } allnotes.append(notes); } if (allnotes.length() > 0) cv.put(Contacts.People.NOTES, allnotes.toString()); return cv; } public ContentValues getOrganizationCV(OrgData org) { if(StringUtil.isNullOrEmpty(org.company) && StringUtil.isNullOrEmpty(org.title)) { return null; } ContentValues cv = new ContentValues(); cv.put(Contacts.Organizations.COMPANY, org.company); cv.put(Contacts.Organizations.TITLE, org.title); cv.put(Contacts.Organizations.TYPE, org.type); cv.put(Contacts.Organizations.PERSON_ID, _id); if (org.customLabel != null) { cv.put(Contacts.Organizations.LABEL, org.customLabel); } return cv; } public ContentValues getPhoneCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.Phones.NUMBER, data.data); cv.put(Contacts.Phones.TYPE, data.type); cv.put(Contacts.Phones.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.Phones.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.Phones.LABEL, data.customLabel); } return cv; } public ContentValues getEmailCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getAddressCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } return cv; } public ContentValues getImCV(RowData data) { ContentValues cv = new ContentValues(); cv.put(Contacts.ContactMethods.DATA, data.data); cv.put(Contacts.ContactMethods.TYPE, data.type); cv.put(Contacts.ContactMethods.KIND, Contacts.KIND_IM); cv.put(Contacts.ContactMethods.ISPRIMARY, data.preferred ? 1 : 0); cv.put(Contacts.ContactMethods.PERSON_ID, _id); if (data.customLabel != null) { cv.put(Contacts.ContactMethods.LABEL, data.customLabel); } if (data.auxData != null) { int protoNum = -1; for (int i = 0; i < PROTO.length; ++i) { if (data.auxData.equalsIgnoreCase(PROTO[i])) { protoNum = i; break; } } if (protoNum >= 0) { cv.put(Contacts.ContactMethods.AUX_DATA, "pre:"+protoNum); } else { cv.put(Contacts.ContactMethods.AUX_DATA, "custom:"+data.auxData); } } return cv; } /** * Add a new contact to the Content Resolver * * @param key the row number of the existing contact (if known) * @return The row number of the inserted column */ public long addContact(Context context, long key, boolean replace) { ContentResolver cResolver = context.getContentResolver(); ContentValues pCV = getPeopleCV(); boolean addSyncId = false; boolean replacing = false; if (key <= 0 && syncid != null) { if (queryPersonId != null) try { queryPersonId.bindString(1, syncid); setId(queryPersonId.simpleQueryForString()); key = getId(); } catch(SQLiteDoneException e) { // Couldn't locate syncid, we'll add it; // need to wait until we know what the key is, though. addSyncId = true; } } Uri newContactUri = null; if (key > 0) { newContactUri = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Cursor testit = cResolver.query(newContactUri, null, null, null, null); if (testit == null || testit.getCount() == 0) { newContactUri = null; pCV.put(Contacts.People._ID, key); } if (testit != null) testit.close(); } if (newContactUri == null) { newContactUri = insertContentValues(cResolver, Contacts.People.CONTENT_URI, pCV); if (newContactUri == null) { Log.error("Error adding contact." + " (key: " + key + ")"); return -1; } // Set the contact person id setId(newContactUri.getLastPathSegment()); key = getId(); // Add the new contact to the myContacts group Contacts.People.addToMyContactsGroup(cResolver, key); } else { // update existing Uri if (!replace) return -1; replacing = true; cResolver.update(newContactUri, pCV, null, null); } // We need to add the syncid to the database so // that we'll detect this contact if we try to import // it again. if (addSyncId && insertSyncId != null) { insertSyncId.bindLong(1, key); insertSyncId.bindString(2, syncid); insertSyncId.executeInsert(); } /* * Insert all the new ContentValues */ if (replacing) { // Remove existing phones Uri phones = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.Phones.CONTENT_DIRECTORY); String[] phoneID = {Contacts.People.Phones._ID}; Cursor existingPhones = cResolver.query(phones, phoneID, null, null, null); if (existingPhones != null && existingPhones.moveToFirst()) { int idColumn = existingPhones.getColumnIndex(Contacts.People.Phones._ID); List<Long> ids = new ArrayList<Long>(existingPhones.getCount()); do { ids.add(existingPhones.getLong(idColumn)); } while (existingPhones.moveToNext()); existingPhones.close(); for (Long id : ids) { Uri phone = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(phone, null, null); } } // Remove existing contact methods (emails, addresses, etc.) Uri methods = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key), Contacts.People.ContactMethods.CONTENT_DIRECTORY); String[] methodID = {Contacts.People.ContactMethods._ID}; Cursor existingMethods = cResolver.query(methods, methodID, null, null, null); if (existingMethods != null && existingMethods.moveToFirst()) { int idColumn = existingMethods.getColumnIndex(Contacts.People.ContactMethods._ID); List<Long> ids = new ArrayList<Long>(existingMethods.getCount()); do { ids.add(existingMethods.getLong(idColumn)); } while (existingMethods.moveToNext()); existingMethods.close(); for (Long id : ids) { Uri method = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, id); cResolver.delete(method, null, null); } } } // Phones for (RowData phone : phones) { insertContentValues(cResolver, Contacts.Phones.CONTENT_URI, getPhoneCV(phone)); } // Organizations for (OrgData org : orgs) { insertContentValues(cResolver, Contacts.Organizations.CONTENT_URI, getOrganizationCV(org)); } Builder builder = newContactUri.buildUpon(); builder.appendEncodedPath(Contacts.ContactMethods.CONTENT_URI.getPath()); // Emails for (RowData email : emails) { insertContentValues(cResolver, builder.build(), getEmailCV(email)); } // Addressess for (RowData addr : addrs) { insertContentValues(cResolver, builder.build(), getAddressCV(addr)); } // IMs for (RowData im : ims) { insertContentValues(cResolver, builder.build(), getImCV(im)); } // Photo if (photo != null) { Uri person = ContentUris.withAppendedId(Contacts.People.CONTENT_URI, key); Contacts.People.setPhotoData(cResolver, person, photo); } return key; } /** * Insert a new ContentValues raw into the Android ContentProvider */ private Uri insertContentValues(ContentResolver cResolver, Uri uri, ContentValues cv) { if (cv != null) { return cResolver.insert(uri, cv); } return null; } /** * Get the item content */ public String getContent() { return toString(); } /** * Check if the email string is well formatted */ @SuppressWarnings("unused") private boolean checkEmail(String email) { return (email != null && !"".equals(email) && email.indexOf("@") != -1); } }
Java
package vcard.io; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class App extends Activity { /** Called when the activity is first created. */ boolean isActive; Handler mHandler = new Handler(); VCardIO mBoundService = null; int mLastProgress; TextView mStatusText = null; CheckBox mReplaceOnImport = null; @Override protected void onPause() { isActive = false; super.onPause(); } @Override protected void onResume() { super.onResume(); isActive = true; updateProgress(mLastProgress); } protected void updateProgress(final int progress) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { setProgress(progress * 100); if (progress == 100) mStatusText.setText("Done"); } else { mLastProgress = progress; } } }); } void updateStatus(final String status) { // Update the progress bar mHandler.post(new Runnable() { public void run() { if (isActive) { mStatusText.setText(status); } } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_PROGRESS); setProgress(10000); // Turn it off for now setContentView(R.layout.main); Button importButton = (Button) findViewById(R.id.ImportButton); Button exportButton = (Button) findViewById(R.id.ExportButton); mStatusText = ((TextView) findViewById(R.id.StatusText)); mReplaceOnImport = ((CheckBox) findViewById(R.id.ReplaceOnImport)); final Intent app = new Intent(App.this, VCardIO.class); OnClickListener listenImport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ImportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Importing Contacts..."); // Start the import mBoundService.doImport(fileName, mReplaceOnImport.isChecked(), App.this); } } }; OnClickListener listenExport = new OnClickListener() { public void onClick(View v) { // Make sure the service is started. It will continue running // until someone calls stopService(). The Intent we use to find // the service explicitly specifies our service component, because // we want it running in our own process and don't want other // applications to replace it. if (mBoundService != null) { String fileName = ((EditText) findViewById(R.id.ExportFile)).getText().toString(); // Update the progress bar setProgress(0); mStatusText.setText("Exporting Contacts..."); // Start the import mBoundService.doExport(fileName, App.this); } } }; // Start the service using startService so it won't be stopped when activity is in background. startService(app); bindService(app, mConnection, Context.BIND_AUTO_CREATE); importButton.setOnClickListener(listenImport); exportButton.setOnClickListener(listenExport); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = ((VCardIO.LocalBinder)service).getService(); // Tell the user about this for our demo. Toast.makeText(App.this, "Connected to VCard IO Service", Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; Toast.makeText(App.this, "Disconnected from VCard IO!", Toast.LENGTH_SHORT).show(); } }; }
Java
package vcard.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; import android.os.Binder; import android.os.IBinder; import android.provider.Contacts; import android.widget.Toast; public class VCardIO extends Service { static final String DATABASE_NAME = "syncdata.db"; static final String SYNCDATA_TABLE_NAME = "sync"; static final String PERSONID = "person"; static final String SYNCID = "syncid"; private static final int DATABASE_VERSION = 1; private NotificationManager mNM; final Object syncMonitor = "SyncMonitor"; String syncFileName; enum Action { IDLE, IMPORT, EXPORT }; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + SYNCDATA_TABLE_NAME + " (" + PERSONID + " INTEGER PRIMARY KEY," + SYNCID + " TEXT UNIQUE" +");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // No need to do anything --- this is version 1 } } private DatabaseHelper mOpenHelper; Action mAction; public class LocalBinder extends Binder { VCardIO getService() { return VCardIO.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); @Override public void onCreate() { mOpenHelper = new DatabaseHelper(getApplicationContext()); mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mAction = Action.IDLE; // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancelAll(); synchronized (syncMonitor) { switch (mAction) { case IMPORT: // Tell the user we stopped. Toast.makeText(this, "VCard import aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; case EXPORT: // Tell the user we stopped. Toast.makeText(this, "VCard export aborted ("+syncFileName +")", Toast.LENGTH_SHORT).show(); break; default: break; } mAction = Action.IDLE; } } /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification String text = null; String detailedText = ""; synchronized (syncMonitor) { switch (mAction) { case IMPORT: text = (String) getText(R.string.importServiceMsg); detailedText = "Importing VCards from " + syncFileName; break; case EXPORT: text = (String) getText(R.string.exportServiceMsg); detailedText = "Exporting VCards from " + syncFileName; break; default: break; } } if (text == null) { mNM.cancelAll(); } else { // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.status_icon, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, App.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, "VCard IO", detailedText, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.app_name, notification); } } public void doImport(final String fileName, final boolean replace, final App app) { try { File vcfFile = new File(fileName); final BufferedReader vcfBuffer = new BufferedReader(new FileReader(fileName)); final long maxlen = vcfFile.length(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long importStatus = 0; synchronized (syncMonitor) { mAction = Action.IMPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { long ret = 0; do { ret = parseContact.parseVCard(vcfBuffer); if (ret >= 0) { parseContact.addContact(getApplicationContext(), 0, replace); importStatus += parseContact.getParseLen(); // Update the progress bar app.updateProgress((int) (100 * importStatus / maxlen)); } } while (ret > 0); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { } } }).start(); } catch (FileNotFoundException e) { app.updateStatus("File not found: " + e.getMessage()); } } public void doExport(final String fileName, final App app) { try { final BufferedWriter vcfBuffer = new BufferedWriter(new FileWriter(fileName)); final ContentResolver cResolver = getContentResolver(); final Cursor allContacts = cResolver.query(Contacts.People.CONTENT_URI, null, null, null, null); if (allContacts == null || !allContacts.moveToFirst()) { app.updateStatus("No contacts found"); allContacts.close(); return; } final long maxlen = allContacts.getCount(); // Start lengthy operation in a background thread new Thread(new Runnable() { public void run() { long exportStatus = 0; synchronized (syncMonitor) { mAction = Action.EXPORT; syncFileName = fileName; } showNotification(); SQLiteDatabase db = mOpenHelper.getWritableDatabase(); SQLiteStatement querySyncId = db.compileStatement("SELECT " + SYNCID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + PERSONID + "=?"); SQLiteStatement queryPersonId = db.compileStatement("SELECT " + PERSONID + " FROM " + SYNCDATA_TABLE_NAME + " WHERE " + SYNCID + "=?"); SQLiteStatement insertSyncId = db.compileStatement("INSERT INTO " + SYNCDATA_TABLE_NAME + " (" + PERSONID + "," + SYNCID + ") VALUES (?,?)"); Contact parseContact = new Contact(querySyncId, queryPersonId, insertSyncId); try { boolean hasNext = true; do { parseContact.populate(allContacts, cResolver); parseContact.writeVCard(vcfBuffer); ++exportStatus; // Update the progress bar app.updateProgress((int) (100 * exportStatus / maxlen)); hasNext = allContacts.moveToNext(); } while (hasNext); vcfBuffer.close(); db.close(); app.updateProgress(100); synchronized (syncMonitor) { mAction = Action.IDLE; showNotification(); } stopSelf(); } catch (IOException e) { app.updateStatus("Write error: " + e.getMessage()); } } }).start(); } catch (IOException e) { app.updateStatus("Error opening file: " + e.getMessage()); } } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Vector; /** * Utility class useful when dealing with string objects. * This class is a collection of static functions, and the usage is: * * StringUtil.method() * * it is not allowed to create instances of this class */ public class StringUtil { private static final String HT = "\t"; private static final String CRLF = "\r\n"; // This class cannot be instantiated private StringUtil() { } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param s the string to tokenize * @param sep a list of separator to use * * @return the array of tokens (an array of size 1 with the original * string if no separator found) */ public static String[] split(String s, String sep) { // convert a String s to an Array, the elements // are delimited by sep Vector<Integer> tokenIndex = new Vector<Integer>(10); int len = s.length(); int i; // Find all characters in string matching one of the separators in 'sep' for (i = 0; i < len; i++) { if (sep.indexOf(s.charAt(i)) != -1 ){ tokenIndex.addElement(new Integer(i)); } } int size = tokenIndex.size(); String[] elements = new String[size+1]; // No separators: return the string as the first element if(size == 0) { elements[0] = s; } else { // Init indexes int start = 0; int end = (tokenIndex.elementAt(0)).intValue(); // Get the first token elements[0] = s.substring(start, end); // Get the mid tokens for (i=1; i<size; i++) { // update indexes start = (tokenIndex.elementAt(i-1)).intValue()+1; end = (tokenIndex.elementAt(i)).intValue(); elements[i] = s.substring(start, end); } // Get last token start = (tokenIndex.elementAt(i-1)).intValue()+1; elements[i] = (start < s.length()) ? s.substring(start) : ""; } return elements; } /** * Split the string into an array of strings using one of the separator * in 'sep'. * * @param list the string array to join * @param sep the separator to use * * @return the joined string */ public static String join(String[] list, String sep) { StringBuffer buffer = new StringBuffer(list[0]); int len = list.length; for (int i = 1; i < len; i++) { buffer.append(sep).append(list[i]); } return buffer.toString(); } /** * Returns the string array * @param stringVec the Vecrot of tring to convert * @return String [] */ public static String[] getStringArray(Vector<String> stringVec){ if(stringVec==null){ return null; } String[] stringArray=new String[stringVec.size()]; for(int i=0;i<stringVec.size();i++){ stringArray[i]=stringVec.elementAt(i); } return stringArray; } /** * Find two consecutive newlines in a string. * @param s - The string to search * @return int: the position of the empty line */ public static int findEmptyLine(String s){ int ret = 0; // Find a newline while( (ret = s.indexOf("\n", ret)) != -1 ){ // Skip carriage returns, if any while(s.charAt(ret) == '\r'){ ret++; } if(s.charAt(ret) == '\n'){ // Okay, it was empty ret ++; break; } } return ret; } /** * Removes unwanted blank characters * @param content * @return String */ public static String removeBlanks(String content){ if(content==null){ return null; } StringBuffer buff = new StringBuffer(); buff.append(content); for(int i = buff.length()-1; i >= 0;i--){ if(' ' == buff.charAt(i)){ buff.deleteCharAt(i); } } return buff.toString(); } /** * Removes unwanted backslashes characters * * @param content The string containing the backslashes to be removed * @return the content without backslashes */ public static String removeBackslashes(String content){ if (content == null) { return null; } StringBuffer buff = new StringBuffer(); buff.append(content); int len = buff.length(); for (int i = len - 1; i >= 0; i--) { if ('\\' == buff.charAt(i)) buff.deleteCharAt(i); } return buff.toString(); } /** * Builds a list of the recipients email addresses each on a different line, * starting just from the second line with an HT ("\t") separator at the * head of the line. This is an implementation of the 'folding' concept from * the RFC 2822 (par. 2.2.3) * * @param recipients * A string containing all recipients comma-separated * @return A string containing the email list of the recipients spread over * more lines, ended by CRLF and beginning from the second with the * WSP defined in the RFC 2822 */ public static String fold(String recipients) { String[] list = StringUtil.split(recipients, ","); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { String address = list[i] + (i != list.length - 1 ? "," : ""); buffer.append(i == 0 ? address + CRLF : HT + address + CRLF); } return buffer.toString(); } /** * This method is missing in CLDC 1.0 String implementation */ public static boolean equalsIgnoreCase(String string1, String string2) { // Strings are both null, return true if (string1 == null && string2 == null) { return true; } // One of the two is null, return false if (string1 == null || string2 == null) { return false; } // Both are not null, compare the lowercase strings if ((string1.toLowerCase()).equals(string2.toLowerCase())) { return true; } else { return false; } } /** * Util method for retrieve a boolean primitive type from a String. * Implemented because Boolean class doesn't provide * parseBoolean() method */ public static boolean getBooleanValue(String string) { if ((string == null) || string.equals("")) { return false; } else { if (StringUtil.equalsIgnoreCase(string, "true")) { return true; } else { return false; } } } /** * Removes characters 'c' from the beginning and the end of the string */ public static String trim(String s, char c) { int start = 0; int end = s.length()-1; while(s.charAt(start) == c) { if(++start >= end) { // The string is made by c only return ""; } } while(s.charAt(end) == c) { if(--end <= start) { return ""; } } return s.substring(start, end+1); } /** * Returns true if the given string is null or empty. */ public static boolean isNullOrEmpty(String str) { if (str==null) { return true; } if (str.trim().equals("")) { return true; } return false; } /** * Returns true if the string does not fit in standard ASCII */ public static boolean isASCII(String str) { if (str == null) return true; for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c < 0 || c > 0x7f) return false; } return true; } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.io.UnsupportedEncodingException; /** * A class containing static methods to perform decoding from <b>quoted * printable</b> content transfer encoding and to encode into */ public class QuotedPrintable { private static byte HT = 0x09; // \t private static byte LF = 0x0A; // \n private static byte CR = 0x0D; // \r /** * A method to decode quoted printable encoded data. * It overrides the same input byte array to save memory. Can be done * because the result is surely smaller than the input. * * @param qp * a byte array to decode. * @return the length of the decoded array. */ public static int decode(byte [] qp) { int qplen = qp.length; int retlen = 0; for (int i=0; i < qplen; i++) { // Handle encoded chars if (qp[i] == '=') { if (qplen - i > 2) { // The sequence can be complete, check it if (qp[i+1] == CR && qp[i+2] == LF) { // soft line break, ignore it i += 2; continue; } else if (isHexDigit(qp[i+1]) && isHexDigit(qp[i+2]) ) { // convert the number into an integer, taking // the ascii digits stored in the array. qp[retlen++]=(byte)(getHexValue(qp[i+1])*16 + getHexValue(qp[i+2])); i += 2; continue; } else { Log.error("decode: Invalid sequence = " + qp[i+1] + qp[i+2]); } } // In all wrong cases leave the original bytes // (see RFC 2045). They can be incomplete sequence, // or a '=' followed by non hex digit. } // RFC 2045 says to exclude control characters mistakenly // present (unencoded) in the encoded stream. // As an exception, we keep unencoded tabs (0x09) if( (qp[i] >= 0x20 && qp[i] <= 0x7f) || qp[i] == HT || qp[i] == CR || qp[i] == LF) { qp[retlen++] = qp[i]; } } return retlen; } private static boolean isHexDigit(byte b) { return ( (b>=0x30 && b<=0x39) || (b>=0x41&&b<=0x46) ); } private static byte getHexValue(byte b) { return (byte)Character.digit((char)b, 16); } /** * * @param qp Byte array to decode * @param enc The character encoding of the returned string * @return The decoded string. */ public static String decode(byte[] qp, String enc) { int len=decode(qp); try { return new String(qp, 0, len, enc); } catch (UnsupportedEncodingException e) { Log.error("qp.decode: "+ enc + " not supported. " + e.toString()); return new String(qp, 0, len); } } /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(String content, String enc) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ /** * A method to encode data in quoted printable * * @param content * The string to be encoded * @return the encoded string. * @throws Exception * public static byte[] encode(byte[] content) throws Exception { // TODO: to be implemented (has to return a String) throw new Exception("This method is not implemented!"); } */ }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; public interface Appender { /** * Initialize Log File */ void initLogFile(); /** * Open Log file */ void openLogFile(); /** * Close Log file */ void closeLogFile(); /** * Delete Log file */ void deleteLogFile(); /** * Append a message to the Log file */ void writeLogMessage(String level, String msg) throws DataAccessException; }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import java.util.Calendar; import java.util.Date; /** * A utility class providing methods to convert date information contained in * <code>Date</code> objects into RFC2822 and UTC ('Zulu') strings, and to * build <code>Date</code> objects starting from string representations of * dates in RFC2822 and UTC format */ public class MailDateFormatter { /** Format date as: MM/DD */ public static final int FORMAT_MONTH_DAY = 0; /** Format date as: MM/DD/YYYY */ public static final int FORMAT_MONTH_DAY_YEAR = 1; /** Format date as: hh:mm */ public static final int FORMAT_HOURS_MINUTES = 2; /** Format date as: hh:mm:ss */ public static final int FORMAT_HOURS_MINUTES_SECONDS = 3; /** Format date as: DD/MM */ public static final int FORMAT_DAY_MONTH = 4; /** Format date as: DD/MM/YYYY */ public static final int FORMAT_DAY_MONTH_YEAR = 5; /** Device offset, as string */ private static String deviceOffset = "+0000"; /** Device offset, in millis */ private static long millisDeviceOffset = 0; /** Names of the months */ private static String[] monthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /** * Transforms data contained in a <code>Date</code> object (expressed in * UTC) in a string formatted as per RFC2822 in local time (par. 3.3) * * @return A string representing the date contained in the passed * <code>Date</code> object formatted as per RFC 2822 and in local * time */ public static String dateToRfc2822(Date date) { Calendar deviceTime = Calendar.getInstance(); deviceTime.setTime(date); String dayweek = ""; int dayOfWeek = deviceTime.get(Calendar.DAY_OF_WEEK); switch (dayOfWeek) { case 1 : dayweek = "Sun"; break; case 2 : dayweek = "Mon"; break; case 3 : dayweek = "Tue"; break; case 4 : dayweek = "Wed"; break; case 5 : dayweek = "Thu"; break; case 6 : dayweek = "Fri"; break; case 7 : dayweek = "Sat"; break; } int dayOfMonth = deviceTime.get(Calendar.DAY_OF_MONTH); String monthInYear = getMonthName(deviceTime.get(Calendar.MONTH)); int year = deviceTime.get(Calendar.YEAR); int hourOfDay = deviceTime.get(Calendar.HOUR_OF_DAY); int minutes = deviceTime.get(Calendar.MINUTE); int seconds = deviceTime.get(Calendar.SECOND); String rfc = dayweek + ", " + // Tue dayOfMonth + " " + // 7 monthInYear + " " + // Nov year + " " + // 2006 hourOfDay + ":" + minutes + ":" + seconds + " " + // 14:13:26 deviceOffset; //+0200 return rfc; } /** * Converts a <code>Date</code> object into a string in 'Zulu' format * * @param d * A <code>Date</code> object to be converted into a string in * 'Zulu' format * @return A string representing the date contained in the passed * <code>Date</code> object in 'Zulu' format (e.g. * yyyyMMDDThhmmssZ) */ public static String dateToUTC(Date d) { StringBuffer date = new StringBuffer(); Calendar cal = Calendar.getInstance(); cal.setTime(d); date.append(cal.get(Calendar.YEAR)); date.append(printTwoDigits(cal.get(Calendar.MONTH) + 1)) .append(printTwoDigits(cal.get(Calendar.DATE))) .append("T"); date.append(printTwoDigits(cal.get(Calendar.HOUR_OF_DAY))) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(printTwoDigits(cal.get(Calendar.SECOND))) .append("Z"); return date.toString(); } /** * A method that returns a string rapresenting a date. * * @param date the date * * @param format the format as one of * FORMAT_MONTH_DAY, * FORMAT_MONTH_DAY_YEAR, * FORMAT_HOURS_MINUTES, * FORMAT_HOURS_MINUTES_SECONDS * FORMAT_DAY_MONTH * FORMAT_DAY_MONTH_YEAR * constants * * @param separator the separator to be used */ public static String getFormattedStringFromDate( Date date, int format, String separator) { Calendar cal=Calendar.getInstance(); cal.setTime(date); StringBuffer ret = new StringBuffer(); switch (format) { case FORMAT_HOURS_MINUTES: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(getAMPM(cal)); break; case FORMAT_HOURS_MINUTES_SECONDS: //if pm and hour == 0 we want to write 12, not 0 if (cal.get(Calendar.AM_PM)==Calendar.PM && cal.get(Calendar.HOUR) == 0) { ret.append("12"); } else { ret.append(cal.get(Calendar.HOUR)); } ret.append(separator) .append(printTwoDigits(cal.get(Calendar.MINUTE))) .append(separator) .append(cal.get(Calendar.SECOND)) .append(getAMPM(cal)); break; case FORMAT_MONTH_DAY: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)); break; case FORMAT_DAY_MONTH: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1); break; case FORMAT_MONTH_DAY_YEAR: ret.append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.YEAR)); break; case FORMAT_DAY_MONTH_YEAR: ret.append(cal.get(Calendar.DAY_OF_MONTH)) .append(separator) .append(cal.get(Calendar.MONTH)+1) .append(separator) .append(cal.get(Calendar.YEAR)); break; default: Log.error("getFormattedStringFromDate: invalid format ("+ format+")"); } return ret.toString(); } /** * Returns a localized string representation of Date. */ public static String formatLocalTime(Date d) { int dateFormat = FORMAT_MONTH_DAY_YEAR; int timeFormat = FORMAT_HOURS_MINUTES; if(!System.getProperty("microedition.locale").equals("en")) { dateFormat = FORMAT_DAY_MONTH_YEAR; } return getFormattedStringFromDate(d,dateFormat,"/") +" "+getFormattedStringFromDate(d,timeFormat,":"); } /** * Parses the string in RFC 2822 format and return a <code>Date</code> * object. <p> * Parse strings like: * Thu, 03 May 2007 14:45:38 GMT * Thu, 03 May 2007 14:45:38 GMT+0200 * Thu, 1 Feb 2007 03:57:01 -0800 * Fri, 04 May 2007 13:40:17 PDT * * @param d the date representation to parse * @return a date, if valid, or null on error * */ public static Date parseRfc2822Date(String stringDate) { if (stringDate == null) { return null; } long hourOffset=0; long minOffset=0; Calendar cal = Calendar.getInstance(); try { Log.info("Date original: " + stringDate); // Just skip the weekday if present int start = stringDate.indexOf(','); //put start after ", " start = (start == -1) ? 0 : start + 2; stringDate = stringDate.substring(start).trim(); start = 0; // Get day of month int end = stringDate.indexOf(' ', start); int day =1; try { day = Integer.parseInt(stringDate.substring(start, end)); } catch (NumberFormatException ex) { // some phones (Nokia 6111) have a invalid date format, // something like Tue10 Jul... instead of Tue, 10 // so we try to strip (again) the weekday day = Integer.parseInt(stringDate.substring(start+3, end)); Log.info("Nokia 6111 patch applied."); } cal.set(Calendar.DAY_OF_MONTH,day); // Get month start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.MONTH, getMonthNumber(stringDate.substring(start, end))); // Get year start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.YEAR, Integer.parseInt(stringDate.substring(start, end))); // Get hour start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(stringDate.substring(start, end).trim())); // Get min start = end + 1; end = stringDate.indexOf(':', start); cal.set(Calendar.MINUTE, Integer.parseInt(stringDate.substring(start, end))); // Get sec start = end + 1; end = stringDate.indexOf(' ', start); cal.set(Calendar.SECOND, Integer.parseInt(stringDate.substring(start, end))); // Get OFFSET start = end +1; end = stringDate.indexOf('\r', start); // Process Timezone, checking first for the actual RFC2822 format, // and then for nthe obsolete syntax. char sign = '+'; String hourDiff = "0"; String minDiff = "0"; String offset = stringDate.substring(start).trim(); if (offset.startsWith("+") || offset.startsWith("-")) { if(offset.length() >= 5 ){ sign = offset.charAt(0); hourDiff = offset.substring(1,3); minDiff = offset.substring(3,5); } else if(offset.length() == 3){ sign = offset.charAt(0); hourDiff = offset.substring(1); minDiff = "00"; } // Convert offset to int hourOffset = Long.parseLong(hourDiff); minOffset = Long.parseLong(minDiff); if(sign == '-') { hourOffset = -hourOffset; } } else if(offset.equals("EDT")){ hourOffset = -4; } else if(offset.equals("EST") || offset.equals("CDT")){ hourOffset = -5; } else if(offset.equals("CST") || offset.equals("MDT")){ hourOffset = -6; } else if(offset.equals("PDT") || offset.equals("MST")){ hourOffset = -7; } else if(offset.equals("PST")){ hourOffset = -8; } else if(offset.equals("GMT") || offset.equals("UT")){ hourOffset = 0; } else if (offset.substring(0,3).equals("GMT") && offset.length() > 3){ sign = offset.charAt(3); hourDiff = offset.substring(4,6); minDiff = offset.substring(6,8); } long millisOffset = (hourOffset * 3600000) + (minOffset * 60000); Date gmtDate = cal.getTime(); long millisDate = gmtDate.getTime(); millisDate -= millisOffset; gmtDate.setTime(millisDate); return gmtDate; } catch (Exception e) { Log.error("Exception in parseRfc2822Date: " + e.toString() + " parsing " + stringDate); e.printStackTrace(); return null; } } /** * Convert the given date (GMT) into the local date. * NOTE: changes the original date too! * Should we change it to a void toLocalDate(Date) that changes the * input date only? */ public static Date getDeviceLocalDate (Date gmtDate){ if (null != gmtDate){ /*long dateInMillis = gmtDate.getTime(); Date deviceDate = new Date(); deviceDate.setTime(dateInMillis+millisDeviceOffset); return deviceDate; **/ gmtDate.setTime(gmtDate.getTime()+millisDeviceOffset); return gmtDate; } else { return null; } } /** * Gets a <code>Date</code> object from a string representing a date in * 'Zulu' format (yyyyMMddTHHmmssZ) * * @param utc * date in 'Zulu' format (yyyyMMddTHHmmssZ) * @return A <code>Date</code> object obtained starting from a time in * milliseconds from the Epoch */ public static Date parseUTCDate(String utc) { int day = 0; int month = 0; int year = 0; int hour = 0; int minute = 0; int second = 0; Calendar calendar = null; day = Integer.parseInt(utc.substring(6, 8)); month = Integer.parseInt(utc.substring(4, 6)); year = Integer.parseInt(utc.substring(0, 4)); hour = Integer.parseInt(utc.substring(9, 11)); minute = Integer.parseInt(utc.substring(11, 13)); second = Integer.parseInt(utc.substring(13, 15)); calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); Date date = calendar.getTime(); long dateInMillis = date.getTime(); date.setTime(dateInMillis+millisDeviceOffset); return date; } public static void setTimeZone(String timeZone){ if (timeZone == null || timeZone.length() < 5) { Log.error("setTimeZone: invalid timezone " + timeZone); } try { deviceOffset = timeZone; String hstmz = deviceOffset.substring(1, 3); String mstmz = deviceOffset.substring(3, 5); long hhtmz = Long.parseLong(hstmz); long mmtmz = Long.parseLong(mstmz); millisDeviceOffset = (hhtmz * 3600000) + (mmtmz * 60000); if(deviceOffset.charAt(0)=='-') { millisDeviceOffset *= -1; } } catch(Exception e) { Log.error("setTimeZone: " + e.toString()); e.printStackTrace(); } } //------------------------------------------------------------- Private methods /** * Get the number of the month, given the name. */ private static int getMonthNumber(String name) { for(int i=0, l=monthNames.length; i<l; i++) { if(monthNames[i].equals(name)) { return i; } } return -1; } /** * Get the name of the month, given the number. */ private static String getMonthName(int number) { if(number>0 && number<monthNames.length) { return monthNames[number]; } else return null; } private static String getAMPM(Calendar cal) { return (cal.get(Calendar.AM_PM)==Calendar.AM)?"a":"p"; } /** * Returns a string representation of number with at least 2 digits */ private static String printTwoDigits(int number) { if (number>9) { return String.valueOf(number); } else { return "0"+number; } } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.util; import com.funambol.storage.DataAccessException; import java.util.Date; /** * Generic Log class */ public class Log { //---------------------------------------------------------------- Constants /** * Log level DISABLED: used to speed up applications using logging features */ public static final int DISABLED = -1; /** * Log level ERROR: used to log error messages. */ public static final int ERROR = 0; /** * Log level INFO: used to log information messages. */ public static final int INFO = 1; /** * Log level DEBUG: used to log debug messages. */ public static final int DEBUG = 2; /** * Log level TRACE: used to trace the program execution. */ public static final int TRACE = 3; private static final int PROFILING = -2; //---------------------------------------------------------------- Variables /** * The default appender is the console */ private static Appender out; /** * The default log level is INFO */ private static int level = INFO; /** * Last time stamp used to dump profiling information */ private static long initialTimeStamp = -1; //------------------------------------------------------------- Constructors /** * This class is static and cannot be intantiated */ private Log(){ } //----------------------------------------------------------- Public methods /** * Initialize log file with a specific log level. * With this implementation of initLog the initialization is skipped. * Only a delete of log is performed. * * @param object the appender object that write log file * @param level the log level */ public static void initLog(Appender object, int level){ setLogLevel(level); out = object; // Delete Log invocation removed to speed up startup initialization. // However if needed the log store will rotate //deleteLog(); if (level > Log.DISABLED) { writeLogMessage(level, "INITLOG","---------"); } } /** * Ititialize log file * @param object the appender object that write log file */ public static void initLog(Appender object){ out = object; out.initLogFile(); } /** * Delete log file * */ public static void deleteLog() { out.deleteLogFile(); } /** * Accessor method to define log level: * @param newlevel log level to be set */ public static void setLogLevel(int newlevel) { level = newlevel; } /** * Accessor method to retrieve log level: * @return actual log level */ public static int getLogLevel() { return level; } /** * ERROR: Error message * @param msg the message to be logged */ public static void error(String msg) { writeLogMessage(ERROR, "ERROR", msg); } /** * ERROR: Error message * @param msg the message to be logged * @param obj the object that send error message */ public static void error(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " + msg; writeLogMessage(ERROR, "ERROR", message); } /** * INFO: Information message * @param msg the message to be logged */ public static void info(String msg) { writeLogMessage(INFO, "INFO", msg); } /** * INFO: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void info(Object obj, String msg) { writeLogMessage(INFO, "INFO", msg); } /** * DEBUG: Debug message * @param msg the message to be logged */ public static void debug(String msg) { writeLogMessage(DEBUG, "DEBUG", msg); } /** * DEBUG: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void debug(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(DEBUG, "DEBUG", message); } /** * TRACE: Debugger mode */ public static void trace(String msg) { writeLogMessage(TRACE, "TRACE", msg); } /** * TRACE: Information message * @param msg the message to be logged * @param obj the object that send log message */ public static void trace(Object obj, String msg) { String message = "["+ obj.getClass().getName() + "] " +msg; writeLogMessage(TRACE, "TRACE", message); } /** * Dump memory statistics at this point. Dump if level >= DEBUG. * * @param msg message to be logged */ public static void memoryStats(String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long available = Runtime.getRuntime().freeMemory(); Runtime.getRuntime().gc(); writeLogMessage(PROFILING, "PROFILING-MEMORY", msg + ":" + available + " [bytes]"); } /** * Dump memory statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void memoryStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory Runtime.getRuntime().gc(); long available = Runtime.getRuntime().freeMemory(); writeLogMessage(PROFILING, "PROFILING-MEMORY", obj.getClass().getName() + "::" + msg + ":" + available + " [bytes]"); } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void timeStats(String msg) { long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", msg + ": " + currentTime + "[msec]"); } } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void timeStats(Object obj, String msg) { // Try to force a garbage collection, so we get the real amount of // available memory long time = System.currentTimeMillis(); if (initialTimeStamp == -1) { writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ": 0 [msec]"); initialTimeStamp = time; } else { long currentTime = time - initialTimeStamp; writeLogMessage(PROFILING, "PROFILING-TIME", obj.getClass().getName() + "::" + msg + ":" + currentTime + " [msec]"); } } /** * Dump time statistics at this point. * * @param msg message to be logged */ public static void stats(String msg) { memoryStats(msg); timeStats(msg); } /** * Dump time statistics at this point. * * @param obj caller object * @param msg message to be logged */ public static void stats(Object obj, String msg) { memoryStats(obj, msg); timeStats(obj, msg); } private static void writeLogMessage(int msgLevel, String levelMsg, String msg) { if (level >= msgLevel) { try { if (out != null) { out.writeLogMessage(levelMsg, msg); } else { System.out.print(MailDateFormatter.dateToUTC(new Date())); System.out.print(" [" + levelMsg + "] " ); System.out.println(msg); } } catch (DataAccessException ex) { ex.printStackTrace(); } } } }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * A simple interface to serialize objects on j2ME platform */ public interface Serializable { /** * Write object fields to the output stream. * @param out Output stream * @throws IOException */ void serialize(DataOutputStream out) throws IOException; /** * Read object field from the input stream. * @param in Input stream * @throws IOException */ void deserialize(DataInputStream in) throws IOException; }
Java
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.storage; /** * Represents a <i>"update"</i> error on device database. */ public class DataAccessException extends Exception { /** * */ private static final long serialVersionUID = -6695128856314376170L; /** * Creates a new instance of <code>DataAccessException</code> * without detail message. */ public DataAccessException() { } /** * Constructs an instance of <p><code>DataAccessException</code></p> * with the specified detail message. * @param msg the detail message. */ public DataAccessException(String msg) { super(msg); } }
Java
package pl.polidea.treeview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; /** * Tree view, expandable multi-level. * * <pre> * attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width * attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background * attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background * </pre> */ public class TreeViewList extends ListView { private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed; private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded; private static final int DEFAULT_INDENT = 0; private static final int DEFAULT_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private Drawable expandedDrawable; private Drawable collapsedDrawable; private Drawable rowBackgroundDrawable; private Drawable indicatorBackgroundDrawable; private int indentWidth = 0; private int indicatorGravity = 0; private AbstractTreeViewAdapter< ? > treeAdapter; private boolean collapsible; private boolean handleTrackballPress; public TreeViewList(final Context context, final AttributeSet attrs) { this(context, attrs, R.style.treeViewListStyle); } public TreeViewList(final Context context) { this(context, null); } public TreeViewList(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } private void parseAttributes(final Context context, final AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TreeViewList); expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded); if (expandedDrawable == null) { expandedDrawable = context.getResources().getDrawable( DEFAULT_EXPANDED_RESOURCE); } collapsedDrawable = a .getDrawable(R.styleable.TreeViewList_src_collapsed); if (collapsedDrawable == null) { collapsedDrawable = context.getResources().getDrawable( DEFAULT_COLLAPSED_RESOURCE); } indentWidth = a.getDimensionPixelSize( R.styleable.TreeViewList_indent_width, DEFAULT_INDENT); indicatorGravity = a.getInteger( R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY); indicatorBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_indicator_background); rowBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_row_background); collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true); handleTrackballPress = a.getBoolean( R.styleable.TreeViewList_handle_trackball_press, true); } @Override public void setAdapter(final ListAdapter adapter) { if (!(adapter instanceof AbstractTreeViewAdapter)) { throw new TreeConfigurationException( "The adapter is not of TreeViewAdapter type"); } treeAdapter = (AbstractTreeViewAdapter< ? >) adapter; syncAdapter(); super.setAdapter(treeAdapter); } private void syncAdapter() { treeAdapter.setCollapsedDrawable(collapsedDrawable); treeAdapter.setExpandedDrawable(expandedDrawable); treeAdapter.setIndicatorGravity(indicatorGravity); treeAdapter.setIndentWidth(indentWidth); treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable); treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable); treeAdapter.setCollapsible(collapsible); if (handleTrackballPress) { setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView< ? > parent, final View view, final int position, final long id) { treeAdapter.handleItemClick(view, view.getTag()); } }); } else { setOnClickListener(null); } } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; syncAdapter(); treeAdapter.refresh(); } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; syncAdapter(); treeAdapter.refresh(); } public void setHandleTrackballPress(final boolean handleTrackballPress) { this.handleTrackballPress = handleTrackballPress; syncAdapter(); treeAdapter.refresh(); } public Drawable getExpandedDrawable() { return expandedDrawable; } public Drawable getCollapsedDrawable() { return collapsedDrawable; } public Drawable getRowBackgroundDrawable() { return rowBackgroundDrawable; } public Drawable getIndicatorBackgroundDrawable() { return indicatorBackgroundDrawable; } public int getIndentWidth() { return indentWidth; } public int getIndicatorGravity() { return indicatorGravity; } public boolean isCollapsible() { return collapsible; } public boolean isHandleTrackballPress() { return handleTrackballPress; } }
Java
package pl.polidea.treeview; import android.util.Log; /** * Allows to build tree easily in sequential mode (you have to know levels of * all the tree elements upfront). You should rather use this class rather than * manager if you build initial tree from some external data source. * * @param <T> */ public class TreeBuilder<T> { private static final String TAG = TreeBuilder.class.getSimpleName(); private final TreeStateManager<T> manager; private T lastAddedId = null; private int lastLevel = -1; public TreeBuilder(final TreeStateManager<T> manager) { this.manager = manager; } public void clear() { manager.clear(); } /** * Adds new relation to existing tree. Child is set as the last child of the * parent node. Parent has to already exist in the tree, child cannot yet * exist. This method is mostly useful in case you add entries layer by * layer - i.e. first top level entries, then children for all parents, then * grand-children and so on. * * @param parent * parent id * @param child * child id */ public synchronized void addRelation(final T parent, final T child) { Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child); manager.addAfterChild(parent, child, null); lastAddedId = child; lastLevel = manager.getLevel(child); } /** * Adds sequentially new node. Using this method is the simplest way of * building tree - if you have all the elements in the sequence as they * should be displayed in fully-expanded tree. You can combine it with add * relation - for example you can add information about few levels using * {@link addRelation} and then after the right level is added as parent, * you can continue adding them using sequential operation. * * @param id * id of the node * @param level * its level */ public synchronized void sequentiallyAddNextNode(final T id, final int level) { Log.d(TAG, "Adding sequentiall node " + id + " at level " + level); if (lastAddedId == null) { addNodeToParentOneLevelDown(null, id, level); } else { if (level <= lastLevel) { final T parent = findParentAtLevel(lastAddedId, level - 1); addNodeToParentOneLevelDown(parent, id, level); } else { addNodeToParentOneLevelDown(lastAddedId, id, level); } } } /** * Find parent of the node at the level specified. * * @param node * node from which we start * @param levelToFind * level which we are looking for * @return the node found (null if it is topmost node). */ private T findParentAtLevel(final T node, final int levelToFind) { T parent = manager.getParent(node); while (parent != null) { if (manager.getLevel(parent) == levelToFind) { break; } parent = manager.getParent(parent); } return parent; } /** * Adds note to parent at the level specified. But it verifies that the * level is one level down than the parent! * * @param parent * parent parent * @param id * new node id * @param level * should always be parent's level + 1 */ private void addNodeToParentOneLevelDown(final T parent, final T id, final int level) { if (parent == null && level != 0) { throw new TreeConfigurationException("Trying to add new id " + id + " to top level with level != 0 (" + level + ")"); } if (parent != null && manager.getLevel(parent) != level - 1) { throw new TreeConfigurationException("Trying to add new id " + id + " <" + level + "> to " + parent + " <" + manager.getLevel(parent) + ">. The difference in levels up is bigger than 1."); } manager.addAfterChild(parent, id, null); setLastAdded(id, level); } private void setLastAdded(final T id, final int level) { lastAddedId = id; lastLevel = level; } }
Java
package pl.polidea.treeview; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import android.database.DataSetObserver; /** * In-memory manager of tree state. * * @param <T> * type of identifier */ public class InMemoryTreeStateManager<T> implements TreeStateManager<T> { private static final long serialVersionUID = 1L; private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>(); private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>( null, null, -1, true); private transient List<T> visibleListCache = null; // lasy initialised private transient List<T> unmodifiableVisibleList = null; private boolean visibleByDefault = true; private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>(); private synchronized void internalDataSetChanged() { visibleListCache = null; unmodifiableVisibleList = null; for (final DataSetObserver observer : observers) { observer.onChanged(); } } /** * If true new nodes are visible by default. * * @param visibleByDefault * if true, then newly added nodes are expanded by default */ public void setVisibleByDefault(final boolean visibleByDefault) { this.visibleByDefault = visibleByDefault; } private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) { if (id == null) { throw new NodeNotInTreeException("(null)"); } final InMemoryTreeNode<T> node = allNodes.get(id); if (node == null) { throw new NodeNotInTreeException(id.toString()); } return node; } private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) { if (id == null) { return topSentinel; } return getNodeFromTreeOrThrow(id); } private void expectNodeNotInTreeYet(final T id) { final InMemoryTreeNode<T> node = allNodes.get(id); if (node != null) { throw new NodeAlreadyInTreeException(id.toString(), node.toString()); } } @Override public synchronized TreeNodeInfo<T> getNodeInfo(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id); final List<InMemoryTreeNode<T>> children = node.getChildren(); boolean expanded = false; if (!children.isEmpty() && children.get(0).isVisible()) { expanded = true; } return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(), node.isVisible(), expanded); } @Override public synchronized List<T> getChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getChildIdList(); } @Override public synchronized T getParent(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getParent(); } private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) { boolean visibility; final List<InMemoryTreeNode<T>> children = node.getChildren(); if (children.isEmpty()) { visibility = visibleByDefault; } else { visibility = children.get(0).isVisible(); } return visibility; } @Override public synchronized void addBeforeChild(final T parent, final T newChild, final T beforeChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); // top nodes are always expanded. if (beforeChild == null) { final InMemoryTreeNode<T> added = node.add(0, newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(beforeChild); final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void addAfterChild(final T parent, final T newChild, final T afterChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); if (afterChild == null) { final InMemoryTreeNode<T> added = node.add( node.getChildrenListSize(), newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(afterChild); final InMemoryTreeNode<T> added = node.add( index == -1 ? node.getChildrenListSize() : index + 1, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void removeNodeRecursively(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); final boolean visibleNodeChanged = removeNodeRecursively(node); final T parent = node.getParent(); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); parentNode.removeChild(id); if (visibleNodeChanged) { internalDataSetChanged(); } } private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) { boolean visibleNodeChanged = false; for (final InMemoryTreeNode<T> child : node.getChildren()) { if (removeNodeRecursively(child)) { visibleNodeChanged = true; } } node.clearChildren(); if (node.getId() != null) { allNodes.remove(node.getId()); if (node.isVisible()) { visibleNodeChanged = true; } } return visibleNodeChanged; } private void setChildrenVisibility(final InMemoryTreeNode<T> node, final boolean visible, final boolean recursive) { for (final InMemoryTreeNode<T> child : node.getChildren()) { child.setVisible(visible); if (recursive) { setChildrenVisibility(child, visible, true); } } } @Override public synchronized void expandDirectChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, false); internalDataSetChanged(); } @Override public synchronized void expandEverythingBelow(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, true); internalDataSetChanged(); } @Override public synchronized void collapseChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (node == topSentinel) { for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) { setChildrenVisibility(n, false, true); } } else { setChildrenVisibility(node, false, true); } internalDataSetChanged(); } @Override public synchronized T getNextSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); boolean returnNext = false; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (returnNext) { return child.getId(); } if (child.getId().equals(id)) { returnNext = true; } } return null; } @Override public synchronized T getPreviousSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); final T previousSibling = null; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (child.getId().equals(id)) { return previousSibling; } } return null; } @Override public synchronized boolean isInTree(final T id) { return allNodes.containsKey(id); } @Override public synchronized int getVisibleCount() { return getVisibleList().size(); } @Override public synchronized List<T> getVisibleList() { T currentId = null; if (visibleListCache == null) { visibleListCache = new ArrayList<T>(allNodes.size()); do { currentId = getNextVisible(currentId); if (currentId == null) { break; } else { visibleListCache.add(currentId); } } while (true); } if (unmodifiableVisibleList == null) { unmodifiableVisibleList = Collections .unmodifiableList(visibleListCache); } return unmodifiableVisibleList; } public synchronized T getNextVisible(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (!node.isVisible()) { return null; } final List<InMemoryTreeNode<T>> children = node.getChildren(); if (!children.isEmpty()) { final InMemoryTreeNode<T> firstChild = children.get(0); if (firstChild.isVisible()) { return firstChild.getId(); } } final T sibl = getNextSibling(id); if (sibl != null) { return sibl; } T parent = node.getParent(); do { if (parent == null) { return null; } final T parentSibling = getNextSibling(parent); if (parentSibling != null) { return parentSibling; } parent = getNodeFromTreeOrThrow(parent).getParent(); } while (true); } @Override public synchronized void registerDataSetObserver( final DataSetObserver observer) { observers.add(observer); } @Override public synchronized void unregisterDataSetObserver( final DataSetObserver observer) { observers.remove(observer); } @Override public int getLevel(final T id) { return getNodeFromTreeOrThrow(id).getLevel(); } @Override public Integer[] getHierarchyDescription(final T id) { final int level = getLevel(id); final Integer[] hierarchy = new Integer[level + 1]; int currentLevel = level; T currentId = id; T parent = getParent(currentId); while (currentLevel >= 0) { hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId); currentId = parent; parent = getParent(parent); } return hierarchy; } private void appendToSb(final StringBuilder sb, final T id) { if (id != null) { final TreeNodeInfo<T> node = getNodeInfo(id); final int indent = node.getLevel() * 4; final char[] indentString = new char[indent]; Arrays.fill(indentString, ' '); sb.append(indentString); sb.append(node.toString()); sb.append(Arrays.asList(getHierarchyDescription(id)).toString()); sb.append("\n"); } final List<T> children = getChildren(id); for (final T child : children) { appendToSb(sb, child); } } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(); appendToSb(sb, null); return sb.toString(); } @Override public synchronized void clear() { allNodes.clear(); topSentinel.clearChildren(); internalDataSetChanged(); } @Override public void refresh() { internalDataSetChanged(); } }
Java
package pl.polidea.treeview; /** * The node being added is already in the tree. * */ public class NodeAlreadyInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeAlreadyInTreeException(final String id, final String oldNode) { super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode); } }
Java
/** * Provides expandable Tree View implementation. */ package pl.polidea.treeview;
Java
package pl.polidea.treeview; import android.app.Activity; import android.content.Context; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ListAdapter; /** * Adapter used to feed the table view. * * @param <T> * class for ID of the tree */ public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements ListAdapter { private final TreeStateManager<T> treeStateManager; private final int numberOfLevels; private final LayoutInflater layoutInflater; private int indentWidth = 0; private int indicatorGravity = 0; private Drawable collapsedDrawable; private Drawable expandedDrawable; private Drawable indicatorBackgroundDrawable; private Drawable rowBackgroundDrawable; private final OnClickListener indicatorClickListener = new OnClickListener() { @Override public void onClick(final View v) { @SuppressWarnings("unchecked") final T id = (T) v.getTag(); expandCollapse(id); } }; private boolean collapsible; private final Activity activity; public Activity getActivity() { return activity; } protected TreeStateManager<T> getManager() { return treeStateManager; } protected void expandCollapse(final T id) { final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id); if (!info.isWithChildren()) { // ignore - no default action return; } if (info.isExpanded()) { treeStateManager.collapseChildren(id); } else { treeStateManager.expandDirectChildren(id); } } private void calculateIndentWidth() { if (expandedDrawable != null) { indentWidth = Math.max(getIndentWidth(), expandedDrawable.getIntrinsicWidth()); } if (collapsedDrawable != null) { indentWidth = Math.max(getIndentWidth(), collapsedDrawable.getIntrinsicWidth()); } } public AbstractTreeViewAdapter(final Activity activity, final TreeStateManager<T> treeStateManager, final int numberOfLevels) { this.activity = activity; this.treeStateManager = treeStateManager; this.layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.numberOfLevels = numberOfLevels; this.collapsedDrawable = null; this.expandedDrawable = null; this.rowBackgroundDrawable = null; this.indicatorBackgroundDrawable = null; } @Override public void registerDataSetObserver(final DataSetObserver observer) { treeStateManager.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { treeStateManager.unregisterDataSetObserver(observer); } @Override public int getCount() { return treeStateManager.getVisibleCount(); } @Override public Object getItem(final int position) { return getItemId(position); } public T getTreeId(final int position) { return treeStateManager.getVisibleList().get(position); } public TreeNodeInfo<T> getTreeNodeInfo(final int position) { return treeStateManager.getNodeInfo(getTreeId(position)); } @Override public boolean hasStableIds() { // NOPMD return true; } @Override public int getItemViewType(final int position) { return getTreeNodeInfo(position).getLevel(); } @Override public int getViewTypeCount() { return numberOfLevels; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public boolean areAllItemsEnabled() { // NOPMD return true; } @Override public boolean isEnabled(final int position) { // NOPMD return true; } protected int getTreeListItemWrapperId() { return R.layout.tree_list_item_wrapper; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position); if (convertView == null) { final LinearLayout layout = (LinearLayout) layoutInflater.inflate( getTreeListItemWrapperId(), null); return populateTreeItem(layout, getNewChildView(nodeInfo), nodeInfo, true); } else { final LinearLayout linear = (LinearLayout) convertView; final FrameLayout frameLayout = (FrameLayout) linear .findViewById(R.id.treeview_list_item_frame); final View childView = frameLayout.getChildAt(0); updateView(childView, nodeInfo); return populateTreeItem(linear, childView, nodeInfo, false); } } /** * Called when new view is to be created. * * @param treeNodeInfo * node info * @return view that should be displayed as tree content */ public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo); /** * Called when new view is going to be reused. You should update the view * and fill it in with the data required to display the new information. You * can also create a new view, which will mean that the old view will not be * reused. * * @param view * view that should be updated with the new values * @param treeNodeInfo * node info used to populate the view * @return view to used as row indented content */ public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo); /** * Retrieves background drawable for the node. * * @param treeNodeInfo * node info * @return drawable returned as background for the whole row. Might be null, * then default background is used */ public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD return null; } private Drawable getDrawableOrDefaultBackground(final Drawable r) { if (r == null) { return activity.getResources() .getDrawable(R.drawable.list_selector_background).mutate(); } else { return r; } } public final LinearLayout populateTreeItem(final LinearLayout layout, final View childView, final TreeNodeInfo<T> nodeInfo, final boolean newChildView) { final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo); layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable) : individualRowDrawable); final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT); final LinearLayout indicatorLayout = (LinearLayout) layout .findViewById(R.id.treeview_list_item_image_layout); indicatorLayout.setGravity(indicatorGravity); indicatorLayout.setLayoutParams(indicatorLayoutParams); final ImageView image = (ImageView) layout .findViewById(R.id.treeview_list_item_image); image.setImageDrawable(getDrawable(nodeInfo)); image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable)); image.setScaleType(ScaleType.CENTER); image.setTag(nodeInfo.getId()); if (nodeInfo.isWithChildren() && collapsible) { image.setOnClickListener(indicatorClickListener); } else { image.setOnClickListener(null); } layout.setTag(nodeInfo.getId()); final FrameLayout frameLayout = (FrameLayout) layout .findViewById(R.id.treeview_list_item_frame); final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); if (newChildView) { frameLayout.addView(childView, childParams); } frameLayout.setTag(nodeInfo.getId()); return layout; } protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) { return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0)); } protected Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) { if (!nodeInfo.isWithChildren() || !collapsible) { return getDrawableOrDefaultBackground(indicatorBackgroundDrawable); } if (nodeInfo.isExpanded()) { return expandedDrawable; } else { return collapsedDrawable; } } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; calculateIndentWidth(); } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; calculateIndentWidth(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; calculateIndentWidth(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; } public void refresh() { treeStateManager.refresh(); } private int getIndentWidth() { return indentWidth; } @SuppressWarnings("unchecked") public void handleItemClick(final View view, final Object id) { expandCollapse((T) id); } }
Java
package pl.polidea.treeview; /** * Exception thrown when there is a problem with configuring tree. * */ public class TreeConfigurationException extends RuntimeException { private static final long serialVersionUID = 1L; public TreeConfigurationException(final String detailMessage) { super(detailMessage); } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Node. It is package protected so that it cannot be used outside. * * @param <T> * type of the identifier used by the tree */ class InMemoryTreeNode<T> implements Serializable { private static final long serialVersionUID = 1L; private final T id; private final T parent; private final int level; private boolean visible = true; private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>(); private List<T> childIdListCache = null; public InMemoryTreeNode(final T id, final T parent, final int level, final boolean visible) { super(); this.id = id; this.parent = parent; this.level = level; this.visible = visible; } public int indexOf(final T id) { return getChildIdList().indexOf(id); } /** * Cache is built lasily only if needed. The cache is cleaned on any * structure change for that node!). * * @return list of ids of children */ public synchronized List<T> getChildIdList() { if (childIdListCache == null) { childIdListCache = new LinkedList<T>(); for (final InMemoryTreeNode<T> n : children) { childIdListCache.add(n.getId()); } } return childIdListCache; } public boolean isVisible() { return visible; } public void setVisible(final boolean visible) { this.visible = visible; } public int getChildrenListSize() { return children.size(); } public synchronized InMemoryTreeNode<T> add(final int index, final T child, final boolean visible) { childIdListCache = null; // Note! top levell children are always visible (!) final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child, getId(), getLevel() + 1, getId() == null ? true : visible); children.add(index, newNode); return newNode; } /** * Note. This method should technically return unmodifiable collection, but * for performance reason on small devices we do not do it. * * @return children list */ public List<InMemoryTreeNode<T>> getChildren() { return children; } public synchronized void clearChildren() { children.clear(); childIdListCache = null; } public synchronized void removeChild(final T child) { final int childIndex = indexOf(child); if (childIndex != -1) { children.remove(childIndex); childIdListCache = null; } } @Override public String toString() { return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent() + ", level=" + getLevel() + ", visible=" + visible + ", children=" + children + ", childIdListCache=" + childIdListCache + "]"; } T getId() { return id; } T getParent() { return parent; } int getLevel() { return level; } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.List; import android.database.DataSetObserver; /** * Manages information about state of the tree. It only keeps information about * tree elements, not the elements themselves. * * @param <T> * type of the identifier for nodes in the tree */ public interface TreeStateManager<T> extends Serializable { /** * Returns array of integers showing the location of the node in hierarchy. * It corresponds to heading numbering. {0,0,0} in 3 level node is the first * node {0,0,1} is second leaf (assuming that there are two leaves in first * subnode of the first node). * * @param id * id of the node * @return textual description of the hierarchy in tree for the node. */ Integer[] getHierarchyDescription(T id); /** * Returns level of the node. * * @param id * id of the node * @return level in the tree */ int getLevel(T id); /** * Returns information about the node. * * @param id * node id * @return node info */ TreeNodeInfo<T> getNodeInfo(T id); /** * Returns children of the node. * * @param id * id of the node or null if asking for top nodes * @return children of the node */ List<T> getChildren(T id); /** * Returns parent of the node. * * @param id * id of the node * @return parent id or null if no parent */ T getParent(T id); /** * Adds the node before child or at the beginning. * * @param parent * id of the parent node. If null - adds at the top level * @param newChild * new child to add if null - adds at the beginning. * @param beforeChild * child before which to add the new child */ void addBeforeChild(T parent, T newChild, T beforeChild); /** * Adds the node after child or at the end. * * @param parent * id of the parent node. If null - adds at the top level. * @param newChild * new child to add. If null - adds at the end. * @param afterChild * child after which to add the new child */ void addAfterChild(T parent, T newChild, T afterChild); /** * Removes the node and all children from the tree. * * @param id * id of the node to remove or null if all nodes are to be * removed. */ void removeNodeRecursively(T id); /** * Expands all children of the node. * * @param id * node which children should be expanded. cannot be null (top * nodes are always expanded!). */ void expandDirectChildren(T id); /** * Expands everything below the node specified. Might be null - then expands * all. * * @param id * node which children should be expanded or null if all nodes * are to be expanded. */ void expandEverythingBelow(T id); /** * Collapse children. * * @param id * id collapses everything below node specified. If null, * collapses everything but top-level nodes. */ void collapseChildren(T id); /** * Returns next sibling of the node (or null if no further sibling). * * @param id * node id * @return the sibling (or null if no next) */ T getNextSibling(T id); /** * Returns previous sibling of the node (or null if no previous sibling). * * @param id * node id * @return the sibling (or null if no previous) */ T getPreviousSibling(T id); /** * Checks if given node is already in tree. * * @param id * id of the node * @return true if node is already in tree. */ boolean isInTree(T id); /** * Count visible elements. * * @return number of currently visible elements. */ int getVisibleCount(); /** * Returns visible node list. * * @return return the list of all visible nodes in the right sequence */ List<T> getVisibleList(); /** * Registers observers with the manager. * * @param observer * observer */ void registerDataSetObserver(final DataSetObserver observer); /** * Unregisters observers with the manager. * * @param observer * observer */ void unregisterDataSetObserver(final DataSetObserver observer); /** * Cleans tree stored in manager. After this operation the tree is empty. * */ void clear(); /** * Refreshes views connected to the manager. */ void refresh(); }
Java
package pl.polidea.treeview; /** * This exception is thrown when the tree does not contain node requested. * */ public class NodeNotInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeNotInTreeException(final String id) { super("The tree does not contain the node specified: " + id); } }
Java
package pl.polidea.treeview; /** * Information about the node. * * @param <T> * type of the id for the tree */ public class TreeNodeInfo<T> { private final T id; private final int level; private final boolean withChildren; private final boolean visible; private final boolean expanded; /** * Creates the node information. * * @param id * id of the node * @param level * level of the node * @param withChildren * whether the node has children. * @param visible * whether the tree node is visible. * @param expanded * whether the tree node is expanded * */ public TreeNodeInfo(final T id, final int level, final boolean withChildren, final boolean visible, final boolean expanded) { super(); this.id = id; this.level = level; this.withChildren = withChildren; this.visible = visible; this.expanded = expanded; } public T getId() { return id; } public boolean isWithChildren() { return withChildren; } public boolean isVisible() { return visible; } public boolean isExpanded() { return expanded; } public int getLevel() { return level; } @Override public String toString() { return "TreeNodeInfo [id=" + id + ", level=" + level + ", withChildren=" + withChildren + ", visible=" + visible + ", expanded=" + expanded + "]"; } }
Java
/** * Provides just demo of the TreeView widget. */ package pl.polidea.treeview.demo;
Java
package pl.polidea.treeview.demo; import java.util.Arrays; import java.util.Set; import pl.polidea.treeview.AbstractTreeViewAdapter; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; /** * This is a very simple adapter that provides very basic tree view with a * checkboxes and simple item description. * */ class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> { private final Set<Long> selected; private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { final Long id = (Long) buttonView.getTag(); changeSelected(isChecked, id); } }; private void changeSelected(final boolean isChecked, final Long id) { if (isChecked) { selected.add(id); } else { selected.remove(id); } } public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(treeViewListDemo, treeStateManager, numberOfLevels); this.selected = selected; } private String getDescription(final long id) { final Integer[] hierarchy = getManager().getHierarchyDescription(id); return "Node " + id + Arrays.asList(hierarchy); } @Override public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) getActivity() .getLayoutInflater().inflate(R.layout.demo_list_item, null); return updateView(viewLayout, treeNodeInfo); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) view; final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setText(getDescription(treeNodeInfo.getId())); levelView.setText(Integer.toString(treeNodeInfo.getLevel())); final CheckBox box = (CheckBox) viewLayout .findViewById(R.id.demo_list_checkbox); box.setTag(treeNodeInfo.getId()); if (treeNodeInfo.isWithChildren()) { box.setVisibility(View.GONE); } else { box.setVisibility(View.VISIBLE); box.setChecked(selected.contains(treeNodeInfo.getId())); } box.setOnCheckedChangeListener(onCheckedChange); return viewLayout; } @Override public void handleItemClick(final View view, final Object id) { final Long longId = (Long) id; final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId); if (info.isWithChildren()) { super.handleItemClick(view, id); } else { final ViewGroup vg = (ViewGroup) view; final CheckBox cb = (CheckBox) vg .findViewById(R.id.demo_list_checkbox); cb.performClick(); } } @Override public long getItemId(final int position) { return getTreeId(position); } }
Java
package pl.polidea.treeview.demo; import java.util.Set; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter { public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(activity, selected, treeStateManager, numberOfLevels); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = super.updateView(view, treeNodeInfo); final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); return viewLayout; } @Override public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) { switch (treeNodeInfo.getLevel()) { case 0: return new ColorDrawable(Color.WHITE); case 1: return new ColorDrawable(Color.GRAY); case 2: return new ColorDrawable(Color.YELLOW); default: return null; } } }
Java
package pl.polidea.treeview.demo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import pl.polidea.treeview.InMemoryTreeStateManager; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeBuilder; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import pl.polidea.treeview.TreeViewList; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; /** * Demo activity showing how the tree view can be used. * */ public class TreeViewListDemo extends Activity { private enum TreeType implements Serializable { SIMPLE, FANCY } private final Set<Long> selected = new HashSet<Long>(); private static final String TAG = TreeViewListDemo.class.getSimpleName(); private TreeViewList treeView; private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 }; private static final int LEVEL_NUMBER = 4; private TreeStateManager<Long> manager = null; private FancyColouredVariousSizesAdapter fancyAdapter; private SimpleStandardAdapter simpleAdapter; private TreeType treeType; private boolean collapsible; @SuppressWarnings("unchecked") @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); TreeType newTreeType = null; boolean newCollapsible; if (savedInstanceState == null) { manager = new InMemoryTreeStateManager<Long>(); final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager); for (int i = 0; i < DEMO_NODES.length; i++) { treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]); } Log.d(TAG, manager.toString()); newTreeType = TreeType.SIMPLE; newCollapsible = true; } else { manager = (TreeStateManager<Long>) savedInstanceState .getSerializable("treeManager"); newTreeType = (TreeType) savedInstanceState .getSerializable("treeType"); newCollapsible = savedInstanceState.getBoolean("collapsible"); } setContentView(R.layout.main_demo); treeView = (TreeViewList) findViewById(R.id.mainTreeView); fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected, manager, LEVEL_NUMBER); simpleAdapter = new SimpleStandardAdapter(this, selected, manager, LEVEL_NUMBER); setTreeAdapter(newTreeType); setCollapsible(newCollapsible); registerForContextMenu(treeView); } @Override protected void onSaveInstanceState(final Bundle outState) { outState.putSerializable("treeManager", manager); outState.putSerializable("treeType", treeType); outState.putBoolean("collapsible", this.collapsible); super.onSaveInstanceState(outState); } protected final void setTreeAdapter(final TreeType newTreeType) { this.treeType = newTreeType; switch (newTreeType) { case SIMPLE: treeView.setAdapter(simpleAdapter); break; case FANCY: treeView.setAdapter(fancyAdapter); break; default: treeView.setAdapter(simpleAdapter); } } protected final void setCollapsible(final boolean newCollapsible) { this.collapsible = newCollapsible; treeView.setCollapsible(this.collapsible); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { final MenuItem collapsibleMenu = menu .findItem(R.id.collapsible_menu_item); if (collapsible) { collapsibleMenu.setTitle(R.string.collapsible_menu_disable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_disable)); } else { collapsibleMenu.setTitle(R.string.collapsible_menu_enable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_enable)); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == R.id.simple_menu_item) { setTreeAdapter(TreeType.SIMPLE); } else if (item.getItemId() == R.id.fancy_menu_item) { setTreeAdapter(TreeType.FANCY); } else if (item.getItemId() == R.id.collapsible_menu_item) { setCollapsible(!this.collapsible); } else if (item.getItemId() == R.id.expand_all_menu_item) { manager.expandEverythingBelow(null); } else if (item.getItemId() == R.id.collapse_all_menu_item) { manager.collapseChildren(null); } else { return false; } return true; } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo; final long id = adapterInfo.id; final TreeNodeInfo<Long> info = manager.getNodeInfo(id); final MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.context_menu, menu); if (info.isWithChildren()) { if (info.isExpanded()) { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); } else { menu.findItem(R.id.context_menu_collapse).setVisible(false); } } else { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); menu.findItem(R.id.context_menu_collapse).setVisible(false); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(final MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); final long id = info.id; if (item.getItemId() == R.id.context_menu_collapse) { manager.collapseChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_all) { manager.expandEverythingBelow(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_item) { manager.expandDirectChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_delete) { manager.removeNodeRecursively(id); return true; } else { return super.onContextItemSelected(item); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.dslr.dashboard; import java.util.Calendar; import com.dslr.dashboard.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewStub; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; /** * This class is a slight improvement over the android time picker dialog. * It allows the user to select hour, minute, and second (the android picker * does not support seconds). It also has a configurable increment feature * (30, 5, and 1). */ public final class TimePickerDialog extends AlertDialog { public interface OnTimeSetListener { public void onTimeSet(int hourOfDay, int minute, int second); } private static final String PICKER_PREFS = "TimePickerPreferences"; private static final String INCREMENT_PREF = "increment"; private OnTimeSetListener listener; private SharedPreferences prefs; private Calendar calendar; private TextView timeText; private Button amPmButton; private PickerView hourPicker; private PickerView minutePicker; private PickerView secondPicker; /** * Construct a time picker with the supplied hour minute and second. * @param context * @param title Dialog title. * @param hourOfDay 0 to 23. * @param minute 0 to 60. * @param second 0 to 60. * @param showSeconds Show/hide the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, int hourOfDay, int minute, int second, final boolean showSeconds, OnTimeSetListener setListener) { this(context, title, showSeconds, setListener); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); hourPicker.pickerRefresh(); calendar.set(Calendar.MINUTE, minute); minutePicker.pickerRefresh(); calendar.set(Calendar.SECOND, second); if (showSeconds) { secondPicker.pickerRefresh(); } dialogRefresh(); } public TimePickerDialog(Context context, String title, TimeSpan timeSpan, OnTimeSetListener setListener) { this(context, title, true, setListener); calendar.set(Calendar.HOUR_OF_DAY, timeSpan.Hours()); hourPicker.pickerRefresh(); calendar.set(Calendar.MINUTE, timeSpan.Minutes()); minutePicker.pickerRefresh(); calendar.set(Calendar.SECOND, timeSpan.Seconds()); secondPicker.pickerRefresh(); dialogRefresh(); } /** * Construct a time picker with 'now' as the starting time. * @param context * @param title Dialog title. * @param showSeconds Show/hid the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, final boolean showSeconds, OnTimeSetListener setListener) { super(context); listener = setListener; prefs = context.getSharedPreferences(PICKER_PREFS, Context.MODE_PRIVATE); calendar = Calendar.getInstance(); // The default increment amount is stored in a shared preference. Look // it up. final int incPref = prefs.getInt(INCREMENT_PREF, IncrementValue.FIVE.ordinal()); final IncrementValue defaultIncrement = IncrementValue.values()[incPref]; // OK button setup. setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { if (listener == null) { return; } int seconds = showSeconds ? calendar.get(Calendar.SECOND) : 0; listener.onTimeSet( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), seconds); } }); // Cancel button setup. setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { cancel(); } }); // Set title and icon. if (title.length() != 0) { setTitle(title); setIcon(R.drawable.ic_dialog_time); } // Set the view for the body section of the AlertDialog. final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View body_view = inflater.inflate(R.layout.time_picker_dialog, null); setView(body_view); // Setup each of the components of the body section. timeText = (TextView) body_view.findViewById(R.id.picker_text); amPmButton = (Button) body_view.findViewById(R.id.picker_am_pm); amPmButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.AM_PM, Calendar.PM); } else { calendar.set(Calendar.AM_PM, Calendar.AM); } dialogRefresh(); } }); // Setup the three time fields. // if (DateFormat.is24HourFormat(getContext())) { body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.GONE); hourPicker = new PickerView(Calendar.HOUR_OF_DAY, "%02d"); // } else { // body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.VISIBLE); // hourPicker = new PickerView(Calendar.HOUR, "%d"); // } hourPicker.inflate(body_view, R.id.picker_hour, false, IncrementValue.ONE); minutePicker = new PickerView(Calendar.MINUTE, "%02d"); minutePicker.inflate(body_view, R.id.picker_minute, true, defaultIncrement); if (showSeconds) { secondPicker = new PickerView(Calendar.SECOND, "%02d"); secondPicker.inflate(body_view, R.id.picker_second, true, defaultIncrement); } dialogRefresh(); } private void dialogRefresh() { // AlarmTime time = new AlarmTime( // calendar.get(Calendar.HOUR_OF_DAY), // calendar.get(Calendar.MINUTE), // calendar.get(Calendar.SECOND)); // timeText.setText(time.timeUntilString(getContext())); if (calendar.get(Calendar.AM_PM) == Calendar.AM) { amPmButton.setText("AM"); } else { amPmButton.setText("PM"); } } /** * Enum that represents the states of the increment picker button. */ private enum IncrementValue { FIVE(5), ONE(1); private int value; IncrementValue(int value) { this.value = value; } public int value() { return value; } } /** * Helper class that wraps up the view elements of each number picker * (plus/minus button, text field, increment picker). */ private final class PickerView { private int calendarField; private String formatString; private EditText text = null; private Increment increment = null; private Button incrementValueButton = null; private Button plus = null; private Button minus = null; /** * Construct a numeric picker for the supplied calendar field and formats * it according to the supplied format string. * @param calendarField * @param formatString */ public PickerView(int calendarField, String formatString) { this.calendarField = calendarField; this.formatString = formatString; } /** * Inflates the ViewStub for this numeric picker. * @param parentView * @param resourceId * @param showIncrement * @param defaultIncrement */ public void inflate(View parentView, int resourceId, boolean showIncrement, IncrementValue defaultIncrement) { final ViewStub stub = (ViewStub) parentView.findViewById(resourceId); final View view = stub.inflate(); text = (EditText) view.findViewById(R.id.time_value); text.setOnFocusChangeListener(new TextChangeListener()); text.setOnEditorActionListener(new TextChangeListener()); increment = new Increment(defaultIncrement); incrementValueButton = (Button) view.findViewById(R.id.time_increment); incrementValueButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { increment.cycleToNext(); Editor editor = prefs.edit(); editor.putInt(INCREMENT_PREF, increment.value.ordinal()); editor.commit(); pickerRefresh(); } }); if (showIncrement) { incrementValueButton.setVisibility(View.VISIBLE); } else { incrementValueButton.setVisibility(View.GONE); } plus = (Button) view.findViewById(R.id.time_plus); TimeIncrementListener incrementListener = new TimeIncrementListener(); plus.setOnClickListener(incrementListener); plus.setOnTouchListener(incrementListener); plus.setOnLongClickListener(incrementListener); minus = (Button) view.findViewById(R.id.time_minus); TimeDecrementListener decrementListener= new TimeDecrementListener(); minus.setOnClickListener(decrementListener); minus.setOnTouchListener(decrementListener); minus.setOnLongClickListener(decrementListener); pickerRefresh(); } public void pickerRefresh() { int fieldValue = calendar.get(calendarField); if (calendarField == Calendar.HOUR && fieldValue == 0) { fieldValue = 12; } text.setText(String.format(formatString, fieldValue)); incrementValueButton.setText("+/- " + increment.nextValue().value()); plus.setText("+" + increment.value()); minus.setText("-" + increment.value()); dialogRefresh(); } private final class Increment { private IncrementValue value; public Increment(IncrementValue value) { this.value = value; } public IncrementValue nextValue() { int nextIndex = (value.ordinal() + 1) % IncrementValue.values().length; return IncrementValue.values()[nextIndex]; } public void cycleToNext() { value = nextValue(); } public int value() { return value.value(); } } /** * Listener that figures out what the next value should be when a numeric * picker plus/minus button is clicked. It will round up/down to the next * interval increment then increment by the increment amount on subsequent * clicks. */ private abstract class TimeAdjustListener implements View.OnClickListener, View.OnTouchListener, View.OnLongClickListener { protected abstract int sign(); private void adjust() { int currentValue = calendar.get(calendarField); int remainder = currentValue % increment.value(); if (remainder == 0) { calendar.roll(calendarField, sign() * increment.value()); } else { int difference; if (sign() > 0) { difference = increment.value() - remainder; } else { difference = -1 * remainder; } calendar.roll(calendarField, difference); } pickerRefresh(); } private Handler handler = new Handler(); private Runnable delayedAdjust = new Runnable() { public void run() { adjust(); handler.postDelayed(delayedAdjust, 150); } }; public void onClick(View v) { adjust(); } public boolean onLongClick(View v) { delayedAdjust.run(); return false; } public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { handler.removeCallbacks(delayedAdjust); } return false; } } private final class TimeIncrementListener extends TimeAdjustListener { @Override protected int sign() { return 1; } } private final class TimeDecrementListener extends TimeAdjustListener { @Override protected int sign() { return -1; } } /** * Listener to handle direct user input into the time picker text fields. * Updates after the editor confirmation button is picked or when the * text field loses focus. */ private final class TextChangeListener implements OnFocusChangeListener, OnEditorActionListener { private void handleChange() { try { int newValue = Integer.parseInt(text.getText().toString()); if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.HOUR_OF_DAY, 0); } else if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.PM) { calendar.set(Calendar.HOUR_OF_DAY, 12); } else { calendar.set(calendarField, newValue); } } catch (NumberFormatException e) {} pickerRefresh(); } public void onFocusChange(View v, boolean hasFocus) { handleChange(); } public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { handleChange(); return false; } } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.IOException; import java.util.ArrayList; import java.util.Vector; import org.xmlpull.v1.XmlPullParserException; import android.app.FragmentManager; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; public class DslrHelper { private static final String TAG = "DslrHelper"; private static DslrHelper mInstance = null; public static DslrHelper getInstance() { if (mInstance == null) mInstance = new DslrHelper(); return mInstance; } private DslrHelper() { } private DslrProperties mDslrProperties; private boolean mIsInitialized = false; private int mVendorId = 0; private int mProductId = 0; private PtpDevice mPtpDevice = null; public boolean getIsInitialized() { return mIsInitialized; } public PtpDevice getPtpDevice() { return mPtpDevice; } public int getVendorId() { return mVendorId; } public int getProductId() { return mProductId; } public void loadDslrProperties(Context context, PtpDevice ptpDevice, int vendorId, int productId) { if (context == null || ptpDevice == null) return; mPtpDevice = ptpDevice; mVendorId = vendorId; mProductId = productId; mDslrProperties = new DslrProperties(vendorId, productId); String deviceId = null; int propertyTitle = 0; String productName = String.format("%04X%04X", vendorId, productId) .toLowerCase(); boolean addItems = true; Log.d(TAG, "Loading DSLR properties for: " + productName); Resources res = context.getResources(); XmlResourceParser devices = context.getResources().getXml( R.xml.propertyvalues); int eventType = -1; DslrProperty dslrProperty = null; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_DOCUMENT) { } else if (eventType == XmlResourceParser.START_TAG) { String strName = devices.getName(); if (strName.equals("device")) { } else if (strName.equals("ptpproperty")) { int propertyCode = Integer.parseInt( devices.getAttributeValue(null, "id"), 16); deviceId = devices.getAttributeValue(null, "deviceId"); addItems = false; if (deviceId != null) { if (deviceId.toLowerCase().equals(productName)) { addItems = true; } } else { addItems = true; } if (addItems) { dslrProperty = mDslrProperties .addProperty(propertyCode); dslrProperty.setPropertyTitle( devices.getAttributeResourceValue(null, "title", 0)); } // if (deviceId != null // && deviceId.toLowerCase().equals(productName)) { // dslrProperty = mDslrProperties // .addProperty(propertyCode); // addItems = true; // } else { // dslrProperty = mDslrProperties // .getProperty(propertyCode); // if (dslrProperty == null) { // dslrProperty = mDslrProperties // .addProperty(propertyCode); // addItems = true; // } else // addItems = false; // } } else if (strName.equals("item")) { if (addItems) { int valueId = devices.getAttributeResourceValue(null, "value", 0); int nameId = devices.getAttributeResourceValue(null, "name", 0); int resId = devices.getAttributeResourceValue(null, "img", 0); Object value = null; String valueType = res.getResourceTypeName(valueId); if (valueType.equals("string")) { value = res.getString(valueId); } else if (valueType.equals("integer")) { value = res.getInteger(valueId); } dslrProperty.addPropertyValue(value, nameId, resId); } } } try { eventType = devices.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } mIsInitialized = true; Log.d(TAG, "Document End"); } public void createDialog(Context context, final int propertyCode, String dialogTitle, final ArrayList<PtpPropertyListItem> items, int selectedItem, DialogInterface.OnClickListener listener) { createDialog(context, propertyCode, dialogTitle, items, 0, selectedItem, listener); } public void createDialog(Context context, final int propertyCode, String dialogTitle, final ArrayList<PtpPropertyListItem> items, final int offset, int selectedItem, DialogInterface.OnClickListener listener) { if (!mIsInitialized) return; DialogInterface.OnClickListener mListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.d(TAG, items.get(which).getValue().getClass().toString()); Integer value = null; Object val = items.get(which).getValue(); if (val instanceof Long) val = (Long) val - offset; else if (val instanceof Integer) val = (Integer) val - offset; if (val != null) { // value = value - offset; mPtpDevice.setDevicePropValueCmd(propertyCode, val); } } }; if (listener != null) mListener = listener; CustomDialog.Builder customBuilder = new CustomDialog.Builder(context); customBuilder.setTitle(dialogTitle).setListItems(items, selectedItem) .setListOnClickListener(mListener); CustomDialog dialog = customBuilder.create(); dialog.show(); } // public void createDialog(FragmentManager fragmentManager, final int // propertyCode, String dialogTitle, final ArrayList<PtpPropertyListItem> // items, int selectedItem, DialogInterface.OnClickListener listener) { // Log.d(TAG, "CreateDialog"); // if (!mIsInitialized) // return; // DialogInterface.OnClickListener mListener = new // DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // mPtpDevice.setDevicePropValueCmd(propertyCode, // items.get(which).getValue()); // } // }; // if (listener != null) // mListener = listener; // PtpPropertyDialog dialog = new PtpPropertyDialog(items, selectedItem, // dialogTitle, mListener); // // dialog.show(fragmentManager.beginTransaction(), "dialog"); // } public void createDslrDialog(Context context, final int propertyCode, String dialogTitle, DialogInterface.OnClickListener listener) { createDslrDialog(context, propertyCode, 0, dialogTitle, listener); } public void createDslrDialog(Context context, final int propertyCode, final int offset, String dialogTitle, DialogInterface.OnClickListener listener) { if (!mIsInitialized) return; PtpProperty property = mPtpDevice.getPtpProperty(propertyCode); if (property == null) return; DslrProperty dslrProperty = mDslrProperties.getProperty(property .getPropertyCode()); if (dslrProperty == null) return; ArrayList<PtpPropertyListItem> items = null; int selectedItem = -1; Vector<?> propValues = property.getEnumeration(); if (propValues != null) { items = new ArrayList<PtpPropertyListItem>(); selectedItem = propValues.indexOf(property.getValue()); for (int i = 0; i < propValues.size(); i++) { PtpPropertyListItem item = dslrProperty .getPropertyByValue(propValues.get(i + offset)); if (item != null) items.add(item); } } else { int vFrom = 0; int vTo = 0; int vStep = 1; PtpProperty.PtpRange range = property.getRange(); if (range != null) { try { vFrom = (Integer) range.getMinimum(); vTo = (Integer) range.getMaximum(); vStep = (Integer) range.getIncrement(); items = new ArrayList<PtpPropertyListItem>(); for (int i = vFrom; i <= vTo; i += vStep) { PtpPropertyListItem item = dslrProperty .getPropertyByValue(i + offset); if (item != null) items.add(item); } } catch (Exception e) { } } else items = dslrProperty.valueNames(); selectedItem = dslrProperty.indexOfValue(property.getValue()); } String title = dialogTitle; if (dslrProperty.propertyTitle() != 0) title = (String)context.getText(dslrProperty.propertyTitle()); createDialog(context, propertyCode, title, items, selectedItem, listener); } // public void createDslrDialog(FragmentManager fragmentManager, final int // propertyCode, String dialogTitle, DialogInterface.OnClickListener // listener){ // if (!mIsInitialized) // return; // PtpProperty property = mPtpDevice.getPtpProperty(propertyCode); // if (property == null) // return; // // DslrProperty dslrProperty = // mDslrProperties.getProperty(property.getPropertyCode()); // if (dslrProperty == null) // return; // ArrayList<PtpPropertyListItem> items = null; // int selectedItem = -1; // Vector<?> propValues = property.getEnumeration(); // if (propValues != null){ // // items = new ArrayList<PtpPropertyListItem>(); // selectedItem = propValues.indexOf(property.getValue()); // // // for(int i = 0; i < propValues.size(); i++){ // PtpPropertyListItem item = // dslrProperty.getPropertyByValue(propValues.get(i)); // if (item != null) // items.add(item); // } // } // else { // int vFrom = 0; // int vTo = 0; // int vStep = 1; // // PtpProperty.PtpRange range = property.getRange(); // if (range != null) { // try { // vFrom = (Integer)range.getMinimum(); // vTo = (Integer)range.getMaximum(); // vStep = (Integer)range.getIncrement(); // // items = new ArrayList<PtpPropertyListItem>(); // // for(int i = vFrom; i <= vTo; i += vStep){ // PtpPropertyListItem item = dslrProperty.getPropertyByValue(i); // if (item != null) // items.add(item); // } // // } catch (Exception e) { // // } // } // else // items = dslrProperty.valueNames(); // selectedItem = dslrProperty.indexOfValue(property.getValue()); // } // createDialog(fragmentManager, propertyCode, dialogTitle, items, // selectedItem, listener); // } public void setDslrImg(ImageView view, PtpProperty property) { setDslrImg(view, 0, property); } public void setDslrImg(ImageView view, int offset, PtpProperty property) { setDslrImg(view, offset, property, true); } public void setDslrImg(ImageView view, int propertyCode) { setDslrImg(view, 0, propertyCode); } public void setDslrImg(ImageView view, int offset, int propertyCode) { if (mIsInitialized && mPtpDevice != null) { setDslrImg(view, offset, mPtpDevice.getPtpProperty(propertyCode), true); } } public void setDslrImg(ImageView view, PtpProperty property, boolean setEnableStatus) { setDslrImg(view, 0, property, setEnableStatus); } public void setDslrImg(ImageView view, int offset, PtpProperty property, boolean setEnableStatus) { if (property != null && view != null) { DslrProperty prop = mDslrProperties.getProperty(property .getPropertyCode()); if (prop == null) return; if (setEnableStatus) view.setEnabled(property.getIsWritable()); if (property.getDataType() <= 0x000a) { Integer value = (Integer) property.getValue(); view.setImageResource(prop.getImgResourceId(value + offset)); } else view.setImageResource(prop.getImgResourceId(property.getValue())); } } public void setDslrTxt(TextView view, PtpProperty property) { try { DslrProperty prop = mDslrProperties.getProperty(property .getPropertyCode()); if (prop == null) return; view.setEnabled(property.getIsWritable()); int propRes = prop.getnameResourceId(property.getValue()); if (propRes != 0) view.setText(propRes); else Log.d(TAG, String.format( "setDslrTxt value not found for property: %#x", property.getPropertyCode())); } catch (Exception e) { Log.d(TAG, String.format( "setDslrTxt exception, property: %#x exception: ", property.getPropertyCode()) + e.getMessage()); } } public void showApertureDialog(Context context) { Log.d(TAG, "Show aperture dialog"); if (!mIsInitialized) return; final PtpProperty property = mPtpDevice .getPtpProperty(PtpProperty.FStop); if (property != null) { final Vector<?> enums = property.getEnumeration(); int selectedItem = enums.indexOf(property.getValue()); if (enums != null) { final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); for (int i = 0; i < enums.size(); i++) { Integer value = (Integer) enums.get(i); Double val = ((double) value / 100); PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(val.toString()); item.setValue(enums.get(i)); items.add(item); } createDialog(context, PtpProperty.FStop, "Select aperture", items, selectedItem, null); } } } public void showExposureTimeDialog(Context context) { if (!mIsInitialized) return; PtpProperty property = mPtpDevice .getPtpProperty(PtpProperty.ExposureTime); if (property != null) { final Vector<?> enums = property.getEnumeration(); int selectedItem = enums.indexOf(property.getValue()); if (enums != null) { ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); for (int i = 0; i < enums.size(); i++) { String str; Long nesto = (Long) enums.get(i); if (nesto == 0xffffffffL) str = "Bulb"; else { if (nesto >= 10000) str = String.format("%.1f \"", (double) nesto / 10000); else str = String.format("1/%.1f", 10000 / (double) nesto); } PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(str); item.setValue(enums.get(i)); items.add(item); } createDialog(context, PtpProperty.ExposureTime, "Select exposure time", items, selectedItem, null); } } } public void showExposureCompensationDialog(Context context) { Log.d(TAG, "Show exposure compensation dialog"); if (!mIsInitialized) return; final PtpProperty property = mPtpDevice .getPtpProperty(PtpProperty.ExposureBiasCompensation); if (property != null) { final Vector<?> enums = property.getEnumeration(); int selectedItem = enums.indexOf(property.getValue()); if (enums != null) { final ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); for (int i = 0; i < enums.size(); i++) { Integer value = (Integer) enums.get(i); PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(String.format("%+.1f EV", (double) value / 1000)); item.setValue(enums.get(i)); items.add(item); } createDialog(context, PtpProperty.ExposureBiasCompensation, "Select EV compensation", items, selectedItem, null); } } } public void showInternalFlashCompensationDialog(Context context) { Log.d(TAG, "Show exposure compensation dialog"); if (!mIsInitialized) return; final PtpProperty property = mPtpDevice .getPtpProperty(PtpProperty.InternalFlashCompensation); if (property != null) { PtpProperty.PtpRange range = property.getRange(); if (range != null) { int selectedItem = -1; int i = 0; ArrayList<PtpPropertyListItem> items = new ArrayList<PtpPropertyListItem>(); for (int r = (Integer) range.getMinimum(); r <= (Integer) range .getMaximum(); r += (Integer) range.getIncrement()) { if (r == (Integer) property.getValue()) selectedItem = i; PtpPropertyListItem item = new PtpPropertyListItem(); item.setImage(-1); item.setTitle(String.format("%+.1f EV", (double) r / 6)); item.setValue(r); items.add(item); i++; } createDialog(context, PtpProperty.InternalFlashCompensation, "Select Internal Flash Compensation", items, selectedItem, null); } } } // enable/disable controls in view group public void enableDisableControls(ViewGroup viewGroup, boolean enable) { enableDisableControls(viewGroup, enable, false); } public void enableDisableControls(ViewGroup viewGroup, boolean enable, boolean checkOnlyVisible) { if (viewGroup != null) { boolean change = true; if (viewGroup.getTag() != null) { Boolean old = (Boolean) viewGroup.getTag(); if (old == enable) change = false; } if (change) { viewGroup.setTag(enable); for (int i = 0; i < viewGroup.getChildCount(); i++) { boolean checkView = viewGroup.getChildAt(i).getVisibility() == View.VISIBLE; if (!checkOnlyVisible) checkView = true; if (checkView) { if (enable) { if (viewGroup.getChildAt(i).getTag() != null) { viewGroup.getChildAt(i).setEnabled( (Boolean) viewGroup.getChildAt(i) .getTag()); viewGroup.getChildAt(i).setTag(null); } } else { viewGroup.getChildAt(i).setTag( viewGroup.getChildAt(i).isEnabled()); viewGroup.getChildAt(i).setEnabled(false); } } } } } } }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; public class PtpBuffer { static final int HDR_LEN = 12; private byte mData [] = null; private int mOffset = 0; public PtpBuffer(){ } public PtpBuffer(byte[] data) { mData = data; mOffset = 0; } public void wrap(byte[] data){ mData = data; mOffset = 0; } public boolean hasData(){ return mData != null; } public byte[] data(){ return mData; } public byte[] getOfssetArray(){ byte[] buf = new byte[mOffset]; System.arraycopy(mData, 0, buf, 0, mOffset); return buf; } public int length(){ if (mData != null) return mData.length; else return 0; } public int offset(){ return mOffset; } public void moveOffset(int moveBy){ mOffset += moveBy; } public void parse(){ mOffset = HDR_LEN; } public void setPacketLength(){ int tmpOffset = mOffset; mOffset = 0; put32(tmpOffset); mOffset = tmpOffset; } /** * Return the packet length * @return */ public int getPacketLength(){ return getS32(0); } /** * Return the packet type (1 command, 2 data) * @return */ public int getPacketType(){ return getU16(4); } /** * Return the packet code * @return */ public int getPacketCode(){ return getU16(6); } /** * Returns the session id * @return */ public int getSessionId(){ return getS32(8); } /** Unmarshals a signed 8 bit integer from a fixed buffer offset. */ public final int getS8 (int index) { return mData [index]; } /** Unmarshals an unsigned 8 bit integer from a fixed buffer offset. */ public final int getU8 (int index) { return 0xff & mData [index]; } /** Marshals an 8 bit integer (signed or unsigned) */ protected final void put8 (int value) { mData [mOffset++] = (byte) value; } /** Unmarshals the next signed 8 bit integer */ public final int nextS8 () { return mData [mOffset++]; } /** Unmarshals the next unsigned 8 bit integer */ public final int nextU8 () { return 0xff & mData [mOffset++]; } /** Unmarshals an array of signed 8 bit integers */ public final int [] nextS8Array () { int len = /* unsigned */ nextS32 (); int retval [] = new int [len]; for (int i = 0; i < len; i++) retval [i] = nextS8 (); return retval; } /** Unmarshals an array of 8 bit integers */ public final int [] nextU8Array () { int len = /* unsigned */ nextS32 (); int retval [] = new int [len]; for (int i = 0; i < len; i++) retval [i] = nextU8 (); return retval; } /** Unmarshals a signed 16 bit integer from a fixed buffer offset. */ public final int getS16 (int index) { int retval; retval = 0xff & mData [index++]; retval |= mData [index] << 8; return retval; } /** Unmarshals an unsigned 16 bit integer from a fixed buffer offset. */ public final int getU16 (int index) { return getU16(index, false); } public final int getU16(int index, boolean reverse) { int retval; if (reverse) { retval = 0xff00 & (mData[index++] << 8); retval |= 0xff & mData[index]; } else { retval = 0xff & mData [index++]; retval |= 0xff00 & (mData [index] << 8); } return retval; } /** Marshals a 16 bit integer (signed or unsigned) */ protected final void put16 (int value) { mData [mOffset++] = (byte) value; mData [mOffset++] = (byte) (value >> 8); } /** Unmarshals the next signed 16 bit integer */ public final int nextS16 () { int retval = getS16 (mOffset); mOffset += 2; return retval; } /** Unmarshals the next unsinged 16 bit integer */ public final int nextU16() { return nextU16(false); } public final int nextU16 (boolean reverse) { int retval = getU16 (mOffset, reverse); mOffset += 2; return retval; } /** Unmarshals an array of signed 16 bit integers */ public final int [] nextS16Array () { int len = /* unsigned */ nextS32 (); int retval [] = new int [len]; for (int i = 0; i < len; i++) retval [i] = nextS16 (); return retval; } /** Unmarshals an array of unsigned 16 bit integers */ public final int [] nextU16Array () { int len = /* unsigned */ nextS32 (); int retval [] = new int [len]; for (int i = 0; i < len; i++) retval [i] = nextU16 (); return retval; } /** Unmarshals a signed 32 bit integer from a fixed buffer offset. */ public final int getS32 (int index) { return getS32(index, false); } public final int getS32(int index, boolean reverse) { int retval; if (reverse) { retval = mData[index++] << 24; retval |= (0xff & mData[index++]) << 16; retval |= (0xff & mData[index++]) << 8; retval |= (0xff & mData[index]); } else { retval = (0xff & mData [index++]) ; retval |= (0xff & mData [index++]) << 8; retval |= (0xff & mData [index++]) << 16; retval |= mData [index ] << 24; } return retval; } /** Marshals a 32 bit integer (signed or unsigned) */ protected final void put32 (int value) { mData [mOffset++] = (byte) value; mData [mOffset++] = (byte) (value >> 8); mData [mOffset++] = (byte) (value >> 16); mData [mOffset++] = (byte) (value >> 24); } protected final void put32(long value) { mData [mOffset++] = (byte) value; mData [mOffset++] = (byte) (value >> 8); mData [mOffset++] = (byte) (value >> 16); mData [mOffset++] = (byte) (value >> 24); } /** Unmarshals the next signed 32 bit integer */ public final int nextS32 (boolean reverse) { int retval = getS32 (mOffset, reverse); mOffset += 4; return retval; } public final int nextS32 () { return nextS32(false); } /** Unmarshals an array of signed 32 bit integers. */ public final int [] nextS32Array () { int len = /* unsigned */ nextS32 (); int retval [] = new int [len]; for (int i = 0; i < len; i++) { retval [i] = nextS32 (); } return retval; } /** Unmarshals a signed 64 bit integer from a fixed buffer offset */ public final long getS64 (int index) { long retval = 0xffffffff & getS32 (index); retval |= (getS32 (index + 4) << 32); return retval; } /** Marshals a 64 bit integer (signed or unsigned) */ protected final void put64 (long value) { put32 ((int) value); put32 ((int) (value >> 32)); } /** Unmarshals the next signed 64 bit integer */ public final long nextS64 () { long retval = getS64 (mOffset); mOffset += 8; return retval; } /** Unmarshals an array of signed 64 bit integers */ public final long [] nextS64Array () { int len = /* unsigned */ nextS32 (); long retval [] = new long [len]; for (int i = 0; i < len; i++) retval [i] = nextS64 (); return retval; } // Java doesn't yet support 128 bit integers, // needed to support primitives like these: // getU128 // putU128 // nextU128 // nextU128Array // getS128 // putS128 // nextS128 // nextS128Array /** Unmarshals a string (or null) from a fixed buffer offset. */ public final String getString (int index) { int savedOffset = mOffset; String retval; mOffset = index; retval = nextString (); mOffset = savedOffset; return retval; } /** Marshals a string, of length at most 254 characters, or null. */ protected void putString (String s) { if (s == null) { put8 (0); return; } int len = s.length (); if (len > 254) throw new IllegalArgumentException (); put8 (len + 1); for (int i = 0; i < len; i++) put16 ((int) s.charAt (i)); put16 (0); } /** Unmarshals the next string (or null). */ public String nextString () { int len = nextU8 (); StringBuffer str; if (len == 0) return null; str = new StringBuffer (len); for (int i = 0; i < len; i++) str.append ((char) nextU16 ()); // drop terminal null str.setLength (len - 1); return str.toString (); } }
Java
package com.dslr.dashboard; import java.util.ArrayList; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class CustomDialog extends Dialog { public CustomDialog(Context context, int theme) { super(context, theme); } public CustomDialog(Context context) { super(context); } public void proba(int selectedItem){ ListView list = (ListView)this.findViewById(R.id.list); list.setItemChecked(selectedItem, true); setListviewSelection(list, selectedItem); } private static void setListviewSelection(final ListView list, final int pos) { list.post(new Runnable() { public void run() { list.setSelection(pos); View v = list.getChildAt(pos); if (v != null) { v.requestFocus(); } } }); } /** * Helper class for creating a custom dialog */ public static class Builder { private Context context; private String title; private String message; private String positiveButtonText; private String negativeButtonText; private View contentView; PtpPropertyListAdapter adapter; private ArrayList<PtpPropertyListItem> itemList; private int selectedItem = -1; private DialogInterface.OnClickListener positiveButtonClickListener, negativeButtonClickListener, listOnClickListener; public Builder(Context context) { this.context = context; } /** * Set the Dialog message from String * @param title * @return */ public Builder setMessage(String message) { this.message = message; return this; } /** * Set the Dialog message from resource * @param title * @return */ public Builder setMessage(int message) { this.message = (String) context.getText(message); return this; } /** * Set the Dialog title from resource * @param title * @return */ public Builder setTitle(int title) { this.title = (String) context.getText(title); return this; } /** * Set the Dialog title from String * @param title * @return */ public Builder setTitle(String title) { this.title = title; return this; } /** * Set a custom content view for the Dialog. * If a message is set, the contentView is not * added to the Dialog... * @param v * @return */ public Builder setContentView(View v) { this.contentView = v; return this; } public Builder setListitems(ArrayList<PtpPropertyListItem> items) { return this.setListItems(items, -1); } public Builder setListItems(ArrayList<PtpPropertyListItem> items, int selected){ this.itemList = items; this.selectedItem = selected; return this; } public Builder setListOnClickListener(DialogInterface.OnClickListener listener){ this.listOnClickListener = listener; return this; } /** * Set the positive button resource and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = (String) context .getText(positiveButtonText); this.positiveButtonClickListener = listener; return this; } /** * Set the positive button text and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = positiveButtonText; this.positiveButtonClickListener = listener; return this; } /** * Set the negative button resource and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = (String) context .getText(negativeButtonText); this.negativeButtonClickListener = listener; return this; } /** * Set the negative button text and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = negativeButtonText; this.negativeButtonClickListener = listener; return this; } /** * Create the custom dialog */ public CustomDialog create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // instantiate the dialog with the custom Theme final CustomDialog dialog = new CustomDialog(context, R.style.Dialog); View layout = inflater.inflate(R.layout.custom_dialog, null); dialog.addContentView(layout, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); // set the dialog title ((TextView) layout.findViewById(R.id.title)).setText(title); ListView list = (ListView)layout.findViewById(R.id.list); if (itemList != null){ adapter = new PtpPropertyListAdapter(context, itemList, selectedItem); list.setAdapter(adapter); list.setItemChecked(selectedItem, true); list.setSelection(selectedItem); //setListviewSelection(list, selectedItem); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { // user clicked a list item, make it "selected" //adapter.setSelectedItem(position); if (listOnClickListener != null) listOnClickListener.onClick(dialog, position); dialog.dismiss(); } }); } else list.setVisibility(View.GONE); // set the confirm button if (positiveButtonText != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setText(positiveButtonText); if (positiveButtonClickListener != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { positiveButtonClickListener.onClick( dialog, DialogInterface.BUTTON_POSITIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.positiveButton).setVisibility( View.GONE); } // set the cancel button if (negativeButtonText != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setText(negativeButtonText); if (negativeButtonClickListener != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { negativeButtonClickListener.onClick( dialog, DialogInterface.BUTTON_NEGATIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.negativeButton).setVisibility( View.GONE); } // set the content message if (message != null) { ((TextView) layout.findViewById( R.id.message)).setText(message); } else { ((TextView)layout.findViewById(R.id.message)).setVisibility(View.GONE); if (contentView != null) { // if no message set // add the contentView to the dialog body ((LinearLayout) layout.findViewById(R.id.content)) .removeAllViews(); ((LinearLayout) layout.findViewById(R.id.content)) .addView(contentView, new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } } dialog.setContentView(layout); return dialog; } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; public class AutoRepeatImageView extends ImageView { private long initialRepeatDelay = 500; private long repeatIntervalInMilliseconds = 100; private Runnable repeatClickWhileButtonHeldRunnable = new Runnable() { public void run() { //Perform the present repetition of the click action provided by the user // in setOnClickListener(). performClick(); //Schedule the next repetitions of the click action, using a faster repeat // interval than the initial repeat delay interval. postDelayed(repeatClickWhileButtonHeldRunnable, repeatIntervalInMilliseconds); } }; private void commonConstructorCode() { this.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if(action == MotionEvent.ACTION_DOWN) { //Just to be sure that we removed all callbacks, // which should have occurred in the ACTION_UP removeCallbacks(repeatClickWhileButtonHeldRunnable); //Perform the default click action. performClick(); //Schedule the start of repetitions after a one half second delay. postDelayed(repeatClickWhileButtonHeldRunnable, initialRepeatDelay); } else if(action == MotionEvent.ACTION_UP) { //Cancel any repetition in progress. removeCallbacks(repeatClickWhileButtonHeldRunnable); } //Returning true here prevents performClick() from getting called // in the usual manner, which would be redundant, given that we are // already calling it above. return true; } }); } public AutoRepeatImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); commonConstructorCode(); } public AutoRepeatImageView(Context context, AttributeSet attrs) { super(context, attrs); commonConstructorCode(); } public AutoRepeatImageView(Context context) { super(context); commonConstructorCode(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.hardware.usb.*; import android.util.Log; public class PtpUsbCommunicator extends PtpCommunicatorBase { private static String TAG = "PtpCommunicator"; private final PtpSession mSession; private UsbDeviceConnection mUsbDeviceConnection; private UsbEndpoint mWriteEp; private UsbEndpoint mReadEp; private UsbEndpoint mInterrupEp; private boolean mIsInitialized = false; public PtpUsbCommunicator(PtpSession session){ mSession = session; } public void initCommunicator( UsbDeviceConnection connection, UsbEndpoint writeEp, UsbEndpoint readEp, UsbEndpoint interrupEp) { mUsbDeviceConnection = connection; mWriteEp = writeEp; mReadEp = readEp; mInterrupEp = interrupEp; mIsInitialized = true; } public void closeCommunicator() { mIsInitialized = false; } public UsbDeviceConnection getUsbDeviceConnection() { return mUsbDeviceConnection; } public UsbEndpoint getInterrupEp() { return mInterrupEp; } public int getWriteEpMaxPacketSize() { return mWriteEp.getMaxPacketSize(); } public boolean getIsInitialized(){ return mIsInitialized; } protected synchronized void processCommand(PtpCommand cmd) throws Exception{ if (mIsInitialized) { boolean needAnotherRun = false; do { //Log.d(TAG, "+++ Sending command to device"); int bytesCount = 0; int retry = 0; byte[] data; synchronized (mSession) { data = cmd.getCommandPacket(mSession.getNextSessionID()); } while(true) { bytesCount = mUsbDeviceConnection.bulkTransfer(mWriteEp, data, data.length , 200); if (bytesCount != data.length) { Log.d(TAG, "+++ Command packet sent, bytes: " + bytesCount); retry += 1; if (retry > 2) throw new Exception("writen length != packet length"); } else break; } if (cmd.getHasSendData()){ data = cmd.getCommandDataPacket(); bytesCount = mUsbDeviceConnection.bulkTransfer(mWriteEp, data, data.length, 200); //Log.d(TAG, "+++ Command data packet sent, bytes: " + bytesCount); if (bytesCount != data.length) throw new Exception("writen length != packet length"); // give the device a bit time to process the data Thread.sleep(100); } data = new byte[mReadEp.getMaxPacketSize()]; while (true){ bytesCount = mUsbDeviceConnection.bulkTransfer(mReadEp, data, data.length, 200); // if (bytesCount < 1) // Log.d(TAG, "+++ Packet received, bytes: " + bytesCount); if (bytesCount > 0) { if (!cmd.newPacket(data, bytesCount)){ //data = null; if (cmd.hasResponse()) { needAnotherRun = cmd.weFinished(); break; } } } } // if (needAnotherRun) // Thread.sleep(300); } while (needAnotherRun); } } @Override public boolean getIsNetworkCommunicator() { return false; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.content.Context; import android.content.DialogInterface; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; public class FocusStackingDialog { private final static String TAG = FocusStackingDialog.class.getSimpleName(); private Context mContext; private DslrHelper mDslrHelper; private PtpDevice mPtpDevice; private View mView; private CustomDialog mDialog; private EditText mEditImageNumber, mEditFocusStep; private RadioButton mFocusDown, mFocusUp; private Button mStartFocusStacking; private CheckBox mFocusFirst; private int mFocusImages = 5; private int mFocusStep = 10; private boolean mFocusDirectionDown = true; private boolean mFocusFocusFirst = false; public FocusStackingDialog(Context context) { mContext = context; mDslrHelper = DslrHelper.getInstance(); mPtpDevice = mDslrHelper.getPtpDevice(); if (mPtpDevice != null) { mFocusImages = mPtpDevice.getFocusImages(); mFocusStep = mPtpDevice.getFocusStep(); mFocusDirectionDown = mPtpDevice.getFocusDirectionDown(); mFocusFocusFirst = mPtpDevice.getFocusFocusFirst(); } LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.focusstackingdialog, null); mEditImageNumber = (EditText)mView.findViewById(R.id.focus_stacking_Number); mEditFocusStep = (EditText)mView.findViewById(R.id.focus_stacking_Step); mFocusDown = (RadioButton)mView.findViewById(R.id.focus_stacking_RadioDown); mFocusUp = (RadioButton)mView.findViewById(R.id.focus_stacking_RadioUp); mStartFocusStacking = (Button)mView.findViewById(R.id.focus_stacking_start); mFocusFirst = (CheckBox)mView.findViewById(R.id.focus_stacking_focus_first); mStartFocusStacking.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mFocusImages = Integer.valueOf(mEditImageNumber.getText().toString()); mFocusStep = Integer.valueOf(mEditFocusStep.getText().toString()); mFocusDirectionDown = mFocusDown.isChecked(); Log.d(TAG, "Focus direction down: " + mFocusDirectionDown); Log.d(TAG, "Focus images: " + mFocusImages); Log.d(TAG, "Focus step: " + mFocusStep); mDialog.dismiss(); mPtpDevice.startFocusStacking(mFocusImages, mFocusStep, mFocusDirectionDown, mFocusFocusFirst); } }); // mFocusUp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Log.d(TAG, "Focus direction down: " + isChecked); // mFocusDirectionDown = isChecked; // } // }); // mEditImageNumber.addTextChangedListener(new TextWatcher() { // // public void onTextChanged(CharSequence s, int start, int before, int count) { // // TODO Auto-generated method stub // // } // // public void beforeTextChanged(CharSequence s, int start, int count, // int after) { // // TODO Auto-generated method stub // // } // // public void afterTextChanged(Editable s) { // mFocusImages = Integer.valueOf(s.toString()); // Log.d(TAG, "Focus images changed: " + mFocusImages); // } // }); // mEditFocusStep.addTextChangedListener(new TextWatcher() { // // public void onTextChanged(CharSequence s, int start, int before, int count) { // // TODO Auto-generated method stub // // } // // public void beforeTextChanged(CharSequence s, int start, int count, // int after) { // // TODO Auto-generated method stub // // } // // public void afterTextChanged(Editable s) { // mFocusStep = Integer.valueOf(s.toString()); // Log.d(TAG, "Focus step changed: " + mFocusStep); // } // }); } private void initDialog(){ mEditImageNumber.setText(Integer.toString(mFocusImages)); mEditFocusStep.setText(Integer.toString(mFocusStep)); mFocusDown.setChecked(mFocusDirectionDown); mFocusFirst.setChecked(mFocusFocusFirst); } public void show() { initDialog(); CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Focus Stacking settings") .setContentView(mView); mDialog = customBuilder .create(); mDialog.show(); } }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.TimeZone; import android.graphics.Bitmap; import android.util.Log; public class PtpObjectInfo { private final static String TAG = "PtpObjectInfo"; public int objectId; public int storageId; // 8.1 public int objectFormatCode; // 6.2 public int protectionStatus; // 0 r/w, 1 r/o public int objectCompressedSize; public int thumbFormat; // 6.2 public int thumbCompressedSize; public int thumbPixWidth; public int thumbPixHeight; public int imagePixWidth; public int imagePixHeight; public int imageBitDepth; public int parentObject; public int associationType; // 6.4 public int associationDesc; // 6.4 public int sequenceNumber; // (ordered associations) public String filename; // (sans path) private String mCaptureDate; // DateTime string private String mModificationDate; // DateTime string public String keywords; public Date captureDate = null; public Date modificationDate = null; public PtpObjectInfo(int objectIdentification, PtpBuffer buf){ objectId = objectIdentification; if (buf != null) parse(buf); } public Bitmap thumb = null; public void parse (PtpBuffer buf) { buf.parse(); storageId = buf.nextS32 (); objectFormatCode = buf.nextU16 (); protectionStatus = buf.nextU16 (); objectCompressedSize = /* unsigned */ buf.nextS32 (); thumbFormat = buf.nextU16 (); thumbCompressedSize = /* unsigned */ buf.nextS32 (); thumbPixWidth = /* unsigned */ buf.nextS32 (); thumbPixHeight = /* unsigned */ buf.nextS32 (); imagePixWidth = /* unsigned */ buf.nextS32 (); imagePixHeight = /* unsigned */ buf.nextS32 (); imageBitDepth = /* unsigned */ buf.nextS32 (); parentObject = buf.nextS32 (); associationType = buf.nextU16 (); associationDesc = buf.nextS32 (); sequenceNumber = /* unsigned */ buf.nextS32 (); filename = buf.nextString (); mCaptureDate = buf.nextString (); mModificationDate = buf.nextString (); keywords = buf.nextString (); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); captureDate = sdf.parse(mCaptureDate, new ParsePosition(0)); modificationDate = sdf.parse(mModificationDate, new ParsePosition(0)); //Log.d(TAG, "CaptureDate: " + mCaptureDate + " Parsed: " + captureDate.toString()); } // public PtpObjectInfo clone() { // PtpObjectInfo obj = new PtpObjectInfo(objectId, null); // // obj.storageId = this.storageId; // obj.objectFormatCode = this.objectFormatCode; // obj.protectionStatus = this.protectionStatus; // obj.objectCompressedSize = /* unsigned */ this.objectCompressedSize; // // obj.thumbFormat = this.thumbFormat; // obj.thumbCompressedSize = /* unsigned */ this.thumbCompressedSize; // obj.thumbPixWidth = /* unsigned */ this.thumbPixWidth; // obj.thumbPixHeight = /* unsigned */ this.thumbPixHeight; // // obj.imagePixWidth = /* unsigned */ this.imagePixWidth; // obj.imagePixHeight = /* unsigned */ this.imagePixHeight; // obj.imageBitDepth = /* unsigned */ this.imageBitDepth; // obj.parentObject = this.parentObject; // // obj.associationType = this.associationType; // obj.associationDesc = this.associationDesc; // obj.sequenceNumber = /* unsigned */ this.sequenceNumber; // obj.filename = this.filename; // // obj.captureDate = this.captureDate; // obj.modificationDate = this.modificationDate; // obj.keywords = this.keywords; // // return obj; // } /** ObjectFormatCode: unrecognized non-image format */ public static final int Undefined = 0x3000; /** ObjectFormatCode: associations include folders and panoramas */ public static final int Association = 0x3001; /** ObjectFormatCode: */ public static final int Script = 0x3002; /** ObjectFormatCode: */ public static final int Executable = 0x3003; /** ObjectFormatCode: */ public static final int Text = 0x3004; /** ObjectFormatCode: */ public static final int HTML = 0x3005; /** ObjectFormatCode: */ public static final int DPOF = 0x3006; /** ObjectFormatCode: */ public static final int AIFF = 0x3007; /** ObjectFormatCode: */ public static final int WAV = 0x3008; /** ObjectFormatCode: */ public static final int MP3 = 0x3009; /** ObjectFormatCode: */ public static final int AVI = 0x300a; /** ObjectFormatCode: */ public static final int MPEG = 0x300b; /** ObjectFormatCode: */ public static final int ASF = 0x300c; /** ObjectFormatCode: QuickTime video */ public static final int QuickTime = 0x300d; /** ImageFormatCode: unknown image format */ public static final int UnknownImage = 0x3800; /** * ImageFormatCode: EXIF/JPEG version 2.1, the preferred format * for thumbnails and for images. */ public static final int EXIF_JPEG = 0x3801; /** * ImageFormatCode: Uncompressed TIFF/EP, the alternate format * for thumbnails. */ public static final int TIFF_EP = 0x3802; /** ImageFormatCode: FlashPix image format */ public static final int FlashPix = 0x3803; /** ImageFormatCode: MS-Windows bitmap image format */ public static final int BMP = 0x3804; /** ImageFormatCode: Canon camera image file format */ public static final int CIFF = 0x3805; // 3806 is reserved /** ImageFormatCode: Graphics Interchange Format (deprecated) */ public static final int GIF = 0x3807; /** ImageFormatCode: JPEG File Interchange Format */ public static final int JFIF = 0x3808; /** ImageFormatCode: PhotoCD Image Pac*/ public static final int PCD = 0x3809; /** ImageFormatCode: Quickdraw image format */ public static final int PICT = 0x380a; /** ImageFormatCode: Portable Network Graphics */ public static final int PNG = 0x380b; /** ImageFormatCode: Tag Image File Format */ public static final int TIFF = 0x380d; /** ImageFormatCode: TIFF for Information Technology (graphic arts) */ public static final int TIFF_IT = 0x380e; /** ImageFormatCode: JPEG 2000 baseline */ public static final int JP2 = 0x380f; /** ImageFormatCode: JPEG 2000 extended */ public static final int JPX = 0x3810; /** * Returns true for format codes that have the image type bit set. */ public boolean isImage () { return (objectFormatCode & 0xf800) == 0x3800; } /** * Returns true for some recognized video format codes. */ public boolean isVideo () { switch (objectFormatCode) { case AVI: case MPEG: case ASF: case QuickTime: return true; } return false; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public class LvSurfaceHelper { public PtpLiveViewObject mLvo; public boolean mHistogramEnabled = true; public boolean mHistogramSeparate = true; public PtpProperty mLvZoom; // public LayoutMain.TouchMode mTouchMode; // public int mMfDriveStep; // public int mFocusCurrent; // public int mFocusMax; public int mOsdDisplay; public LvSurfaceHelper(PtpLiveViewObject lvo, PtpProperty lvZoom, int osdDisplay){ mLvo = lvo; mLvZoom = lvZoom; mOsdDisplay = osdDisplay; } // public LvSurfaceHelper(PtpLiveViewObject lvo, PtpProperty lvZoom, LayoutMain.TouchMode touchMode, int mfDriveStep, int focusCurrent, int focusMax, int osdDisplay) { // mLvo = lvo; // mLvZoom = lvZoom; // mTouchMode = touchMode; // mMfDriveStep = mfDriveStep; // mFocusCurrent = focusCurrent; // mFocusMax = focusMax; // mOsdDisplay = osdDisplay; // } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.content.DialogInterface; import android.view.ActionProvider; import android.view.LayoutInflater; import android.view.View; public class ImagePreviewActionProvider extends ActionProvider { public enum ImageMenuButtonEnum { PhoneImages, CameraImages, Download, SelectAll, Delete, LoadInfos } public interface ImageMenuClickListener { public void onImageButtonClick(ImageMenuButtonEnum btnEnum); } private ImageMenuClickListener mImageMenuClickListener; public void setImageMenuClickListener(ImageMenuClickListener listener) { mImageMenuClickListener = listener; } private Context mContext; private CheckableImageView mLoadInfos, mDownload, mSelectAll, mDelete, mGalleryPhone, mGalleryCamera; private boolean mIsEnabled = true; private boolean mDownloadVisible = false; private boolean mDownloadImageEnabled = false; private boolean mSelectionModeEnabled = false; private boolean mCameraGalleryEnabled = false; public boolean getIsEnabled() { return mIsEnabled; } public void setIsEnabled(boolean value) { mIsEnabled = value; } public boolean getDownloadImageEnabled() { return mDownloadImageEnabled; } public void setDownloadImageEnabled(boolean value) { mDownloadImageEnabled = value; } public boolean getDownloadVisible() { return mDownloadVisible; } public void setDownloadVisible(boolean value) { mDownloadVisible = value; setDownloadVisibility(); } public boolean getIsSelectionModeEnabled() { return mSelectionModeEnabled; } public void setIsSelectionModeEnabled(boolean value) { mSelectionModeEnabled = value; setSelectionMode(); } public boolean getIsCameraGalleryEnabled() { return mCameraGalleryEnabled; } public void setIsCameraGalleryEnabled(boolean value) { mCameraGalleryEnabled = value; mGalleryCamera.setChecked(mCameraGalleryEnabled); mGalleryPhone.setChecked(!mCameraGalleryEnabled); mDownload.setVisibility(mCameraGalleryEnabled ? View.VISIBLE : View.GONE); mLoadInfos.setVisibility(mCameraGalleryEnabled ? View.VISIBLE : View.GONE); } public ImagePreviewActionProvider(Context context) { super(context); mContext = context; } private void setDownloadVisibility() { if (mDownload != null) { mDownload.setVisibility(mDownloadVisible ? View.VISIBLE : View.GONE); mDownload.setChecked(mDownloadImageEnabled); } if (mLoadInfos != null) mLoadInfos.setVisibility(mDownloadVisible ? View.VISIBLE : View.GONE); } private void setSelectionMode() { if (mSelectAll != null) mSelectAll.setChecked(mSelectionModeEnabled); } @Override public View onCreateActionView() { LayoutInflater layoutInflater = LayoutInflater.from(mContext); View view = layoutInflater.inflate(R.layout.image_preview_menu_provider,null); mGalleryPhone = (CheckableImageView)view.findViewById(R.id.phone_images); mGalleryCamera = (CheckableImageView)view.findViewById(R.id.camera_images); mLoadInfos = (CheckableImageView)view.findViewById(R.id.load_object_info); mDownload = (CheckableImageView)view.findViewById(R.id.download_img); setDownloadVisibility(); mSelectAll = (CheckableImageView)view.findViewById(R.id.select_all); setSelectionMode(); mDelete = (CheckableImageView)view.findViewById(R.id.delete_selected); setIsCameraGalleryEnabled(false); mDownload.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { if (mIsEnabled) { mDownloadImageEnabled = !mDownloadImageEnabled; setDownloadVisibility(); } return true; } }); mDownload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) { if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.Download); } } }); mSelectAll.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { if (mIsEnabled) { mSelectionModeEnabled = !mSelectionModeEnabled; setSelectionMode(); } return true; } }); mSelectAll.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) { if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.SelectAll); } } }); mDelete.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) showDeleteDialog(); } }); mLoadInfos.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) { if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.LoadInfos); } } }); mGalleryPhone.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) { if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.PhoneImages); } } }); mGalleryCamera.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mIsEnabled) { if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.CameraImages); } } }); return view; } private void showDeleteDialog() { CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Image deletion") .setMessage("Delete selected images)") .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (mImageMenuClickListener != null) mImageMenuClickListener.onImageButtonClick(ImageMenuButtonEnum.Delete); } }); CustomDialog dialog = customBuilder.create(); dialog.show(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; public class DslrProperty { private int mPropertyCode; private int mPropertyTitle; private ArrayList<String> mValues; private ArrayList<PtpPropertyListItem> mPropertyValues; public DslrProperty(int ptpPropertyCode){ mPropertyCode = ptpPropertyCode; mPropertyValues = new ArrayList<PtpPropertyListItem>(); mValues = new ArrayList<String>(); } public int propertyCode(){ return mPropertyCode; } public int propertyTitle() { return mPropertyTitle; } public void setPropertyTitle(int value) { mPropertyTitle = value; } public ArrayList<PtpPropertyListItem> valueNames(){ return mPropertyValues; } public ArrayList<String> values(){ return mValues; } public int indexOfValue(Object value){ return mValues.indexOf(value.toString()); } public int getImgResourceId(Object value){ PtpPropertyListItem prop = getPropertyByValue(value); if (prop == null) return 0; return prop.getImage(); } public int getnameResourceId(Object value){ PtpPropertyListItem prop = getPropertyByValue(value); if (prop == null) return 0; return prop.getNameId(); } public PtpPropertyListItem getPropertyByValue(Object value){ int index = indexOfValue(value); if (index == -1) return null; return mPropertyValues.get(index); } public PtpPropertyListItem addPropertyValue(Object value, int nameId, int imgId){ PtpPropertyListItem item = new PtpPropertyListItem(value, nameId, imgId); mPropertyValues.add(item); mValues.add(value.toString()); return item; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import com.dslr.dashboard.ImagePreviewActionProvider.ImageMenuButtonEnum; import android.app.Activity; import android.app.Fragment; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; public class DslrImageBrowserActivity extends ActivityBase { private final static String TAG = "DslrImageBroseActivity"; private DslrHelper mDslrHelper; private GridView mImageGallery; private TextView mProgressText, mDownloadFile; private ProgressBar mDownloadProgress; private LinearLayout mProgressLayout, mDownloadProgressLayout; private MenuItem mMenuItem; private ImagePreviewActionProvider mMenuProvider; private ImageGalleryAdapter mImageGalleryAdapter; private ArrayList<ImageObjectHelper> mImagesArray; private String mSdramSavingLocation = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"DSLR").getAbsolutePath(); private boolean mUseInternalViewer = true; private boolean mIsCameraGalleryEnabled = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); String tmp = mPrefs.getString(PtpDevice.PREF_KEY_SDRAM_LOCATION, ""); if (tmp.equals("")) { Editor editor = mPrefs.edit(); editor.putString(PtpDevice.PREF_KEY_SDRAM_LOCATION, mSdramSavingLocation); editor.commit(); } else mSdramSavingLocation = tmp; mUseInternalViewer = mPrefs.getBoolean(PtpDevice.PREF_KEY_GENERAL_INTERNAL_VIEWER, true); setContentView(R.layout.activity_dslr_image_browse); mDslrHelper = DslrHelper.getInstance(); mMenuProvider = new ImagePreviewActionProvider(this); mMenuProvider.setDownloadVisible(true); mMenuProvider.setImageMenuClickListener(new ImagePreviewActionProvider.ImageMenuClickListener() { public void onImageButtonClick(ImageMenuButtonEnum btnEnum) { switch(btnEnum) { case Download: downloadSelectedImages(); break; case SelectAll: for (ImageObjectHelper obj : mImagesArray) { obj.isChecked = true; } mImageGalleryAdapter.notifyDataSetChanged(); break; case Delete: if (mIsCameraGalleryEnabled) deleteSelectedImages(); else { deleteSelectedPhoneImages(); } break; case LoadInfos: getObjectInfosFromCamera(); break; case PhoneImages: switchToPhoneGallery(); break; case CameraImages: switchToCameraGallery(); break; } } }); mProgressText = (TextView) findViewById(R.id.browsetxtLoading); mProgressLayout = (LinearLayout) findViewById(R.id.browseprogresslayout); mDownloadFile = (TextView)findViewById(R.id.downloadfile); mDownloadProgress = (ProgressBar)findViewById(R.id.downloadprogress); mDownloadProgressLayout = (LinearLayout)findViewById(R.id.downloadprogresslayout); mImagesArray = new ArrayList<ImageObjectHelper>(); mImageGalleryAdapter = new ImageGalleryAdapter(this, mImagesArray); mImageGallery = (GridView) findViewById(R.id.img_gallery); mImageGallery.setAdapter(mImageGalleryAdapter); mImageGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Log.d(TAG, "Position: " + position + " id: " + id); ImageObjectHelper helper = (ImageObjectHelper)parent.getItemAtPosition(position); if (helper != null) { if (mMenuProvider.getIsSelectionModeEnabled()) { helper.isChecked = !helper.isChecked; mImageGalleryAdapter.notifyDataSetChanged(); } else { displayImage(helper); } } } }); mImageGallery.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { Log.d(TAG, "Long click Position: " + position + " id: " + id); mMenuProvider.setIsSelectionModeEnabled(!mMenuProvider.getIsSelectionModeEnabled()); ImageObjectHelper helper = (ImageObjectHelper)parent.getItemAtPosition(position); helper.isChecked = !helper.isChecked; // mImageGallery.setSelected(true); mImageGalleryAdapter.notifyDataSetChanged(); return true; } }); } private void switchToPhoneGallery() { if (mIsCameraGalleryEnabled) { mIsCameraGalleryEnabled = false; mMenuProvider.setIsCameraGalleryEnabled(mIsCameraGalleryEnabled); loadImagesFromPhone(); } } private void switchToCameraGallery() { if (!mIsCameraGalleryEnabled) { if (DslrHelper.getInstance().getPtpDevice() != null) { if (DslrHelper.getInstance().getPtpDevice().getIsPtpDeviceInitialized()) { mIsCameraGalleryEnabled = true; mMenuProvider.setIsCameraGalleryEnabled(mIsCameraGalleryEnabled); initDisplay(); } } } } private void hideProgressBar() { runOnUiThread(new Runnable() { public void run() { mProgressLayout.setVisibility(View.GONE); mImageGallery.setEnabled(true); mMenuItem.setEnabled(true); mMenuProvider.setIsEnabled(true); mImageGalleryAdapter.notifyDataSetChanged(); } }); } private void showProgressBar(final String text, final boolean showDownloadProgress) { runOnUiThread(new Runnable() { public void run() { mProgressText.setText(text); mProgressLayout.setVisibility(View.VISIBLE); if (showDownloadProgress) { mDownloadProgressLayout.setVisibility(View.VISIBLE); mDownloadProgress.setProgress(0); } else mDownloadProgressLayout.setVisibility(View.GONE); mImageGallery.setEnabled(false); mMenuProvider.setIsEnabled(false); mMenuItem.setEnabled(false); } }); } private void setProgressFileName(final String fileName, final int fileSize) { runOnUiThread(new Runnable() { public void run() { mDownloadFile.setText(fileName); mDownloadProgress.setProgress(0); mDownloadProgress.setMax(fileSize); } }); } private void updateProgress(final ImageObjectHelper obj) { runOnUiThread(new Runnable() { public void run() { mDownloadProgress.setProgress(obj.progress); } }); } private void downloadSelectedImages() { showProgressBar("Downloading selected images", true); new Thread(new Runnable() { public void run() { for (final ImageObjectHelper obj : mImagesArray) { if (obj.isChecked) { setProgressFileName(obj.objectInfo.filename, obj.objectInfo.objectCompressedSize); mDslrHelper.getPtpDevice().getObjectFromCamera(obj, new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() { public void onProgress(int offset) { obj.progress = offset; updateProgress(obj); } }); createThumb(obj); obj.isChecked = false; } } hideProgressBar(); } }).start(); } private void deleteSelectedImages() { showProgressBar("Deleting selected images", true); new Thread(new Runnable() { public void run() { for(int i = mImageGalleryAdapter.getCount()-1; i >= 0; i--){ ImageObjectHelper item = mImageGalleryAdapter.items().get(i); if (item.isChecked) { setProgressFileName(item.objectInfo.filename, 0); mDslrHelper.getPtpDevice().deleteObjectCmd(item); mImageGalleryAdapter.items().remove(i); } } hideProgressBar(); } }).start(); } private void displayImage(ImageObjectHelper obj) { if (mIsCameraGalleryEnabled) displayDslrImage(obj); else displayDownloadedImage(obj); } private void displayDownloadedImage(ImageObjectHelper obj) { runOnUiThread(new Runnable() { public void run() { mProgressLayout.setVisibility(View.GONE); } }); Uri uri = Uri.fromFile(obj.file); if (mUseInternalViewer) { Intent ipIntent = new Intent(this, ImagePreviewActivity.class); ipIntent.setAction(Intent.ACTION_VIEW); ipIntent.setData(uri); this.startActivity(ipIntent); } else { Intent it = new Intent(Intent.ACTION_VIEW); it.setDataAndType(uri, "image/*"); startActivity(it); } } private void displayDslrImage(final ImageObjectHelper obj) { Log.d(TAG, "sdcard image clicked"); if (mMenuProvider.getDownloadImageEnabled()) { File f = mDslrHelper.getPtpDevice().getObjectSaveFile(obj.objectInfo.filename, true); if (!f.exists()) { showProgressBar("Download image for display", true); new Thread(new Runnable() { public void run() { setProgressFileName(obj.objectInfo.filename, obj.objectInfo.objectCompressedSize); mDslrHelper.getPtpDevice().getObjectFromCamera(obj, new PtpPartialObjectProccessor.PtpPartialObjectProgressListener() { public void onProgress(int offset) { obj.progress = offset; updateProgress(obj); } }); hideProgressBar(); createThumb(obj); displayDownloadedImage(obj); } }).start(); } else { obj.file = f; displayDownloadedImage(obj); } } else { byte[] buf = mDslrHelper.getPtpDevice().getLargeThumb( obj.objectInfo.objectId); if (buf != null) { Bitmap bmp = BitmapFactory.decodeByteArray(buf, 12, buf.length - 12); if (bmp != null) { Log.d(TAG, "Display DSLR image"); Intent dslrIntent = new Intent(this, ImagePreviewActivity.class); ByteArrayOutputStream bs = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 85, bs); dslrIntent.putExtra("data", bs.toByteArray()); this.startActivity(dslrIntent); } } } } private void initDisplay() { runOnUiThread(new Runnable() { public void run() { mProgressLayout.setVisibility(View.GONE); loadObjectInfosFromCamera(); } }); } private void loadObjectInfosFromCamera() { mImagesArray.clear(); for (PtpStorageInfo store : mDslrHelper.getPtpDevice().getPtpStorages().values()) { for (PtpObjectInfo obj : store.objects.values()) { addObjectFromCamera(obj, false); } } Collections.sort(mImagesArray, new ImageObjectHelperComparator()); mImageGalleryAdapter.notifyDataSetChanged(); } private class ImageObjectHelperComparator implements Comparator<ImageObjectHelper> { public int compare(ImageObjectHelper lhs, ImageObjectHelper rhs) { return rhs.objectInfo.captureDate .compareTo(lhs.objectInfo.captureDate); } } private void addObjectFromCamera(PtpObjectInfo obj, boolean notifyDataSet) { boolean addThisObject = true; // if slot2 mode is not Sequential recording if (mDslrHelper.getPtpDevice().getSlot2Mode() > 0) { int storage = obj.storageId >> 16; addThisObject = (storage & mDslrHelper.getPtpDevice().getActiveSlot()) == storage; // if this is not the active slot // if ((obj.storageId >> 16) != mDslrHelper.getPtpDevice().getActiveSlot()) // addThisObject = false; } if (addThisObject) { switch (obj.objectFormatCode) { case 0x3000: case 0x3801: ImageObjectHelper imgObj = new ImageObjectHelper(); imgObj.objectInfo = obj; imgObj.galleryItemType = ImageObjectHelper.DSLR_PICTURE; imgObj.file = new File(mSdramSavingLocation + "/.dslrthumbs/" + obj.filename + ".jpg"); mImagesArray.add(imgObj); if (notifyDataSet) mImageGalleryAdapter.notifyDataSetChanged(); break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); getMenuInflater().inflate(R.menu.menu_image_browse, menu); mMenuItem = menu.findItem(R.id.menu_image_browse); mMenuItem.setActionProvider(mMenuProvider); return true; } @Override protected void onRestart() { Log.d(TAG, "onRestart"); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart"); super.onStart(); } private void getObjectInfosFromCamera() { if (mDslrHelper.getIsInitialized()) { if (!mDslrHelper.getPtpDevice().getIsPtpObjectsLoaded()) { mProgressLayout.setVisibility(View.VISIBLE); new Thread(new Runnable() { public void run() { mDslrHelper.getPtpDevice().loadObjectInfos(); initDisplay(); } }).start(); } else initDisplay(); } } @Override protected void onResume() { Log.d(TAG, "onResume"); if (mIsCameraGalleryEnabled) { // we are in camera gallery mode if (mDslrHelper.getIsInitialized()) { initDisplay(); } } else { loadImagesFromPhone(); } super.onResume(); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent"); super.onNewIntent(intent); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); Log.d(TAG, "onAttachFragment"); } @Override protected void serviceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service) { // TODO Auto-generated method stub } @Override protected void serviceDisconnected(Class<?> serviceClass, ComponentName name) { // TODO Auto-generated method stub } private void loadImagesFromPhone(){ Log.d(TAG, "LoadImagesFromPhone"); mImagesArray.clear(); File f = new File(mSdramSavingLocation); if (f.exists()){ File[] phoneFiles = f.listFiles(); for(int i = 0; i < phoneFiles.length; i++){ if (phoneFiles[i].isFile()){ final ImageObjectHelper helper = new ImageObjectHelper(); helper.file = phoneFiles[i]; helper.galleryItemType = ImageObjectHelper.PHONE_PICTURE; createThumb(helper); mImagesArray.add(helper); } } } Log.d(TAG, "Images from phone - NotifyDataSetChanged"); mImageGalleryAdapter.notifyDataSetChanged(); } private void createThumb(ImageObjectHelper helper) { if (!tryLoadThumb(helper)) { String fExt = helper.getFileExt(helper.file.toString()); if (fExt.equals("jpg") || fExt.equals("png")) { Bitmap thumb = null; final int IMAGE_MAX_SIZE = 30000; // 1.2MP BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; thumb = BitmapFactory.decodeFile(helper.file.getAbsolutePath(), options); int scale = 1; while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { scale++; } Log.d(TAG, "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight); if (scale > 1) { scale--; options = new BitmapFactory.Options(); options.inSampleSize = scale; thumb = BitmapFactory.decodeFile(helper.file.getAbsolutePath(), options); } else thumb = BitmapFactory.decodeFile(helper.file.getAbsolutePath()); if (thumb != null) { FileOutputStream fOut; try { fOut = new FileOutputStream(helper.getThumbFilePath("jpg")); thumb.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); thumb.recycle(); } catch (Exception e) { } } } else { // try jni to create a thumb String proba = helper.getThumbFilePath("").getAbsolutePath(); if (NativeMethods.getInstance().loadRawImageThumb(helper.file.getAbsolutePath(), proba )) { } } } } private boolean tryLoadThumb(ImageObjectHelper helper){ boolean rezultat = helper.tryLoadThumb("png"); if (!rezultat){ rezultat = helper.tryLoadThumb("jpg"); if (!rezultat) rezultat = helper.tryLoadThumb("ppm"); } return rezultat; } private void deleteSelectedPhoneImages() { mProgressText.setText("Deleting selected images"); mProgressLayout.setVisibility(View.VISIBLE); for(int i = mImageGalleryAdapter.getCount()-1; i >= 0; i--){ ImageObjectHelper item = mImageGalleryAdapter.items().get(i); if (item.isChecked) { item.deleteImage(); mImageGalleryAdapter.items().remove(i); } } mProgressLayout.setVisibility(View.GONE); mImageGalleryAdapter.notifyDataSetChanged(); } @Override protected void processArduinoButtons( EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) { for (ArduinoButtonEnum button : releasedButtons) { switch (button) { case Button0: break; case Button4: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK,0)); break; case Button5: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER,0)); break; case Button6: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT,0)); break; case Button7: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT,0)); break; case Button8: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP,0)); break; case Button9: generateKeyEvent(new KeyEvent(button.getLongPressStart(), button.getLongPressEnd(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN,0)); break; } Log.d(TAG, "Released button: " + button.toString() + " is long press: " + button.getIsLongPress()); } for (ArduinoButtonEnum button : pressedButtons) { switch(button){ case Button4: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); break; case Button5: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)); break; case Button6: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)); break; case Button7: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)); break; case Button8: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP)); break; case Button9: generateKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN)); break; } Log.d(TAG, "Pressed button: " + button.toString()); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.EnumSet; import java.util.HashMap; import android.app.Activity; import android.app.Instrumentation; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; public abstract class ActivityBase extends Activity { private final static String TAG = ActivityBase.class.getSimpleName(); private HashMap<Class<?>, ServiceConnectionHelper> mBindServices = new HashMap<Class<?>, ServiceConnectionHelper>(); private ArduinoButton mArduinoButtons; private Instrumentation mInstrumentation; private Handler mInstrumentationHandler; private Thread mInstrumentationThread; protected SharedPreferences mPrefs; private class ServiceConnectionHelper { public boolean isBound = false; public Class<?> mServiceClass; public ServiceConnectionHelper(Class<?> serviceClass) { mServiceClass = serviceClass; } public ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "onServiceDisconnected"); doServiceDisconnected(mServiceClass, name); } public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "onServiceConnected"); ServiceBase serviceBase = ((ServiceBase.MyBinder)service).getService(); doServiceConnected(mServiceClass, name, serviceBase); } }; } protected boolean getIsServiceBind(Class<?> serviceClass) { if (mBindServices.containsKey(serviceClass)) return mBindServices.get(serviceClass).isBound; else return false; } protected void doBindService(Class<?> serviceClass ) { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). Log.d(TAG, "doBindService " + serviceClass.getSimpleName()); ServiceConnectionHelper helper; if (!mBindServices.containsKey(serviceClass)) helper = new ServiceConnectionHelper(serviceClass); else helper = mBindServices.get(serviceClass); if (!helper.isBound) { bindService(new Intent(this, serviceClass), helper.serviceConnection, Context.BIND_AUTO_CREATE);// new Intent(MainActivity.this, PtpService.class), serviceConnection, Context.BIND_AUTO_CREATE); helper.isBound = true; mBindServices.put(serviceClass, helper); } } protected void doUnbindService(Class<?> serviceClass) { Log.d(TAG, "doUnbindService: " + serviceClass.getSimpleName()); if (mBindServices.containsKey(serviceClass)) { ServiceConnectionHelper helper = mBindServices.get(serviceClass); unbindService(helper.serviceConnection); helper.isBound = false; } } @Override protected void onCreate(Bundle savedInstanceState) { mPrefs = PreferenceManager.getDefaultSharedPreferences(this); super.onCreate(savedInstanceState); } private void startButtonThread() { mInstrumentation = new Instrumentation(); mInstrumentationThread = new Thread() { public void run() { Log.d( TAG,"Creating handler ..." ); Looper.prepare(); mInstrumentationHandler = new Handler(); Looper.loop(); Log.d( TAG, "Looper thread ends" ); } }; mInstrumentationThread.start(); mArduinoButtons = new ArduinoButton(); mArduinoButtons.setArduinoButtonListener(new ArduinoButton.ArduinoButtonListener() { public void buttonStateChanged(EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) { processArduinoButtons(pressedButtons, releasedButtons); } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { startButtonThread(); doBindService(UsbSerialService.class); super.onResume(); } @Override protected void onPause() { stopUsbSerialService(); mInstrumentationHandler.getLooper().quit(); mInstrumentationHandler = null; super.onPause(); } @Override protected void onStop() { super.onStop(); } private void stopUsbSerialService() { if (mUsbSerialService != null) mUsbSerialService.stopSelf(); doUnbindService(UsbSerialService.class); } private UsbSerialService mUsbSerialService = null; private void doServiceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service){ if (serviceClass.equals(UsbSerialService.class)) { mUsbSerialService = (UsbSerialService)service; mUsbSerialService.setButtonStateChangeListener(new UsbSerialService.ButtonStateChangeListener() { public void onButtonStateChanged(int buttons) { mArduinoButtons.newButtonState(buttons); } }); startService(new Intent(this, UsbSerialService.class)); } else serviceConnected(serviceClass, name, service); } private void doServiceDisconnected(Class<?> serviceClass, ComponentName name){ if (serviceClass.equals(UsbSerialService.class)) { mUsbSerialService = null; } else serviceDisconnected(serviceClass, name); } protected void generateKeyEvent(final KeyEvent key) { if (mInstrumentationHandler != null) { mInstrumentationHandler.post(new Runnable() { public void run() { try { mInstrumentation.sendKeySync(key); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } }); } }; protected void generateKeyEvent(final int key) { if (mInstrumentationHandler != null) { mInstrumentationHandler.post(new Runnable() { public void run() { try { mInstrumentation.sendKeyDownUpSync(key); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } }); } } protected abstract void serviceConnected(Class<?> serviceClass, ComponentName name, ServiceBase service); protected abstract void serviceDisconnected(Class<?> serviceClass, ComponentName name); protected abstract void processArduinoButtons(EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons); }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; public class PtpPropertyValue { int mTypecode; Object mValue; PtpPropertyValue (int tc) { mTypecode = tc; } private PtpPropertyValue (int tc, Object obj) { mTypecode = tc; mValue = obj; } public Object getValue () { return mValue; } public int getTypeCode () { return mTypecode; } protected void parse (PtpBuffer data) { mValue = get(mTypecode, data); } public static void setNewPropertyValue(PtpBuffer data, int valueType, Object value){ switch(valueType){ case u8: case s8: data.put8((Integer) value); break; case s16: case u16: data.put16((Integer)value); break; case s32: data.put32((Integer)value); break; case u32: data.put32((Long)value); break; case s64: case u64: data.put64((Long)value); break; case string: data.putString(value.toString()); break; } } static Object get (int code, PtpBuffer buf) { switch (code) { case s8: return Integer.valueOf(buf.nextS8 ()); case u8: return Integer.valueOf(buf.nextU8 ()); case s16: return Integer.valueOf(buf.nextS16 ()); case u16: return Integer.valueOf(buf.nextU16 ()); case s32: return Integer.valueOf(buf.nextS32 ()); case u32: return Long.valueOf(0xffffffffL & buf.nextS32 ()); //return buf.nextS32(); case s64: return Long.valueOf(buf.nextS64 ()); case u64: // FIXME: unsigned masquerading as signed ... return Long.valueOf(buf.nextS64()); // case s128: case u128: case s8array: return buf.nextS8Array (); case u8array: return buf.nextU8Array (); case s16array: return buf.nextS16Array (); case u16array: return buf.nextU16Array (); case u32array: // FIXME: unsigned masquerading as signed ... case s32array: return buf.nextS32Array (); case u64array: // FIXME: unsigned masquerading as signed ... case s64array: return buf.nextS64Array (); // case s128array: case u128array: case string: return buf.nextString (); } throw new IllegalArgumentException (); } // code values, per 5.3 table 3 public static final int s8 = 0x0001; /** Unsigned eight bit integer */ public static final int u8 = 0x0002; public static final int s16 = 0x0003; /** Unsigned sixteen bit integer */ public static final int u16 = 0x0004; public static final int s32 = 0x0005; /** Unsigned thirty two bit integer */ public static final int u32 = 0x0006; public static final int s64 = 0x0007; /** Unsigned sixty four bit integer */ public static final int u64 = 0x0008; public static final int s128 = 0x0009; /** Unsigned one hundred twenty eight bit integer */ public static final int u128 = 0x000a; public static final int s8array = 0x4001; /** Array of unsigned eight bit integers */ public static final int u8array = 0x4002; public static final int s16array = 0x4003; /** Array of unsigned sixteen bit integers */ public static final int u16array = 0x4004; public static final int s32array = 0x4005; /** Array of unsigned thirty two bit integers */ public static final int u32array = 0x4006; public static final int s64array = 0x4007; /** Array of unsigned sixty four bit integers */ public static final int u64array = 0x4008; public static final int s128array = 0x4009; /** Array of unsigned one hundred twenty eight bit integers */ public static final int u128array = 0x400a; /** Unicode string */ public static final int string = 0xffff; }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.view.ViewConfiguration; public enum ArduinoButtonEnum { Button0 (0x0001), Button1 (0x0002), Button2 (0x0004), Button3 (0x0008), Button4 (0x0010), Button5 (0x0020), Button6 (0x0040), Button7 (0x0080), Button8 (0x0100), Button9 (0x0200); private int mButtonPosition; private long mLongPressStart; private long mLongPressEnd; private boolean mIsPressed = false; private boolean mIsLongPress = false; public void pressStart(long value) { mIsLongPress = false; mIsPressed = true; mLongPressStart = value; } public void pressEnd(long value) { mLongPressEnd = value; mIsPressed = false; mIsLongPress = ((System.currentTimeMillis() - mLongPressStart) > ViewConfiguration.getLongPressTimeout()); } public int getButtonPosition() { return mButtonPosition; } ArduinoButtonEnum(int buttonPosition) { mButtonPosition = buttonPosition; mLongPressStart = System.currentTimeMillis(); } public boolean getIsPressed() { return mIsPressed; } public boolean getIsLongPress() { if (!mIsPressed) return mIsLongPress; else return false; } public long getLongPressStart(){ return mLongPressStart; } public long getLongPressEnd(){ return mLongPressEnd; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.text.InputFilter; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class RightFragment extends DslrFragmentBase { private static final String TAG = "RightFragment"; private LinearLayout mRightLayout; private CheckableImageView mStillCaptureMode, mCompressionSetting, mImageSize, mWhiteBalance, mExposureMetering, mFocusMetering, mAfModeSelect, mActivePicCtrlItem, mActiveDLightning, mFlashMode, mEnableBracketing, mBracketingType; private TextView mIso, mBurstNumber, mExposureCompensation, mExposureEvStep, mFlashCompensation, mAeBracketingStep, mWbBracketingStep, mAeBracketingCount; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_right, container, false); mRightLayout = (LinearLayout)view.findViewById(R.id.right_layout); mStillCaptureMode = (CheckableImageView)view.findViewById(R.id.stillcapturemode); mCompressionSetting = (CheckableImageView)view.findViewById(R.id.compressionsetting); mImageSize = (CheckableImageView)view.findViewById(R.id.imagesize); mIso = (TextView)view.findViewById(R.id.iso); mWhiteBalance = (CheckableImageView)view.findViewById(R.id.whitebalance); mExposureMetering = (CheckableImageView)view.findViewById(R.id.exposuremeteringmode); mFocusMetering = (CheckableImageView)view.findViewById(R.id.focusmeteringmode); mAfModeSelect = (CheckableImageView)view.findViewById(R.id.afmodeselect); mBurstNumber = (TextView)view.findViewById(R.id.burstnumber); mExposureCompensation = (TextView)view.findViewById(R.id.exposurecompensation); mExposureEvStep = (TextView)view.findViewById(R.id.exposureevstep); mActivePicCtrlItem = (CheckableImageView)view.findViewById(R.id.activepicctrlitem); mActiveDLightning = (CheckableImageView)view.findViewById(R.id.activedlightning); mFlashMode = (CheckableImageView)view.findViewById(R.id.flashmode); mFlashCompensation = (TextView)view.findViewById(R.id.flashcompensation); mEnableBracketing = (CheckableImageView)view.findViewById(R.id.enablebracketing); mBracketingType = (CheckableImageView)view.findViewById(R.id.bracketingtype); mAeBracketingStep = (TextView)view.findViewById(R.id.aebracketingstep); mWbBracketingStep = (TextView)view.findViewById(R.id.wbbracketingstep); mAeBracketingCount = (TextView)view.findViewById(R.id.aebracketingcount); mStillCaptureMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.StillCaptureMode, "Select still capture mode", null); } }); mCompressionSetting.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.CompressionSetting, "Select compression mode", null); } }); mImageSize.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ImageSize, "Select image size", null); } }); mIso.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ExposureIndex, "Select ISO value", null); } }); mWhiteBalance.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.WhiteBalance, "Select White Balance value", null); } }); mExposureMetering.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ExposureMeteringMode, "Select Exposure metering mode", null); } }); mFocusMetering.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.FocusMeteringMode, "Select Focus metering mode", null); } }); mAfModeSelect.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.AfModeSelect, "Select AF mode", null); } }); mExposureEvStep.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ExposureEvStep, "Select EV step", null); } }); mExposureCompensation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().showExposureCompensationDialog(getActivity()); } }); mActivePicCtrlItem.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ActivePicCtrlItem, "Select Active picture control", null); } }); mActiveDLightning.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.ActiveDLighting, "Select Active D-Lighting", null); } }); mBurstNumber.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { PtpProperty property = DslrHelper.getInstance().getPtpDevice().getPtpProperty(PtpProperty.BurstNumber); if (property != null){ CustomDialog.Builder customBuilder = new CustomDialog.Builder(getActivity()); InputFilter[] filterArray = new InputFilter[1]; filterArray[0] = new InputFilter.LengthFilter(2); final EditText txt = new EditText(getActivity()); txt.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); txt.setText(property.getValue().toString()); txt.setInputType(InputType.TYPE_CLASS_NUMBER); txt.setFilters(filterArray); customBuilder.setTitle("Enter burst number") .setContentView(txt) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); String strNum = txt.getText().toString().trim(); if (!strNum.isEmpty()) { int brNum = Integer.parseInt(strNum); Toast.makeText(getActivity(), "Burst number: " + strNum + " num: " + brNum, Toast.LENGTH_SHORT).show(); DslrHelper.getInstance().getPtpDevice().setDevicePropValueCmd(PtpProperty.BurstNumber, brNum); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); CustomDialog dialog = customBuilder.create(); dialog.show(); } } }); mFlashMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.FlashMode, "Select Flash mode", null); } }); mFlashCompensation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().showInternalFlashCompensationDialog(getActivity()); } }); mEnableBracketing.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().toggleInternalBracketing(); // PtpProperty property = getPtpDevice().getPtpProperty(PtpProperty.EnableBracketing); // if (property != null) { // Integer val = (Integer)property.getValue(); // getPtpDevice().setDevicePropValueCmd(PtpProperty.EnableBracketing, val == 0 ? 1 : 0); // } } }); mBracketingType.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.BracketingType, "Select Bracketing type", null); } }); mAeBracketingStep.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.AeBracketingStep, "Select AE-Bracketing step", null); } }); mWbBracketingStep.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.WbBracketingStep, "Select WB-Bracketing step", null); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(TAG, "onAttach"); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.d(TAG, "onDetach"); super.onDetach(); } @Override protected void internalInitFragment() { if (getIsPtpDeviceInitialized()) { initializePtpPropertyView(mStillCaptureMode, getPtpDevice().getPtpProperty(PtpProperty.StillCaptureMode)); initializePtpPropertyView(mCompressionSetting, getPtpDevice().getPtpProperty(PtpProperty.CompressionSetting)); initializePtpPropertyView(mImageSize, getPtpDevice().getPtpProperty(PtpProperty.ImageSize)); initializePtpPropertyView(mIso, getPtpDevice().getPtpProperty(PtpProperty.ExposureIndex)); initializePtpPropertyView(mWhiteBalance, getPtpDevice().getPtpProperty(PtpProperty.WhiteBalance)); initializePtpPropertyView(mExposureMetering, getPtpDevice().getPtpProperty(PtpProperty.ExposureMeteringMode)); initializePtpPropertyView(mFocusMetering, getPtpDevice().getPtpProperty(PtpProperty.FocusMeteringMode)); initializePtpPropertyView(mAfModeSelect, getPtpDevice().getPtpProperty(PtpProperty.AfModeSelect)); initializePtpPropertyView(mBurstNumber, getPtpDevice().getPtpProperty(PtpProperty.BurstNumber)); initializePtpPropertyView(mExposureEvStep, getPtpDevice().getPtpProperty(PtpProperty.ExposureEvStep)); initializePtpPropertyView(mExposureCompensation, getPtpDevice().getPtpProperty(PtpProperty.ExposureBiasCompensation)); initializePtpPropertyView(mActivePicCtrlItem, getPtpDevice().getPtpProperty(PtpProperty.ActivePicCtrlItem)); initializePtpPropertyView(mActiveDLightning, getPtpDevice().getPtpProperty(PtpProperty.ActiveDLighting)); initializePtpPropertyView(mFlashMode, getPtpDevice().getPtpProperty(PtpProperty.FlashMode)); initializePtpPropertyView(mFlashCompensation, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCompensation)); initializePtpPropertyView(mEnableBracketing, getPtpDevice().getPtpProperty(PtpProperty.EnableBracketing)); initializePtpPropertyView(mBracketingType, getPtpDevice().getPtpProperty(PtpProperty.BracketingType)); // hide these, if they supported will be displayed mAeBracketingStep.setVisibility(View.GONE); mAeBracketingCount.setVisibility(View.GONE); mWbBracketingStep.setVisibility(View.GONE); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.AeBracketingStep)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.WbBracketingStep)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.AeBracketingCount)); } } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch (property.getPropertyCode()) { case PtpProperty.StillCaptureMode: DslrHelper.getInstance().setDslrImg(mStillCaptureMode, property); break; case PtpProperty.CompressionSetting: DslrHelper.getInstance().setDslrImg(mCompressionSetting, property); break; case PtpProperty.ImageSize: DslrHelper.getInstance().setDslrImg(mImageSize, property); break; case PtpProperty.ExposureIndex: DslrHelper.getInstance().setDslrTxt(mIso, property); break; case PtpProperty.WhiteBalance: DslrHelper.getInstance().setDslrImg(mWhiteBalance, property); break; case PtpProperty.ExposureMeteringMode: DslrHelper.getInstance().setDslrImg(mExposureMetering, property); break; case PtpProperty.FocusMeteringMode: DslrHelper.getInstance().setDslrImg(mFocusMetering, property); break; case PtpProperty.AfModeSelect: DslrHelper.getInstance().setDslrImg(mAfModeSelect, property); break; case PtpProperty.BurstNumber: mBurstNumber.setText(property.getValue().toString()); mBurstNumber.setEnabled(property.getIsWritable()); case PtpProperty.ExposureEvStep: DslrHelper.getInstance().setDslrTxt(mExposureEvStep, property); break; case PtpProperty.ExposureBiasCompensation: mExposureCompensation.setEnabled(property.getIsWritable()); int ev = (Integer)property.getValue(); mExposureCompensation.setText(String.format("%+.1f EV", (double)ev/1000)); break; case PtpProperty.ActivePicCtrlItem: DslrHelper.getInstance().setDslrImg(mActivePicCtrlItem, property); break; case PtpProperty.ActiveDLighting: DslrHelper.getInstance().setDslrImg(mActiveDLightning, property); break; case PtpProperty.FlashMode: DslrHelper.getInstance().setDslrImg(mFlashMode, property); break; case PtpProperty.InternalFlashCompensation: mFlashCompensation.setEnabled(property.getIsWritable()); int fev = (Integer)property.getValue(); mFlashCompensation.setText(String.format("%+.1f EV", (double)fev/6)); break; case PtpProperty.EnableBracketing: Integer enableBkt = (Integer)property.getValue(); mEnableBracketing.setChecked(enableBkt == 1); break; case PtpProperty.BracketingType: Integer val = (Integer)property.getValue(); boolean isAe = val == 1; boolean isWB = val == 3; boolean isADL = val == 4; mAeBracketingStep.setVisibility(isAe ? View.VISIBLE : View.GONE); mAeBracketingCount.setVisibility(isAe || isADL ? View.VISIBLE : View.GONE); mWbBracketingStep.setVisibility(isWB ? View.VISIBLE : View.GONE); DslrHelper.getInstance().setDslrImg(mBracketingType, property); break; case PtpProperty.AeBracketingStep: DslrHelper.getInstance().setDslrTxt(mAeBracketingStep, property); break; case PtpProperty.WbBracketingStep: DslrHelper.getInstance().setDslrTxt(mWbBracketingStep, property); break; case PtpProperty.AeBracketingCount: mAeBracketingCount.setText(property.getValue().toString()); break; default: break; } } } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case BusyBegin: Log.d(TAG, "Busy begin"); DslrHelper.getInstance().enableDisableControls(mRightLayout, false); break; case BusyEnd: Log.d(TAG, "Busy end"); DslrHelper.getInstance().enableDisableControls(mRightLayout, true); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.graphics.RectF; public class PtpLiveViewObject { public static final int FIXED_POINT = 16; public static final int ONE = 1 << FIXED_POINT; private int mVendorId, mProductId; public LvSizeInfo jpegImageSize; LvSizeInfo wholeSize; LvSizeInfo displayAreaSize; LvSizeInfo displayCenterCoordinates; LvSizeInfo afFrameSize; LvSizeInfo afFrameCenterCoordinates; int noPersons = 0; LvSizeInfo[] personAfFrameSize = null;//= new SizeInfo[5]; LvSizeInfo[] personAfFrameCenterCoordinates = null; // = new SizeInfo[5]; public RectF[] afRects = null; // = new RectF[6]; public int selectedFocusArea = 0; public int rotationDirection = 0; public int focusDrivingStatus = 0; public int shutterSpeedUpper = 0; public int shutterSpeedLower = 0; public int apertureValue = 0; public int countDownTime = 0; public int focusingJudgementResult = 0; public int afDrivingEnabledStatus = 0; public int levelAngleInformation = 0; public int faceDetectionAfModeStatus = 0; public int faceDetectionPersonNo = 0; public int afAreaIndex = 0; public byte[] data; // d7000 properties public double rolling = 0; public boolean hasRolling = false; public double pitching = 0; public boolean hasPitching = false; public double yawing = 0; public boolean hasYawing = false; public int movieRecordingTime = 0; public boolean movieRecording = false; public boolean hasApertureAndShutter = true; public float ox, oy, dLeft, dTop; public int imgLen; public int imgPos; public PtpLiveViewObject(int vendorId, int productId){ mVendorId = vendorId; mProductId = productId; switch (mProductId){ case 0x0429: // d5100 case 0x0428: // d7000 case 0x042a: // d800 case 0x042e: // d800e case 0x042d: // d600 noPersons = 35; break; case 0x0423: // d5000 case 0x0421: // d90 noPersons = 5; break; case 0x041a: // d300 case 0x041c: // d3 case 0x0420: // d3x case 0x0422: // d700 case 0x0425: // d300s case 0x0426: // d3s noPersons = 0; break; } personAfFrameSize = new LvSizeInfo[noPersons]; personAfFrameCenterCoordinates = new LvSizeInfo[noPersons]; afRects = new RectF[noPersons + 1]; for (int i = 0; i < noPersons; i++) { personAfFrameSize[i] = new LvSizeInfo(); personAfFrameCenterCoordinates[i] = new LvSizeInfo(); } jpegImageSize = new LvSizeInfo(); wholeSize = new LvSizeInfo(); displayAreaSize = new LvSizeInfo(); displayCenterCoordinates = new LvSizeInfo(); afFrameSize = new LvSizeInfo(); afFrameCenterCoordinates = new LvSizeInfo(); } public float sDw, sDh; private PtpBuffer buf = null; public void setBuffer(PtpBuffer buffer){ buf = buffer; } public void parse(int sWidth, int sHeight){ if (buf != null){ buf.parse(); switch (mProductId){ case 0x042d: // d600 buf.nextS32(); // display information area size buf.nextS32(); // live view image area size break; } jpegImageSize.setSize(buf.nextU16(true), buf.nextU16(true)); sDw = (float)sWidth / (float)jpegImageSize.horizontal; sDh = (float)sHeight / (float)jpegImageSize.vertical; //Log.d(MainActivity.TAG, "++ Width: " + jpegImageSize.horizontal + " height: " + jpegImageSize.vertical); wholeSize.setSize(buf.nextU16(true), buf.nextU16(true)); displayAreaSize.setSize(buf.nextU16(true), buf.nextU16(true)); displayCenterCoordinates.setSize(buf.nextU16(true), buf.nextU16(true)); afFrameSize.setSize(buf.nextU16(true), buf.nextU16(true)); afFrameCenterCoordinates.setSize(buf.nextU16(true), buf.nextU16(true)); buf.nextS32(); // reserved selectedFocusArea = buf.nextU8(); rotationDirection = buf.nextU8(); focusDrivingStatus = buf.nextU8(); buf.nextU8(); // reserved shutterSpeedUpper = buf.nextU16(true); shutterSpeedLower = buf.nextU16(true); apertureValue = buf.nextU16(true); countDownTime = buf.nextU16(true); focusingJudgementResult = buf.nextU8(); afDrivingEnabledStatus = buf.nextU8(); buf.nextU16(); // reserved ox = (float)jpegImageSize.horizontal / (float)displayAreaSize.horizontal; oy = (float)jpegImageSize.vertical / (float)displayAreaSize.vertical; dLeft = ((float)displayCenterCoordinates.horizontal - ((float)displayAreaSize.horizontal / 2)); dTop = ((float)displayCenterCoordinates.vertical - ((float)displayAreaSize.vertical / 2)); switch (mProductId){ case 0x0426: // d3s CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize); hasApertureAndShutter = false; hasRolling = true; rolling = ((double)buf.nextS32(true)) / ONE; imgPos = 128 + 12; break; case 0x0420: // d3x CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize); hasRolling = true; rolling = ((double)buf.nextS32(true)) / ONE; imgPos = 64 + 12; break; case 0x041a: // d300 case 0x041c: // d3 case 0x0422: // d700 case 0x0425: // d300s CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize); imgPos = 64 + 12; break; case 0x0429: // d5100 case 0x0428: // d7000 break; case 0x042a: // d800 case 0x042e: // d800e case 0x042d: // d600 // d800 don't have the aperture and shutter values if (mProductId == 0x042a || mProductId == 0x042e) hasApertureAndShutter = false; hasRolling = true; rolling = ((double)buf.nextS32(true)) / ONE; hasPitching = true; pitching = ((double)buf.nextS32(true)) / ONE; hasYawing = true; yawing = ((double)buf.nextS32(true)) / ONE; movieRecordingTime = buf.nextS32(); movieRecording = buf.nextU8() == 1; faceDetectionAfModeStatus = buf.nextU8(); faceDetectionPersonNo = buf.nextU8(); afAreaIndex = buf.nextU8(); CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize); for(int i = 0; i < noPersons; i++){ personAfFrameSize[i].setSize(buf.nextU16(true), buf.nextU16(true)); personAfFrameCenterCoordinates[i].setSize(buf.nextU16(true), buf.nextU16(true)); if ((i+1) <= faceDetectionPersonNo) CalcCoord(i + 1, dLeft, dTop, personAfFrameCenterCoordinates[i], personAfFrameSize[i]); } imgPos = 384 + 12; break; case 0x0423: // d5000 case 0x0421: // d90 levelAngleInformation = buf.nextS32(true); faceDetectionAfModeStatus = buf.nextU8(); buf.nextU8(); // reserved faceDetectionPersonNo = buf.nextU8(); afAreaIndex = buf.nextU8(); CalcCoord(0, dLeft, dTop, afFrameCenterCoordinates, afFrameSize); for(int i = 0; i < noPersons; i++){ personAfFrameSize[i].setSize(buf.nextU16(true), buf.nextU16(true)); personAfFrameCenterCoordinates[i].setSize(buf.nextU16(true), buf.nextU16(true)); if ((i+1) <= faceDetectionPersonNo) CalcCoord(i + 1, dLeft, dTop, personAfFrameCenterCoordinates[i], personAfFrameSize[i]); } imgPos = 128+12; break; } imgLen = buf.data().length - imgPos; data = buf.data(); } //System.arraycopy(buf.data(), imgPos, imgData, 0, imgLen); } private void CalcCoord(int coord, float dLeft, float dTop, LvSizeInfo afCenter, LvSizeInfo afSize) { float left, top, right, bottom; left = (((float)afCenter.horizontal - ((float)afSize.horizontal / 2)) - dLeft) * ox; top = (((float)afCenter.vertical - ((float)afSize.vertical / 2)) - dTop) * ox; if (left < 0) left = 0; if (top < 0) top = 0; right = left + ((float)afSize.horizontal * ox); bottom = top + ((float)afSize.vertical * oy); if (right > jpegImageSize.horizontal) right = jpegImageSize.horizontal; if (bottom > jpegImageSize.vertical) bottom = jpegImageSize.vertical; //Log.d(MainActivity.TAG, "++ Left: " + left + " top: " + top +" right: " + right + " bottom: " + bottom); afRects[coord] = new RectF(left * sDw, top * sDh, right * sDw, bottom * sDh); } public class LvSizeInfo { public int horizontal; public int vertical; public LvSizeInfo(){ horizontal = 0; vertical = 0; } public LvSizeInfo(int horSize, int vertSize){ horizontal = horSize; vertical = vertSize; } public void setSize(int hor, int vert){ horizontal = hor; vertical = vert; } public void setSize(LvSizeInfo sizeInfo){ horizontal = sizeInfo.horizontal; vertical = sizeInfo.vertical; } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.ArrayList; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class ImageGalleryAdapter extends BaseAdapter { private final static String TAG = "ImageGalleryAdapter"; public interface SelectionChangedListener { public void onSelectionChanged( ArrayList<ImageObjectHelper> selectedItems); } public interface ImageItemClickedListener { public void onImageItemClicked(ImageObjectHelper obj); } private SelectionChangedListener _selectionChangedListener; public void setOnSelectionChanged(SelectionChangedListener listener) { _selectionChangedListener = listener; } private ImageItemClickedListener _imageItemClickedListener; public void setOnImageItemClicked(ImageItemClickedListener listener) { _imageItemClickedListener = listener; } private ArrayList<ImageObjectHelper> _items; public ArrayList<ImageObjectHelper> items() { return _items; } public Context context; public LayoutInflater inflater; public ImageGalleryAdapter(Context context, ArrayList<ImageObjectHelper> arrayList) { super(); // Log.d(TAG, "Costructor"); this.context = context; this._items = arrayList; this.inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); BitmapManager.INSTANCE.setPlaceholder(BitmapFactory.decodeResource( context.getResources(), R.drawable.ic_launcher)); } public void changeItems(ArrayList<ImageObjectHelper> arrayList) { // Log.d(TAG, "changeItems"); _items = arrayList; notifyDataSetChanged(); } public void addImgItem(ImageObjectHelper item) { // Log.d(TAG, "addImgItem"); _items.add(item); this.notifyDataSetChanged(); } public void selectAll() { // Log.d(TAG, "selectAll"); for (ImageObjectHelper item : _items) { item.isChecked = true; } notifyDataSetChanged(); } public void invert() { Log.d(TAG, "invert"); for (ImageObjectHelper item : _items) { item.isChecked = !item.isChecked; } notifyDataSetChanged(); } public int getCount() { // Log.d(TAG, "getCount: " + _items.size()); return _items.size(); } public Object getItem(int position) { // Log.d(TAG, "getItem: " + position); return _items.get(position); } public long getItemId(int position) { // Log.d(TAG, "getItemId: " + position); return position; } @Override public boolean hasStableIds() { // Log.d(TAG, "hasSTableIds"); return true; } @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TYPE; } @Override public int getViewTypeCount() { // Log.d(TAG, "getViewTypeCount"); return 1; } public static class ViewHolder { CheckableLinearLayout itemLayout; ImageView thumbImage; TextView imgName; //CheckBox checkBox; } public View getView(int position, View convertView, ViewGroup parent) { // Log.d(TAG, "getView"); final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.img_preview_item, null); holder.itemLayout = (CheckableLinearLayout) convertView.findViewById(R.id.img_item_layout); holder.imgName = (TextView) convertView.findViewById(R.id.imgName); holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); ImageObjectHelper helper = _items.get(position); holder.thumbImage.setId(position); holder.itemLayout.setChecked(helper.isChecked); switch (helper.galleryItemType) { case ImageObjectHelper.DSLR_PICTURE: holder.imgName.setText(helper.objectInfo.filename); break; case ImageObjectHelper.PHONE_PICTURE: holder.imgName.setText(helper.file.getName()); break; } BitmapManager.INSTANCE.loadBitmap(helper.file.getAbsolutePath(), holder.thumbImage); return convertView; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.nio.channels.ClosedByInterruptException; import android.util.Log; public abstract class ThreadBase extends Thread { private boolean mIsThreadPaused = false; protected int mSleepTime = 10; public boolean getIsThreadPaused() { return mIsThreadPaused; } public void setIsThreadPaused(boolean value) { mIsThreadPaused = value; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(mSleepTime); } catch (InterruptedException e) { Log.i("ThreadBase", "Thread interrupted"); break; } catch (Exception e) { Log.i("ThreadBase", "Thread exception " + e.getMessage()); break; } if (!mIsThreadPaused) { codeToExecute(); } } Log.i("ThreadBase", "Thread ended"); } public abstract void codeToExecute(); }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; public enum PtpDeviceEvent { PtpDeviceInitialized, PtpDeviceStoped, PrefsLoaded, LiveviewStart, LiveviewStop, SdCardInserted, SdCardRemoved, SdCardInfoUpdated, MovieRecordingStart, MovieRecordingEnd, BusyBegin, BusyEnd, RecordingDestinationChanged, CaptureInitiated, CaptureStart, ObjectAdded, ObjectAddedInSdram, CaptureComplete, CaptureCompleteInSdram, GetObjectFromSdramInfo, GetObjectFromSdramThumb, GetObjectFromSdramProgress, GetObjectFromSdramFinished, GetObjectFromCamera, GetObjectFromCameraProgress, GetObjectFromCameraFinished, TimelapseStarted, TimelapseStoped, TimelapseEvent }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public abstract class ServiceBase extends Service { private final static String TAG = ServiceBase.class.getSimpleName(); protected boolean mIsBind = false; public class MyBinder extends Binder { public ServiceBase getService() { Log.d(TAG, ServiceBase.this.getClass().getSimpleName()); return ServiceBase.this; } } private final IBinder mBinder = new MyBinder(); @Override public IBinder onBind(Intent intent) { Log.d(TAG, "onBind"); mIsBind = true; return mBinder; } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "onUnbind"); mIsBind = false; return super.onUnbind(intent); } public void stopService() { stopSelf(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.util.EnumSet; import android.util.Log; import android.view.ViewConfiguration; public class ArduinoButton { private static final String TAG = "ArduinoButton"; private int mButtonState = 0xffff; private ArduinoButtonListener mButtonChangeListener = null; public void setArduinoButtonListener(ArduinoButtonListener listener) { mButtonChangeListener = listener; } public interface ArduinoButtonListener { void buttonStateChanged(EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons); } public ArduinoButton() { } public void newButtonState(int buttonState) { int oldStates = mButtonState; EnumSet<ArduinoButtonEnum> pressedButtons = EnumSet.noneOf(ArduinoButtonEnum.class); EnumSet<ArduinoButtonEnum> releasedButtons = EnumSet.noneOf(ArduinoButtonEnum.class); mButtonState = buttonState; for (ArduinoButtonEnum button : ArduinoButtonEnum.values()) { if ((oldStates & button.getButtonPosition()) != (mButtonState & button.getButtonPosition())) { boolean pressed = (mButtonState & button.getButtonPosition()) == 0; boolean longPress = false; if (pressed) { button.pressStart(System.currentTimeMillis()); pressedButtons.add(button); } else { button.pressEnd(System.currentTimeMillis()); releasedButtons.add(button); } //Log.d(TAG, "Status change " + button.toString() + " KeyDown " + pressed); } } if (mButtonChangeListener != null) mButtonChangeListener.buttonStateChanged(pressedButtons, releasedButtons); } public boolean getIsButtonPressed(ArduinoButtonEnum button) { return (mButtonState & button.getButtonPosition()) != 0; } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class UsbSerialAttachedActivity extends Activity { private static final String TAG = "UsbSerialAttachedActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); } @Override protected void onRestart() { Log.d(TAG, "onRestart"); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent"); super.onNewIntent(intent); } @Override protected void onResume() { Log.d(TAG, "onResume"); Intent intent = new Intent(this, MainActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); Bundle extras = new Bundle(); extras.putBoolean("UsbSerialAttached", true); intent.putExtras(extras); startActivity(intent); finish(); super.onResume(); } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class AboutFragment extends DslrFragmentBase { private final static String TAG = "AboutFragment"; private TextView mAbout, mNoCamera; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); mAbout = (TextView)view.findViewById(R.id.txt_about); mNoCamera = (TextView)view.findViewById(R.id.txt_nocamera); mAbout.setText(Html.fromHtml(getActivity().getString(R.string.about))); mNoCamera.setText(Html.fromHtml(getActivity().getString(R.string.nocamera))); return view; } @Override protected void internalInitFragment() { // TODO Auto-generated method stub } @Override protected void internalPtpPropertyChanged(PtpProperty property) { // TODO Auto-generated method stub } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case PtpDeviceInitialized: mNoCamera.setVisibility(View.GONE); break; case PtpDeviceStoped: mNoCamera.setVisibility(View.VISIBLE); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); mNoCamera.setVisibility(View.VISIBLE); if (getPtpDevice() != null && getPtpDevice().getIsPtpDeviceInitialized()) mNoCamera.setVisibility(View.GONE); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import android.util.Log; import com.dslr.dashboard.PtpPartialObjectProccessor.PtpPartialObjectProgressListener; public class PtpGetPreviewImageProcessor implements IPtpCommandFinalProcessor { private static String TAG = "GetPreviewImageProcessor"; private PtpPartialObjectProgressListener mProgressListener; public void setProgressListener(PtpPartialObjectProgressListener listener){ mProgressListener = listener; } private PtpObjectInfo mObjectInfo; private int mOffset = 0; private int mMaxSize = 0x100000; //private byte[] _objectData; private File mFile; private OutputStream mStream; // public byte[] pictureData(){ // return _objectData; // } public PtpObjectInfo objectInfo(){ return mObjectInfo; } public int maxSize(){ return mMaxSize; } public PtpGetPreviewImageProcessor(PtpObjectInfo objectInfo, File file){ this(objectInfo, 0x100000, file); } public PtpGetPreviewImageProcessor(PtpObjectInfo objectInfo, int maxSize, File file){ mFile = file; mObjectInfo = objectInfo; mMaxSize = maxSize; //_objectData = new byte[_objectInfo.objectCompressedSize]; try { mStream = new BufferedOutputStream(new FileOutputStream(mFile)); } catch (FileNotFoundException e) { } } public boolean doFinalProcessing(PtpCommand cmd) { boolean result = false; int count = cmd.incomingData().getPacketLength() - 12; Log.d(TAG, "Size: " + count); Log.d(TAG, "Response: " + cmd.getResponseCode()); if (cmd.isResponseOk()) { try { mStream.write(cmd.incomingData().data(), 12, count); } catch (IOException e) { } Log.d(TAG, "Remaining: " + cmd.responseParam()); if (cmd.responseParam() != 0) { mOffset += count; Log.d(TAG, "offset: " + mOffset); result = true; } else { mOffset += count; Log.d(TAG, "offset: " + mOffset); try { mStream.flush(); mStream.close(); } catch (IOException e) { } } if (mProgressListener != null){ mProgressListener.onProgress(mOffset); } } return result; } }
Java
package com.dslr.dashboard; import java.util.Hashtable; import android.util.Log; public class PtpStorageInfo { private static String TAG = "PtpStorageInfo"; public int storageId; public int storageType; public int filesystemType; public int accessCapability; public long maxCapacity; public long freeSpaceInBytes; public int freeSpaceInImages; public String storageDescription; public String volumeLabel; public boolean isObjectsLoaded = false; public Hashtable<Integer, PtpObjectInfo> objects; public PtpStorageInfo(int id, PtpBuffer buf) { objects = new Hashtable<Integer, PtpObjectInfo>(); storageId = id; updateInfo(buf); } public void updateInfo(PtpBuffer buf){ buf.parse(); storageType = buf.nextU16(); filesystemType = buf.nextU16(); accessCapability = buf.nextU16(); maxCapacity = buf.nextS64(); freeSpaceInBytes = buf.nextS64(); freeSpaceInImages = buf.nextS32(); storageDescription = buf.nextString(); volumeLabel = buf.nextString(); Log.d(TAG, String.format("Storage id: %#04x images: %d", storageId, freeSpaceInImages)); } public void deleteObject(int objectId) { if (objects.containsKey(objectId)) { objects.remove(objectId); } } }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class ExposureIndicatorDisplay extends SurfaceView implements SurfaceHolder.Callback, Runnable { private static final String TAG = "ExposureIndicatorDisplay"; private SurfaceHolder mHolder; private int mFrameWidth; private int mFrameHeight; private float mValue = 0; private Context _context; private Paint mPaint; private boolean mThreadRun; private final Object _syncRoot = new Object(); public ExposureIndicatorDisplay(Context context, AttributeSet attrs) { super(context, attrs); _context = context; mHolder = getHolder(); mHolder.addCallback(this); mPaint = new Paint(); mPaint.setColor(0xff99cc00); mPaint.setAntiAlias(true); mPaint.setStyle(Style.FILL); mPaint.setStrokeWidth(2); Log.d(TAG, "Created new " + this.getClass()); } public int getFrameWidth() { return mFrameWidth; } public int getFrameHeight() { return mFrameHeight; } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "Surface changed"); mFrameWidth = width; mFrameHeight = height; processValue(mValue); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surface created"); setWillNotDraw(false); (new Thread(this)).start(); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface destroyed"); mThreadRun = false; } public void processValue(float value) { mValue = value; synchronized (_syncRoot) { Log.d(TAG, "Process value"); _syncRoot.notify(); } } public void setDefaultImage() { mValue = 0; synchronized (_syncRoot) { // mLvo = null; _syncRoot.notify(); } } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); } @Override protected void onAttachedToWindow() { setDefaultImage(); super.onAttachedToWindow(); } private void doDraw(Canvas canvas) { canvas.drawColor(Color.BLACK); float xCenter = mFrameWidth / 2; float yCenter = mFrameHeight / 2; canvas.drawRect(xCenter - 3, yCenter - 3, xCenter + 3, (2 * yCenter) - 6, mPaint); float ds = (xCenter - 20) / 3; for (int i = 1; i <= 3; i++) { float dsx = i * ds; canvas.drawRect(xCenter + dsx - 3, yCenter - 3, xCenter + dsx + 3, yCenter + 3, mPaint); canvas.drawRect(xCenter - dsx - 3, yCenter - 3, xCenter - dsx + 3, yCenter + 3, mPaint); } mPaint.setTextSize(18); String str = String.format("%.1f EV", mValue); float tw = mPaint.measureText(str); canvas.drawText(str, xCenter - (tw / 2), yCenter - 6, mPaint); tw = mPaint.measureText("+"); canvas.drawText("+", xCenter + (3 * ds) - (tw / 2), yCenter - 6, mPaint); tw = mPaint.measureText("-"); canvas.drawText("-", xCenter - (3 * ds) - (tw / 2), yCenter - 6, mPaint); if (mValue != 0) { float limit = xCenter + (3 * ds); if (Math.abs(mValue) < 3) limit = xCenter + (Math.abs(mValue) * ds); float multi = Math.signum(mValue); float start = xCenter + (5 * multi); float counter = xCenter + 5; while (counter < limit) { canvas.drawRect(start, yCenter + 6, start + (2 * multi), (2 * yCenter) - 6, mPaint); start += 4 * multi; counter += 4; } if (Math.abs(mValue) >= 3) { Path p = new Path(); p.moveTo(xCenter + (((3 * ds) - 4) * multi), yCenter + 6); p.lineTo(xCenter + (((3 * ds) + 2) * multi), yCenter + 6); p.lineTo(xCenter + (((3 * ds) + 10) * multi), yCenter + 6 + ((yCenter - 12) / 2)); p.lineTo(xCenter + (((3 * ds) + 2) * multi), (2 * yCenter) - 6); p.lineTo(xCenter + (((3 * ds) - 4) * multi), (2 * yCenter) - 6); canvas.drawPath(p, mPaint); } } } public void run() { mThreadRun = true; Log.d(TAG, "Starting Exposure indicator processing thread"); while (mThreadRun) { synchronized (_syncRoot) { try { _syncRoot.wait(); } catch (InterruptedException e) { Log.d(TAG, "interruped"); } } //Log.d(TAG, "Drawing Indicator display"); try { Canvas canvas = mHolder.lockCanvas(); if (canvas != null) { doDraw(canvas); mHolder.unlockCanvasAndPost(canvas); } } catch (Exception e) { Log.e(TAG, "Exposure indicator drawing exception: " + e.getMessage()); } } } }
Java
// Copyright 2000 by David Brownell <dbrownell@users.sourceforge.net> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 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, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // package com.dslr.dashboard; public class PtpEvent { /** EventCode: */ public static final int Undefined = 0x4000; /** EventCode: */ public static final int CancelTransaction = 0x4001; /** EventCode: */ public static final int ObjectAdded = 0x4002; /** EventCode: */ public static final int ObjectRemoved = 0x4003; /** EventCode: */ public static final int StoreAdded = 0x4004; /** EventCode: */ public static final int StoreRemoved = 0x4005; /** EventCode: */ public static final int DevicePropChanged = 0x4006; /** EventCode: */ public static final int ObjectInfoChanged = 0x4007; /** EventCode: */ public static final int DeviceInfoChanged = 0x4008; /** EventCode: */ public static final int RequestObjectTransfer = 0x4009; /** EventCode: */ public static final int StoreFull = 0x400a; /** EventCode: */ public static final int DeviceReset = 0x400b; /** EventCode: */ public static final int StorageInfoChanged = 0x400c; /** EventCode: */ public static final int CaptureComplete = 0x400d; /** EventCode: a status event was dropped (missed an interrupt) */ public static final int UnreportedStatus = 0x400e; /** EventCode: ObjectAddedInSdram */ public static final int ObjectAddedInSdram = 0xc101; /** EventCode: CaptureCompleteRecInSdram */ public static final int CaptureCompleteRecInSdram = 0xc102; /** EventCode: PreviewImageAdded */ public static final int PreviewImageAdded = 0xc103; }
Java
/* <DslrDashboard - controling DSLR camera with Android phone/tablet> Copyright (C) <2012> <Zoltan Hubai> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.dslr.dashboard; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.LinearLayout; public class CheckableLinearLayout extends LinearLayout implements Checkable{ private boolean mChecked; private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; public CheckableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } public void toggle() { setChecked(!mChecked); } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { if (mChecked != checked) { mChecked = checked; refreshDrawableState(); } } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; /** * Utility class used to handle flinging within a specified limit. */ public abstract class Dynamics { /** * The maximum delta time, in milliseconds, between two updates */ private static final int MAX_TIMESTEP = 50; /** The current position */ protected float mPosition; /** The current velocity */ protected float mVelocity; /** The current maximum position */ protected float mMaxPosition = Float.MAX_VALUE; /** The current minimum position */ protected float mMinPosition = -Float.MAX_VALUE; /** The time of the last update */ protected long mLastTime = 0; /** * Sets the state of the dynamics object. Should be called before starting * to call update. * * @param position The current position. * @param velocity The current velocity in pixels per second. * @param now The current time */ public void setState(final float position, final float velocity, final long now) { mVelocity = velocity; mPosition = position; mLastTime = now; } /** * Returns the current position. Normally used after a call to update() in * order to get the updated position. * * @return The current position */ public float getPosition() { return mPosition; } /** * Gets the velocity. Unit is in pixels per second. * * @return The velocity in pixels per second */ public float getVelocity() { return mVelocity; } /** * Used to find out if the list is at rest, that is, has no velocity and is * inside the the limits. Normally used to know if more calls to update are * needed. * * @param velocityTolerance Velocity is regarded as 0 if less than * velocityTolerance * @param positionTolerance Position is regarded as inside the limits even * if positionTolerance above or below * * @return true if list is at rest, false otherwise */ public boolean isAtRest(final float velocityTolerance, final float positionTolerance) { final boolean standingStill = Math.abs(mVelocity) < velocityTolerance; final boolean withinLimits = mPosition - positionTolerance < mMaxPosition && mPosition + positionTolerance > mMinPosition; return standingStill && withinLimits; } /** * Sets the maximum position. * * @param maxPosition The maximum value of the position */ public void setMaxPosition(final float maxPosition) { mMaxPosition = maxPosition; } /** * Sets the minimum position. * * @param minPosition The minimum value of the position */ public void setMinPosition(final float minPosition) { mMinPosition = minPosition; } /** * Updates the position and velocity. * * @param now The current time */ public void update(final long now) { int dt = (int)(now - mLastTime); if (dt > MAX_TIMESTEP) { dt = MAX_TIMESTEP; } onUpdate(dt); mLastTime = now; } /** * Gets the distance to the closest limit (max and min position). * * @return If position is more than max position: distance to max position. If * position is less than min position: distance to min position. If * within limits: 0 */ protected float getDistanceToLimit() { float distanceToLimit = 0; if (mPosition > mMaxPosition) { distanceToLimit = mMaxPosition - mPosition; } else if (mPosition < mMinPosition) { distanceToLimit = mMinPosition - mPosition; } return distanceToLimit; } /** * Updates the position and velocity. * * @param dt The delta time since last time */ abstract protected void onUpdate(int dt); }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import java.util.Observable; import java.util.Observer; /** * View capable of drawing an image at different zoom state levels */ public class ImageZoomView extends View implements Observer { /** Paint object used when drawing bitmap. */ private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG); /** Rectangle used (and re-used) for cropping source image. */ private final Rect mRectSrc = new Rect(); /** Rectangle used (and re-used) for specifying drawing area on canvas. */ private final Rect mRectDst = new Rect(); /** Object holding aspect quotient */ private final AspectQuotient mAspectQuotient = new AspectQuotient(); /** The bitmap that we're zooming in, and drawing on the screen. */ private Bitmap mBitmap; /** State of the zoom. */ private ZoomState mState; // Public methods /** * Constructor */ public ImageZoomView(Context context, AttributeSet attrs) { super(context, attrs); } /** * Set image bitmap * * @param bitmap The bitmap to view and zoom into */ public void setImage(Bitmap bitmap) { mBitmap = bitmap; if (mBitmap != null) { mAspectQuotient.updateAspectQuotient(getWidth(), getHeight(), mBitmap.getWidth(), mBitmap.getHeight()); mAspectQuotient.notifyObservers(); invalidate(); } } /** * Set object holding the zoom state that should be used * * @param state The zoom state */ public void setZoomState(ZoomState state) { if (mState != null) { mState.deleteObserver(this); } mState = state; mState.addObserver(this); invalidate(); } /** * Gets reference to object holding aspect quotient * * @return Object holding aspect quotient */ public AspectQuotient getAspectQuotient() { return mAspectQuotient; } // Superclass overrides @Override protected void onDraw(Canvas canvas) { if (mBitmap != null && mState != null && !mBitmap.isRecycled()) { final float aspectQuotient = mAspectQuotient.get(); final int viewWidth = getWidth(); final int viewHeight = getHeight(); final int bitmapWidth = mBitmap.getWidth(); final int bitmapHeight = mBitmap.getHeight(); final float panX = mState.getPanX(); final float panY = mState.getPanY(); final float zoomX = mState.getZoomX(aspectQuotient) * viewWidth / bitmapWidth; final float zoomY = mState.getZoomY(aspectQuotient) * viewHeight / bitmapHeight; // Setup source and destination rectangles mRectSrc.left = (int)(panX * bitmapWidth - viewWidth / (zoomX * 2)); mRectSrc.top = (int)(panY * bitmapHeight - viewHeight / (zoomY * 2)); mRectSrc.right = (int)(mRectSrc.left + viewWidth / zoomX); mRectSrc.bottom = (int)(mRectSrc.top + viewHeight / zoomY); mRectDst.left = getLeft(); mRectDst.top = getTop(); mRectDst.right = getRight(); mRectDst.bottom = getBottom(); // Adjust source rectangle so that it fits within the source image. if (mRectSrc.left < 0) { mRectDst.left += -mRectSrc.left * zoomX; mRectSrc.left = 0; } if (mRectSrc.right > bitmapWidth) { mRectDst.right -= (mRectSrc.right - bitmapWidth) * zoomX; mRectSrc.right = bitmapWidth; } if (mRectSrc.top < 0) { mRectDst.top += -mRectSrc.top * zoomY; mRectSrc.top = 0; } if (mRectSrc.bottom > bitmapHeight) { mRectDst.bottom -= (mRectSrc.bottom - bitmapHeight) * zoomY; mRectSrc.bottom = bitmapHeight; } canvas.drawBitmap(mBitmap, mRectSrc, mRectDst, mPaint); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mAspectQuotient.updateAspectQuotient(right - left, bottom - top, mBitmap.getWidth(), mBitmap.getHeight()); mAspectQuotient.notifyObservers(); } // implements Observer public void update(Observable observable, Object data) { invalidate(); } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; import java.util.Observable; /** * Class that holds the aspect quotient, defined as content aspect ratio divided * by view aspect ratio. */ public class AspectQuotient extends Observable { /** * Aspect quotient */ private float mAspectQuotient; // Public methods /** * Gets aspect quotient * * @return The aspect quotient */ public float get() { return mAspectQuotient; } /** * Updates and recalculates aspect quotient based on supplied view and * content dimensions. * * @param viewWidth Width of view * @param viewHeight Height of view * @param contentWidth Width of content * @param contentHeight Height of content */ public void updateAspectQuotient(float viewWidth, float viewHeight, float contentWidth, float contentHeight) { final float aspectQuotient = (contentWidth / contentHeight) / (viewWidth / viewHeight); if (aspectQuotient != mAspectQuotient) { mAspectQuotient = aspectQuotient; setChanged(); } } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; import java.util.Observable; /** * A ZoomState holds zoom and pan values and allows the user to read and listen * to changes. Clients that modify ZoomState should call notifyObservers() */ public class ZoomState extends Observable { /** * Zoom level A value of 1.0 means the content fits the view. */ private float mZoom; /** * Pan position x-coordinate X-coordinate of zoom window center position, * relative to the width of the content. */ private float mPanX; /** * Pan position y-coordinate Y-coordinate of zoom window center position, * relative to the height of the content. */ private float mPanY; // Public methods /** * Get current x-pan * * @return current x-pan */ public float getPanX() { return mPanX; } /** * Get current y-pan * * @return Current y-pan */ public float getPanY() { return mPanY; } /** * Get current zoom value * * @return Current zoom value */ public float getZoom() { return mZoom; } /** * Help function for calculating current zoom value in x-dimension * * @param aspectQuotient (Aspect ratio content) / (Aspect ratio view) * @return Current zoom value in x-dimension */ public float getZoomX(float aspectQuotient) { return Math.min(mZoom, mZoom * aspectQuotient); } /** * Help function for calculating current zoom value in y-dimension * * @param aspectQuotient (Aspect ratio content) / (Aspect ratio view) * @return Current zoom value in y-dimension */ public float getZoomY(float aspectQuotient) { return Math.min(mZoom, mZoom / aspectQuotient); } /** * Set pan-x * * @param panX Pan-x value to set */ public void setPanX(float panX) { if (panX != mPanX) { mPanX = panX; setChanged(); } } /** * Set pan-y * * @param panY Pan-y value to set */ public void setPanY(float panY) { if (panY != mPanY) { mPanY = panY; setChanged(); } } /** * Set zoom * * @param zoom Zoom value to set */ public void setZoom(float zoom) { if (zoom != mZoom) { mZoom = zoom; setChanged(); } } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; import android.os.Handler; import android.os.SystemClock; import java.util.Observable; import java.util.Observer; /** * The DynamicZoomControl is responsible for controlling a ZoomState. It makes * sure that pan movement follows the finger, that limits are satisfied and that * we can zoom into specific positions. * * In order to implement these control mechanisms access to certain content and * view state data is required which is made possible through the * ZoomContentViewState. */ public class DynamicZoomControl implements Observer { /** Minimum zoom level limit */ private static final float MIN_ZOOM = 1; /** Maximum zoom level limit */ private static final float MAX_ZOOM = 16; /** Velocity tolerance for calculating if dynamic state is resting */ private static final float REST_VELOCITY_TOLERANCE = 0.004f; /** Position tolerance for calculating if dynamic state is resting */ private static final float REST_POSITION_TOLERANCE = 0.01f; /** Target FPS when animating behavior such as fling and snap to */ private static final int FPS = 50; /** Factor applied to pan motion outside of pan snap limits. */ private static final float PAN_OUTSIDE_SNAP_FACTOR = .4f; /** Zoom state under control */ private final ZoomState mState = new ZoomState(); /** Object holding aspect quotient of view and content */ private AspectQuotient mAspectQuotient; /** * Dynamics object for creating dynamic fling and snap to behavior for pan * in x-dimension. */ private final SpringDynamics mPanDynamicsX = new SpringDynamics(); /** * Dynamics object for creating dynamic fling and snap to behavior for pan * in y-dimension. */ private final SpringDynamics mPanDynamicsY = new SpringDynamics(); /** Minimum snap to position for pan in x-dimension */ private float mPanMinX; /** Maximum snap to position for pan in x-dimension */ private float mPanMaxX; /** Minimum snap to position for pan in y-dimension */ private float mPanMinY; /** Maximum snap to position for pan in y-dimension */ private float mPanMaxY; /** Handler for posting runnables */ private final Handler mHandler = new Handler(); /** Creates new zoom control */ public DynamicZoomControl() { mPanDynamicsX.setFriction(2f); mPanDynamicsY.setFriction(2f); mPanDynamicsX.setSpring(50f, 1f); mPanDynamicsY.setSpring(50f, 1f); } /** * Set reference object holding aspect quotient * * @param aspectQuotient Object holding aspect quotient */ public void setAspectQuotient(AspectQuotient aspectQuotient) { if (mAspectQuotient != null) { mAspectQuotient.deleteObserver(this); } mAspectQuotient = aspectQuotient; mAspectQuotient.addObserver(this); } /** * Get zoom state being controlled * * @return The zoom state */ public ZoomState getZoomState() { return mState; } /** * Zoom * * @param f Factor of zoom to apply * @param x X-coordinate of invariant position * @param y Y-coordinate of invariant position */ public void zoom(float f, float x, float y) { final float aspectQuotient = mAspectQuotient.get(); final float prevZoomX = mState.getZoomX(aspectQuotient); final float prevZoomY = mState.getZoomY(aspectQuotient); mState.setZoom(mState.getZoom() * f); limitZoom(); final float newZoomX = mState.getZoomX(aspectQuotient); final float newZoomY = mState.getZoomY(aspectQuotient); // Pan to keep x and y coordinate invariant mState.setPanX(mState.getPanX() + (x - .5f) * (1f / prevZoomX - 1f / newZoomX)); mState.setPanY(mState.getPanY() + (y - .5f) * (1f / prevZoomY - 1f / newZoomY)); updatePanLimits(); mState.notifyObservers(); } /** * Pan * * @param dx Amount to pan in x-dimension * @param dy Amount to pan in y-dimension */ public void pan(float dx, float dy) { final float aspectQuotient = mAspectQuotient.get(); dx /= mState.getZoomX(aspectQuotient); dy /= mState.getZoomY(aspectQuotient); if (mState.getPanX() > mPanMaxX && dx > 0 || mState.getPanX() < mPanMinX && dx < 0) { dx *= PAN_OUTSIDE_SNAP_FACTOR; } if (mState.getPanY() > mPanMaxY && dy > 0 || mState.getPanY() < mPanMinY && dy < 0) { dy *= PAN_OUTSIDE_SNAP_FACTOR; } final float newPanX = mState.getPanX() + dx; final float newPanY = mState.getPanY() + dy; mState.setPanX(newPanX); mState.setPanY(newPanY); mState.notifyObservers(); } /** * Runnable that updates dynamics state */ private final Runnable mUpdateRunnable = new Runnable() { public void run() { final long startTime = SystemClock.uptimeMillis(); mPanDynamicsX.update(startTime); mPanDynamicsY.update(startTime); final boolean isAtRest = mPanDynamicsX.isAtRest(REST_VELOCITY_TOLERANCE, REST_POSITION_TOLERANCE) && mPanDynamicsY.isAtRest(REST_VELOCITY_TOLERANCE, REST_POSITION_TOLERANCE); mState.setPanX(mPanDynamicsX.getPosition()); mState.setPanY(mPanDynamicsY.getPosition()); if (!isAtRest) { final long stopTime = SystemClock.uptimeMillis(); mHandler.postDelayed(mUpdateRunnable, 1000 / FPS - (stopTime - startTime)); } mState.notifyObservers(); } }; /** * Release control and start pan fling animation * * @param vx Velocity in x-dimension * @param vy Velocity in y-dimension */ public void startFling(float vx, float vy) { final float aspectQuotient = mAspectQuotient.get(); final long now = SystemClock.uptimeMillis(); mPanDynamicsX.setState(mState.getPanX(), vx / mState.getZoomX(aspectQuotient), now); mPanDynamicsY.setState(mState.getPanY(), vy / mState.getZoomY(aspectQuotient), now); mPanDynamicsX.setMinPosition(mPanMinX); mPanDynamicsX.setMaxPosition(mPanMaxX); mPanDynamicsY.setMinPosition(mPanMinY); mPanDynamicsY.setMaxPosition(mPanMaxY); mHandler.post(mUpdateRunnable); } /** * Stop fling animation */ public void stopFling() { mHandler.removeCallbacks(mUpdateRunnable); } /** * Help function to figure out max delta of pan from center position. * * @param zoom Zoom value * @return Max delta of pan */ private float getMaxPanDelta(float zoom) { return Math.max(0f, .5f * ((zoom - 1) / zoom)); } /** * Force zoom to stay within limits */ private void limitZoom() { if (mState.getZoom() < MIN_ZOOM) { mState.setZoom(MIN_ZOOM); } else if (mState.getZoom() > MAX_ZOOM) { mState.setZoom(MAX_ZOOM); } } /** * Update limit values for pan */ private void updatePanLimits() { final float aspectQuotient = mAspectQuotient.get(); final float zoomX = mState.getZoomX(aspectQuotient); final float zoomY = mState.getZoomY(aspectQuotient); mPanMinX = .5f - getMaxPanDelta(zoomX); mPanMaxX = .5f + getMaxPanDelta(zoomX); mPanMinY = .5f - getMaxPanDelta(zoomY); mPanMaxY = .5f + getMaxPanDelta(zoomY); } // Observable interface implementation public void update(Observable observable, Object data) { limitZoom(); updatePanLimits(); } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; /** * SpringDynamics is a Dynamics object that uses friction and spring physics to * snap to boundaries and give a natural and organic dynamic. */ public class SpringDynamics extends Dynamics { /** Friction factor */ private float mFriction; /** Spring stiffness factor */ private float mStiffness; /** Spring damping */ private float mDamping; /** * Set friction parameter, friction physics are applied when inside of snap * bounds. * * @param friction Friction factor */ public void setFriction(float friction) { mFriction = friction; } /** * Set spring parameters, spring physics are applied when outside of snap * bounds. * * @param stiffness Spring stiffness * @param dampingRatio Damping ratio, < 1 underdamped, > 1 overdamped */ public void setSpring(float stiffness, float dampingRatio) { mStiffness = stiffness; mDamping = dampingRatio * 2 * (float)Math.sqrt(stiffness); } /** * Calculate acceleration at the current state * * @return Current acceleration */ private float calculateAcceleration() { float acceleration; final float distanceFromLimit = getDistanceToLimit(); if (distanceFromLimit != 0) { acceleration = distanceFromLimit * mStiffness - mDamping * mVelocity; } else { acceleration = -mFriction * mVelocity; } return acceleration; } @Override protected void onUpdate(int dt) { // Calculate dt in seconds as float final float fdt = dt / 1000f; // Calculate current acceleration final float a = calculateAcceleration(); // Calculate next position based on current velocity and acceleration mPosition += mVelocity * fdt + .5f * a * fdt * fdt; // Update velocity mVelocity += a * fdt; } }
Java
/* * Copyright (c) 2010, Sony Ericsson Mobile Communication AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Sony Ericsson Mobile Communication AB nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.dslr.dashboard.imgzoom; import java.util.Currency; import android.content.Context; import android.os.Vibrator; import android.util.FloatMath; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; /** * Listener for controlling zoom state through touch events */ public class LongPressZoomListener implements View.OnTouchListener { private static String TAG = "LongPressZoomListener"; /** * Enum defining listener modes. Before the view is touched the listener is * in the UNDEFINED mode. Once touch starts it can enter either one of the * other two modes: If the user scrolls over the view the listener will * enter PAN mode, if the user lets his finger rest and makes a longpress * the listener will enter ZOOM mode. */ private enum Mode { UNDEFINED, PAN, ZOOM, PINCH } /** Time of tactile feedback vibration when entering zoom mode */ private static final long VIBRATE_TIME = 50; /** Current listener mode */ private Mode mMode = Mode.UNDEFINED; /** Zoom control to manipulate */ private DynamicZoomControl mZoomControl; /** X-coordinate of previously handled touch event */ private float mX; /** Y-coordinate of previously handled touch event */ private float mY; /** X-coordinate of latest down event */ private float mDownX; /** Y-coordinate of latest down event */ private float mDownY; /** Velocity tracker for touch events */ private VelocityTracker mVelocityTracker; /** Distance touch can wander before we think it's scrolling */ private final int mScaledTouchSlop; /** Duration in ms before a press turns into a long press */ private final int mLongPressTimeout; /** Vibrator for tactile feedback */ private final Vibrator mVibrator; /** Maximum velocity for fling */ private final int mScaledMaximumFlingVelocity; float dist0, distCurrent; /** * Creates a new instance * * @param context Application context */ public LongPressZoomListener(Context context) { mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); mScaledMaximumFlingVelocity = ViewConfiguration.get(context) .getScaledMaximumFlingVelocity(); mVibrator = (Vibrator)context.getSystemService("vibrator"); } /** * Sets the zoom control to manipulate * * @param control Zoom control */ public void setZoomControl(DynamicZoomControl control) { mZoomControl = control; } /** * Runnable that enters zoom mode */ private final Runnable mLongPressRunnable = new Runnable() { public void run() { // mMode = Mode.ZOOM; // mVibrator.vibrate(VIBRATE_TIME); } }; // implements View.OnTouchListener public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction() & MotionEvent.ACTION_MASK; final float x = event.getX(); final float y = event.getY(); float distx, disty; if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN: mZoomControl.stopFling(); v.postDelayed(mLongPressRunnable, mLongPressTimeout); mDownX = x; mDownY = y; mX = x; mY = y; break; case MotionEvent.ACTION_POINTER_DOWN: //Get the distance when the second pointer touch mMode = Mode.PINCH; distx = Math.abs(event.getX(0) - event.getX(1)); disty = Math.abs(event.getY(0) - event.getY(1)); dist0 = FloatMath.sqrt((distx * distx) + (disty * disty)); Log.d(TAG, "Pinch mode"); break; case MotionEvent.ACTION_POINTER_UP: mMode = Mode.PAN; break; case MotionEvent.ACTION_MOVE: { final float dx = (x - mX) / v.getWidth(); final float dy = (y - mY) / v.getHeight(); if (mMode == Mode.ZOOM) { //Log.d(TAG, "dy: " + dy + "zoom: " + (float)Math.pow(20, -dy)); mZoomControl.zoom((float)Math.pow(20, -dy), mDownX / v.getWidth(), mDownY / v.getHeight()); } else if (mMode == Mode.PAN) { mZoomControl.pan(-dx, -dy); } else if (mMode == Mode.PINCH) { //Get the current distance distx = Math.abs(event.getX(0) - event.getX(1)); disty = Math.abs(event.getY(0) - event.getY(1)); distCurrent = FloatMath.sqrt((distx * distx) + (disty * disty)); float factor = (distCurrent / dist0) * 2f; //Log.d(TAG, "Pinch distance: "+ distCurrent + "rate: " + (distCurrent/dist0)); mZoomControl.zoom(factor, mDownX / v.getWidth(), mDownY / v.getHeight()); // mZoomControl.zoom((float)Math.pow(1.5, (distCurrent - dist0)/v.getWidth()), mDownX / v.getWidth(), mDownY // / v.getHeight()); } else { final float scrollX = mDownX - x; final float scrollY = mDownY - y; final float dist = (float)Math.sqrt(scrollX * scrollX + scrollY * scrollY); if (dist >= mScaledTouchSlop) { v.removeCallbacks(mLongPressRunnable); mMode = Mode.PAN; } } mX = x; mY = y; break; } case MotionEvent.ACTION_UP: if (mMode == Mode.PAN) { mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity); mZoomControl.startFling(-mVelocityTracker.getXVelocity() / v.getWidth(), -mVelocityTracker.getYVelocity() / v.getHeight()); } else if (mMode == Mode.PINCH) { } else { mZoomControl.startFling(0, 0); } mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = Mode.UNDEFINED; break; default: mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = Mode.UNDEFINED; break; } return true; } }
Java