code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "reserve") @NamedQueries(value = { @NamedQuery(name = "Reserve.getReserveList", query = "SELECT r FROM Reserve r"), @NamedQuery(name = "Reserve.getReserveListByClient", query = "SELECT r FROM Reserve r WHERE r.client = :client") }) public class Reserve implements Serializable { private static final long serialVersionUID = 7972494055377734791L; @Id @Column(name="recode") @OneToMany(mappedBy="reserve") @GeneratedValue(strategy=GenerationType.SEQUENCE) private long recode; @Column(name="barcode", nullable=false, length=23) private String barcode; @ManyToOne @JoinColumn(name = "clcode", nullable = false) private Client client; public Reserve() { this.recode = 0; this.barcode = ""; this.client = new Client(); } public long getRecode() { return recode; } public String getBarcode() { return barcode; } public Client getClient() { return client; } public void setRecode(int recode) { this.recode = recode; } public void setBarcode(String barcode) { this.barcode = barcode; } public void setClient(Client client) { this.client = client; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (recode ^ (recode >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Reserve other = (Reserve) obj; if (recode != other.recode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "genre") @NamedQueries(value = { @NamedQuery(name = "Genre.getGenreList", query = "SELECT g FROM Genre g"), @NamedQuery(name = "Genre.getGenreByGecode", query = "SELECT g FROM Genre g WHERE g.gecode = :gecode") }) public class Genre implements Serializable { private static final long serialVersionUID = -8665299164795806287L; @Id @Column(name="gecode") @OneToMany(mappedBy="genre") @GeneratedValue(strategy=GenerationType.SEQUENCE) private int gecode; @Column(name="description", nullable=false, length=50) private String description; public Genre() { this.gecode = 0; this.description = ""; } public Genre(int gecode, String description) { this.gecode = gecode; this.description = description.toLowerCase(); } public int getGecode() { return gecode; } public void setGecode(int gecode) { this.gecode = gecode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description.toLowerCase(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + gecode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Genre other = (Genre) obj; if (gecode != other.gecode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "publisher") @NamedQueries(value = { @NamedQuery(name = "Publisher.getPublisherList", query = "SELECT p FROM Publisher p"), @NamedQuery(name = "Publisher.getPublisherByPucode", query = "SELECT p FROM Publisher p WHERE p.pucode = :pucode") }) public class Publisher implements Serializable { private static final long serialVersionUID = 7249816599168099617L; @Id @Column(name="pucode") @OneToMany(mappedBy="publisher") @GeneratedValue(strategy=GenerationType.SEQUENCE) private int pucode; @Column(name="description", nullable=false, length=50) private String description; public Publisher() { super(); } public Publisher(int pucode, String description) { this.pucode = pucode; this.description = description; } public void setPucode(int pucode){ this.pucode = pucode; } public int getPucode() { return pucode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pucode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Publisher other = (Publisher) obj; if (pucode != other.pucode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "city") @NamedQueries(value = { @NamedQuery(name = "City.getCityList", query = "SELECT c FROM City c"), @NamedQuery(name = "City.getCityByCicode", query = "SELECT c FROM City c WHERE c.cicode = :cicode"), @NamedQuery(name = "City.getCityByZip", query = "SELECT c FROM City c WHERE c.zip = :zip") }) public class City implements Serializable { private static final long serialVersionUID = -599386346260224871L; public City() { this.setCicode(0); this.setEstate(new Estate()); this.setName(""); this.setZip(""); } @Id @Column(name="cicode") @OneToMany(mappedBy="city") private int cicode; @ManyToOne @JoinColumn(name="escode", nullable=false) private Estate estate; @Column(name="name", nullable=false, length=72) private String name; @Column(name="zip", nullable=false, length=8) private String zip; public int getCicode() { return cicode; } public void setCicode(int cicode) { this.cicode = cicode; } public Estate getEstate() { return estate; } public void setEstate(Estate estate) { this.estate = estate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + cicode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; City other = (City) obj; if (cicode != other.cicode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "address") @NamedQueries(value = { @NamedQuery(name = "Address.getAddressList", query = "SELECT a FROM Address a"), @NamedQuery(name = "Address.getAddressListByZip", query = "SELECT a FROM Address a WHERE a.zip = :zip"), @NamedQuery(name = "Address.getAddressByAdCode", query = "SELECT a FROM Address a WHERE a.adcode = :adcode") }) public class Address implements Serializable { private static final long serialVersionUID = -6783518220349164154L; public Address(){ this.setAdcode(0L); this.setNeighborhood(new Neighborhood()); this.setComplement(""); this.setName(""); this.setZip(""); } @Id @Column(name="adcode") @GeneratedValue(strategy=GenerationType.SEQUENCE) @OneToMany(mappedBy="address") private Long adcode; @ManyToOne @JoinColumn(name="nhcode", nullable=false) private Neighborhood neighborhood; @Column(name="zip", length=8, nullable=false) private String zip; @Column(name="name", nullable=false, length=72) private String name; @Column(name="complement", nullable=false, length=72) private String complement; public String getFormattedZip(){ return this.zip.substring(0,5) + "-" + this.zip.substring(5,8); } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public Neighborhood getNeighborhood() { return neighborhood; } public void setNeighborhood(Neighborhood neighborhood) { this.neighborhood = neighborhood; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } public Long getAdcode() { return adcode; } public void setAdcode(Long adcode) { this.adcode = adcode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((adcode == null) ? 0 : adcode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Address other = (Address) obj; if (adcode == null) { if (other.adcode != null) return false; } else if (!adcode.equals(other.adcode)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "user") @NamedQueries({ @NamedQuery(name = "User.getUserList", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u WHERE u.login = :login"), @NamedQuery(name = "User.findByActive", query = "SELECT u FROM User u WHERE u.active = :active"), @NamedQuery(name = "User.findProfile", query = "SELECT u.profile FROM User u WHERE u.login = :login"), @NamedQuery(name = "User.findByLoginAndPassword", query = "SELECT u FROM User u WHERE u.login = :login and u.password = :password") }) public class User implements Serializable { private static final long serialVersionUID = 8015083950334827537L; public User() { this.setPerson(new Person()); } public User(String login, String password) { this.login = login; this.password = password; } public User(String login, String password, Boolean active) { this.login = login; this.password = password; this.active = active; } @Id @OneToMany(mappedBy="user", cascade={CascadeType.PERSIST}) @Column(name = "login", length = 32) private String login; @Column(name = "password", nullable = false, length = 32) private String password; @Column(name = "active", nullable = false) private Boolean active; @ManyToOne @JoinColumn(name = "procode", nullable = false) private Profile profile; @OneToOne(cascade = {CascadeType.PERSIST}) @JoinColumn(name = "document", nullable = false, referencedColumnName = "document") private Person person; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Profile getProfile() { return this.profile; } public void setProfile(Profile profile) { this.profile = profile; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getFormattedDocument() { return this.person.getDocument().substring(0, 3) + "." + this.person.getDocument().substring(3, 6) + "." + this.person.getDocument().substring(6, 9) + "-" + this.person.getDocument().substring(9, 11); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((login == null) ? 0 : login.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (login == null) { if (other.login != null) return false; } else if (!login.equals(other.login)) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "person_type") public class PersonType implements Serializable { private static final long serialVersionUID = 1568036970314377557L; @Id @Column(name="ptcode") @OneToMany(mappedBy="person_type") @GeneratedValue(strategy=GenerationType.SEQUENCE) private int ptcode; @Column(name="description", nullable=false, length=50) private String description; public PersonType() { super(); } public PersonType(int ptcode, String description){ this.ptcode = ptcode; this.description = description; } public int getPtcode() { return this.ptcode; } public void setPtcode(int ptcode) { this.ptcode = ptcode; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ptcode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PersonType other = (PersonType) obj; if (ptcode != other.ptcode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "profile") @NamedQueries(value = { @NamedQuery(name = "Profile.getProfileList", query = "SELECT p FROM Profile p"), @NamedQuery(name = "Profile.getProfileByProCode", query = "SELECT p FROM Profile p WHERE p.procode = :procode") }) public class Profile implements Serializable { private static final long serialVersionUID = 545010527182510542L; public Profile(){ this.setPages(new ArrayList<Page>()); } @Id @Column(name = "procode") @OneToMany(mappedBy = "profile", cascade= {CascadeType.PERSIST}) @GeneratedValue(strategy = GenerationType.SEQUENCE) private int procode; @Column(name = "description", nullable = false, length = 50) private String description; @ManyToMany @JoinTable(name = "profile_pages", joinColumns = { @JoinColumn(name = "procode") }, inverseJoinColumns = { @JoinColumn(name = "pacode") }) private List<Page> pages; public int getProcode() { return procode; } public void setProcode(int procode) { this.procode = procode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Page> getPages(){ return this.pages; } public void setPages(List<Page> pages){ this.pages = pages; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + procode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Profile other = (Profile) obj; if (procode != other.procode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="client") @NamedQueries(value = { @NamedQuery(name = "Client.getClientList", query = "SELECT c FROM Client c"), @NamedQuery(name = "Client.getClientByClcode", query = "SELECT c FROM Client c WHERE c.clcode = :clcode") }) public class Client implements Serializable { private static final long serialVersionUID = -341935374393970880L; public Client(){ this.setPerson(new Person()); } @Id @Column(name="clcode") @OneToMany(mappedBy="client", cascade = {CascadeType.PERSIST}) @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long clcode; @OneToOne(cascade = {CascadeType.PERSIST}) @JoinColumn(name="document", nullable=false, referencedColumnName="document") private Person person; public Long getClcode() { return clcode; } public void setClcode(Long clcode) { this.clcode = clcode; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getFormattedDocument() { return this.person.getDocument().substring(0, 3) + "." + this.person.getDocument().substring(3, 6) + "." + this.person.getDocument().substring(6, 9) + "-" + this.person.getDocument().substring(9, 11); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clcode == null) ? 0 : clcode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Client other = (Client) obj; if (clcode == null) { if (other.clcode != null) return false; } else if (!clcode.equals(other.clcode)) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "estate") @NamedQueries(value = { @NamedQuery(name = "Estate.getEstateList", query = "SELECT e FROM Estate e"), @NamedQuery(name = "Estate.getEstateById", query = "SELECT e FROM Estate e WHERE e.escode = :escode") }) public class Estate implements Serializable { private static final long serialVersionUID = 4904907938957979302L; public Estate() { this.setEscode(0); this.setAcronym(""); this.setName(""); } @Id @Column(name="escode") @OneToMany(mappedBy="estate") private int escode; @Column(name="acronym", nullable=false, length=2) private String acronym; @Column(name="name", nullable=false, length=72) private String name; public int getEscode() { return escode; } public void setEscode(int escode) { this.escode = escode; } public String getAcronym() { return acronym; } public void setAcronym(String acronym) { this.acronym = acronym; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + escode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Estate other = (Estate) obj; if (escode != other.escode) return false; return true; } }
Java
package com.anjho.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "sale") @NamedQueries(value = { @NamedQuery(name = "Sale.getSaleList", query = "SELECT s FROM Sale s"), @NamedQuery(name = "Sale.getSaleBySalecode", query = "SELECT s FROM Sale s WHERE s.salecode = :salecode") }) public class Sale implements Serializable { private static final long serialVersionUID = 913432155203391627L; public Sale() { this.setSaleDate(new Date()); } public Sale(Client client){ this.client = client; this.setSaleDate(new Date()); } @Id @Column(name="salecode") @OneToMany(mappedBy="sale") @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long salecode; @Temporal(TemporalType.TIMESTAMP) @Column(name = "saleDate", nullable = false) private Date saleDate; @Column(name = "value", nullable = false, precision = 10, scale=2) private BigDecimal value; @ManyToOne @JoinColumn(name="user_login", nullable=false) private User user; @ManyToOne @JoinColumn(name="client", nullable=false) private Client client; @ManyToMany @JoinTable(name = "sale_products", joinColumns = { @JoinColumn(name = "salecode") }, inverseJoinColumns = { @JoinColumn(name = "prcode") }) private List<Product> productList; public Long getSalecode() { return salecode; } public void setSalecode(Long salecode) { this.salecode = salecode; } public Date getSaleDate() { return saleDate; } public void setSaleDate(Date saleDate) { this.saleDate = saleDate; } public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public List<Product> getProductList() { return productList; } public void setProductList(List<Product> productList) { this.productList = productList; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((salecode == null) ? 0 : salecode.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Sale other = (Sale) obj; if (salecode == null) { if (other.salecode != null) return false; } else if (!salecode.equals(other.salecode)) return false; return true; } }
Java
package com.anjho.exceptions; public class InvalidLoginException extends Exception { private static final long serialVersionUID = 815043682736128436L; public InvalidLoginException() { super(); } public InvalidLoginException(String message) { super(message); } public InvalidLoginException(Throwable cause) { super(cause); } public InvalidLoginException(String message, Throwable cause) { super(message, cause); } public InvalidLoginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
Java
package com.anjho.bean; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.primefaces.model.chart.CartesianChartModel; import org.primefaces.model.chart.ChartSeries; @ManagedBean(name = "reportBean") @RequestScoped public class ReportBean extends GenericBean { private static final long serialVersionUID = 1699763483127190743L; public ReportBean() { super(); clearForm(); } private Date startDate; private Date endDate; private CartesianChartModel saleChartModel; public void clearForm(){ this.setSaleChartModel(new CartesianChartModel()); } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public CartesianChartModel getSaleChartModel() { return saleChartModel; } public void setSaleChartModel(CartesianChartModel saleChartModel) { this.saleChartModel = saleChartModel; } public void createChartReport() { setSaleChartModel(new CartesianChartModel()); ChartSeries sales = new ChartSeries(); sales.setLabel("Vendas"); sales.set("Junho", 334); sales.set("Julho", 222); sales.set("Agosto", 293); sales.set("Setembro", 308); sales.set("Outubro", 311); sales.set("Novembro", 189); this.getSaleChartModel().addSeries(sales); } public void onReportClick(){ this.createChartReport(); } }
Java
package com.anjho.bean; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import com.anjho.dao.DAODistributor; import com.anjho.dao.DAOGenre; import com.anjho.dao.DAOProduct; import com.anjho.dao.DAOPublisher; import com.anjho.pojo.Distributor; import com.anjho.pojo.Genre; import com.anjho.pojo.Product; import com.anjho.pojo.Publisher; @ManagedBean(name = "productBean") @ViewScoped public class ProductBean extends GenericBean { private static final long serialVersionUID = -1211807500652292548L; private String barcode; private String proNumber; private String cover; private String name; private BigDecimal price; private int receivedQtd; private Date receiptDate; private Date returnDate; private int gecode; private int pucode; private int dicode; private Genre genre; private Publisher publisher; private Distributor distributor; private List<Genre> genreList; private List<Publisher> publisherList; private List<Distributor> distributorList; private List<Product> productList; private List<Product> filteredProducts; private List<Product> productListWhereReturnIsNull; private Date currentDate = new Date(); private Product product; public ProductBean() { super(); this.clearForm(); } private void clearForm() { this.setBarcode(""); this.setProNumber(""); this.setCover(""); this.setName(""); this.setPrice(new BigDecimal(0)); this.setReceivedQtd(0); this.setReceiptDate(null); this.setReturnDate(null); this.genre = null; this.publisher = null; this.distributor = null; this.setProduct(new Product()); try { DAODistributor daoDistributor = new DAODistributor(); this.distributorList = daoDistributor.getDistributorList(); daoDistributor = null; DAOPublisher daoPublisher = new DAOPublisher(); this.publisherList = daoPublisher.getPublisherList(); daoPublisher = null; DAOGenre daoGenre = new DAOGenre(); this.genreList = daoGenre.getGenreList(); daoGenre = null; } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getProNumber() { return proNumber; } public void setProNumber(String proNumber) { this.proNumber = proNumber; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public int getReceivedQtd() { return receivedQtd; } public void setReceivedQtd(int receivedQtd) { this.receivedQtd = receivedQtd; } public Date getReceiptDate() { return receiptDate; } public void setReceiptDate(Date receiptDate) { this.receiptDate = receiptDate; } public Date getReturnDate() { return returnDate; } public void setReturnDate(Date returnDate) { this.returnDate = returnDate; } public int getGecode() { return gecode; } public void setGecode(int gecode) { this.gecode = gecode; } public int getPucode() { return pucode; } public void setPucode(int pucode) { this.pucode = pucode; } public int getDicode() { return dicode; } public void setDicode(int dicode) { this.dicode = dicode; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public List<Genre> getGenreList() { return genreList; } public List<Publisher> getPublisherList() { return publisherList; } public List<Distributor> getDistributorList() { return distributorList; } public List<Product> getProductList() { synchronized (this) { DAOProduct daoProduct = new DAOProduct(); try { this.productList = daoProduct.getProductList(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } return this.productList; } } public List<Product> getProductListWhereReturnIsNull() { synchronized (this) { DAOProduct daoProduct = new DAOProduct(); try { this.productListWhereReturnIsNull = daoProduct.getProductListWhereReturnIsNull(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } return this.productListWhereReturnIsNull; } } public Date getCurrentDate() { return currentDate; } public List<Product> getFilteredProducts() { return filteredProducts; } public void setFilteredProducts(List<Product> filteredProducts) { this.filteredProducts = filteredProducts; } public void selDistributorChanged(AjaxBehaviorEvent event) { try { if (this.getDicode() != 0) { this.distributor = new Distributor(); this.distributor.setDicode(this.getDicode()); int idxDist = this.getDistributorList().indexOf( this.distributor); this.distributor = this.getDistributorList().get(idxDist); } else { this.distributor = new Distributor(); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void selGenreChanged(AjaxBehaviorEvent event) { try { if (this.getGecode() != 0) { this.genre = new Genre(); this.genre.setGecode(this.getGecode()); int idxGen = this.getGenreList().indexOf(this.genre); this.genre = this.getGenreList().get(idxGen); } else { this.genre = new Genre(); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void selPublisherChanged(AjaxBehaviorEvent event) { try { if (this.getPucode() != 0) { this.publisher = new Publisher(); this.publisher.setPucode(this.pucode); int idxPuc = this.getPublisherList().indexOf(this.publisher); this.publisher = this.getPublisherList().get(idxPuc); } else { this.publisher = new Publisher(); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() throws Exception { try { Product aux = new Product(); aux.setBarcode(this.getBarcode()); aux.setProNumber(this.getProNumber()); aux.setName(this.getName()); aux.setCover(this.cover); aux.setPrice(this.getPrice()); aux.setReceivedQtd(this.getReceivedQtd()); aux.setQtd(this.getReceivedQtd()); aux.setReceiptDate(this.getReceiptDate()); aux.setReturnDate(null); aux.setDistributor(this.distributor); aux.setGenre(this.genre); aux.setPublisher(this.publisher); DAOProduct daoProduct = new DAOProduct(); daoProduct.insert(aux); this.clearForm(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onReturnClick() throws Exception { try { //this.product.setReturnDate(this.returnDate); DAOProduct daoProduct = new DAOProduct(); daoProduct.update(this.product); this.clearForm(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.persistence.NoResultException; import com.anjho.dao.DAOAddress; import com.anjho.dao.DAOProfile; import com.anjho.dao.DAOUser; import com.anjho.pojo.Address; import com.anjho.pojo.PersonType; import com.anjho.pojo.Profile; import com.anjho.pojo.User; @ManagedBean(name = "userBean") @SessionScoped public class UserBean extends GenericBean implements Serializable { private static final long serialVersionUID = -7884871254823505962L; private List<User> userList; private List<Address> addressList; private List<Profile> profileList; private User user; private Address address; private Profile profile; private String cpf; private String name; private int addNumber; private String complement; private Date birthDate; private String phone1; private String phone2; private String email; private long addCode; private int proCode; private String login; private String password; private Boolean active; public UserBean() { super(); clearForm(); } public void clearForm() { this.setUser(new User()); this.setUserList(new ArrayList<User>()); this.setAddressList(new ArrayList<Address>()); this.user = new User(); this.setAddress(new Address()); this.setCpf(""); this.setName(""); this.addNumber = 0; this.complement = ""; this.birthDate = new Date(); this.phone1 = ""; this.phone2 = ""; this.email = ""; this.addCode = 0; this.login = ""; this.password = ""; this.active = true; } public List<User> getUserList() { synchronized (this) { DAOUser daoUser = new DAOUser(); try { this.userList = daoUser.getUserList(); } catch (NoResultException e) { this.userList = new ArrayList<User>(); } catch (Exception e) { e.printStackTrace(); } return userList; } } public void setUserList(List<User> userList) { this.userList = userList; } public List<Address> getAddressList() { return addressList; } public void setAddressList(List<Address> addressList) { this.addressList = addressList; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAddNumber() { return addNumber; } public void setAddNumber(int addNumber) { this.addNumber = addNumber; } public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { phone1 = phone1.replaceAll("[^0-9]", ""); this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { phone2 = phone2.replaceAll("[^0-9]", ""); this.phone2 = phone2; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public long getAddCode() { return addCode; } public void setAddCode(long addCode) { this.addCode = addCode; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean isActive() { return active; } public void setActive(Boolean active) { this.active = active; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public int getProCode() { return proCode; } public void setProCode(int proCode) { this.proCode = proCode; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public List<Profile> getProfileList() { synchronized (this) { DAOProfile daoProfile = new DAOProfile(); try { this.profileList = daoProfile.getProfileList(); } catch (NoResultException e) { this.profileList = new ArrayList<Profile>(); } catch (Exception e) { e.printStackTrace(); } return profileList; } } public void selAddressChanged(AjaxBehaviorEvent event) { try { if (this.getAddCode() != 0) { DAOAddress daoAddress = new DAOAddress(); this.setAddress(daoAddress.getAddressByAdCode(this.getAddCode())); daoAddress = null; } else { this.setAddress(new Address()); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void selProfileChanged(AjaxBehaviorEvent event) { try { if (this.getProCode() != 0) { DAOProfile daoProfile = new DAOProfile(); this.setProfile(daoProfile.getProfileByProCode(this .getProCode())); } else { this.setProfile(new Profile()); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() throws Exception { try { User aux = new User(); aux.getPerson().setAddress(this.getAddress()); aux.getPerson().setAddressNumber(this.getAddNumber()); aux.getPerson().setDocument(this.getCpf().replaceAll("[^0-9]", "")); aux.getPerson().setName(this.getName()); aux.getPerson().setPersonType(new PersonType(1, "Física")); aux.getPerson().setBirthDate(this.getBirthDate()); aux.getPerson().setEmail(this.getEmail()); aux.getPerson().setComplement(this.getComplement()); aux.getPerson().setPhone1(this.getPhone1()); aux.getPerson().setPhone2(this.getPhone2()); aux.setActive(this.isActive()); aux.setLogin(this.getLogin()); aux.setPassword(this.getPassword()); aux.setProfile(this.getProfile()); DAOUser daoUser = new DAOUser(); daoUser.insert(aux); this.clearForm(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean(name = "profileBean") @RequestScoped public class ProfileBean extends GenericBean { private static final long serialVersionUID = -2844364498965991863L; public ProfileBean() { super(); } }
Java
package com.anjho.bean; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.AjaxBehaviorEvent; import com.anjho.dao.DAOAddress; import com.anjho.dao.DAODistributor; import com.anjho.exceptions.InvalidDistributorException; import com.anjho.pojo.Address; import com.anjho.pojo.City; import com.anjho.pojo.Distributor; import com.anjho.pojo.Estate; import com.anjho.pojo.Neighborhood; import com.anjho.pojo.PersonType; @ManagedBean(name = "distributorBean") @ViewScoped public class DistributorBean extends GenericBean { private static final long serialVersionUID = 1340222169169083861L; private Distributor distributor; private String email; private String name; private String cnpj; private String street; private String zip; private String neigh; private int addNumber; private long addCode; private String segment; private Estate estate; private City city; private Address address; private Neighborhood neighborhood; private List<Address> addresses; private Boolean addressFound; private List<Distributor> distributorList; public DistributorBean() { super(); this.clearForm(); } public void clearForm() { this.setDistributor(new Distributor()); this.setEstate(new Estate()); this.setCity(new City()); this.setNeighborhood(new Neighborhood()); this.setAddress(new Address()); this.setAddresses(new ArrayList<Address>()); this.setDistributorList(new ArrayList<Distributor>()); this.setStreet(""); this.setCnpj(""); this.setEmail(""); this.setName(""); this.setSegment(""); this.setAddressFound(true); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public Distributor getDistributor() { return distributor; } public void setDistributor(Distributor distributor) { this.distributor = distributor; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public int getAddNumber() { return addNumber; } public void setAddNumber(int addNumber) { this.addNumber = addNumber; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } public Boolean isAddressFound() { return addressFound; } public void setAddressFound(Boolean addressFound) { this.addressFound = addressFound; } public Estate getEstate() { return estate; } public void setEstate(Estate estate) { this.estate = estate; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Neighborhood getNeighborhood() { return neighborhood; } public void setNeighborhood(Neighborhood neighborhood) { this.neighborhood = neighborhood; } public String getNeigh() { return neigh; } public void setNeigh(String neigh) { this.neigh = neigh; } public List<Distributor> getDistributorList() throws Exception { synchronized (this) { DAODistributor daoDistributor = new DAODistributor(); this.distributorList = daoDistributor.getDistributorList(); return this.distributorList; } } public void setDistributorList(List<Distributor> distributorList) { this.distributorList = distributorList; } public Boolean getAddressFound() { return addressFound; } public long getAddCode() { return addCode; } public void setAddCode(long addCode) { this.addCode = addCode; } public String getSegment() { return segment; } public void setSegment(String segment) { this.segment = segment; } public void selDistChanged(AjaxBehaviorEvent event) { try { if (this.addCode != 0) { DAOAddress daoAddress = new DAOAddress(); this.address = daoAddress.getAddressByAdCode(this.addCode); daoAddress = null; } else { this.address = new Address(); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro",ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onSaveClick() throws Exception { try { DAODistributor daoDistributor = new DAODistributor(); daoDistributor.update(distributor); this.distributor = new Distributor(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() throws Exception { try { Distributor aux = new Distributor(); /*if (!addressFound) { Neighborhood neiAux = new Neighborhood(); neiAux.setCity(this.getCity()); neiAux.setName(neigh); this.getAddress().setNeighborhood(neiAux); this.getAddress().setName(street); }*/ aux.getPerson().setAddress(this.getAddress()); aux.getPerson().setAddressNumber(this.getAddNumber()); aux.getPerson().setDocument(this.getCnpj().replaceAll("[^0-9]", "")); aux.getPerson().setName(this.getName()); aux.getPerson().setPersonType(new PersonType(2, "Jurídica")); // to distributors, this date means the register date. aux.getPerson().setBirthDate(Calendar.getInstance().getTime()); aux.getPerson().setEmail(this.getEmail()); aux.setSegment(this.getSegment()); DAODistributor daoDistributor = new DAODistributor(); daoDistributor.insert(aux); daoDistributor = null; this.clearForm(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onDeleteClick(ActionEvent actionEvent) { try { if (this.getDistributor() == null) { throw new InvalidDistributorException("É necessário selecionar um distribuidor antes de executar esta operação!"); } DAODistributor daoDistributor = new DAODistributor(); daoDistributor.delete(this.distributor); daoDistributor = null; } catch (SQLException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na base de dados", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (InvalidDistributorException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Distribuidor inválido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import com.anjho.dao.DAOUser; import com.anjho.exceptions.InvalidLoginException; import com.anjho.pojo.Page; import com.anjho.pojo.User; import com.anjho.utils.Constants; /** * @author Jhonathan Corrêa * @version 0.9 * @since 2012/02/23 * @category ManagedBean * * ManagedBean Responsável pelo processo de autenticação * */ @ManagedBean(name = "loginBean") @SessionScoped public class LoginBean extends GenericBean implements Serializable { private static final long serialVersionUID = -1982748532975289462L; private boolean logged = false; private User user; public LoginBean() { super(); init(); } private void init() { this.user = new User(); } private String redirect() { return "/pages/index.jsf?faces-redirect=true"; } public String onLoginClick() { String url = null; try { DAOUser daoUser = new DAOUser(); this.user = daoUser.getUser(this.user); daoUser = null; if (this.user == null){ throw new InvalidLoginException("Login e senha inválidos!"); } this.setLogged(true); this.putInSession(Constants.LOGGED_USER, this.user); url = redirect(); } catch (InvalidLoginException e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Informações inválidas", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } return url; } public String logout() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext() .getSession(false); session.invalidate(); return Constants.LOGIN_PAGE; } public User getUser(){ return this.user; } public void setUser(User user){ this.user = user; } public boolean hasPermission(String page){ Page pemitedPage = new Page(page); if (this.user.getProfile().getPages().contains(pemitedPage)){ return true; } return false; } public boolean isLogged(){ return this.logged; } private void setLogged(boolean logged){ this.logged = logged; } }
Java
package com.anjho.bean; import java.io.Serializable; import java.util.Map; import javax.faces.context.FacesContext; public abstract class GenericBean implements Serializable { private static final long serialVersionUID = 2941146782422586503L; protected Object getFromSession(String key) { Map<String, Object> sessionMap = FacesContext.getCurrentInstance() .getExternalContext().getSessionMap(); return sessionMap.get(key); } protected void putInSession(String key, Object value) { FacesContext.getCurrentInstance().getExternalContext().getSessionMap() .put(key, value); } }
Java
package com.anjho.bean; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import org.eclipse.persistence.exceptions.DatabaseException; import org.primefaces.event.SelectEvent; import com.anjho.dao.DAOProduct; import com.anjho.dao.DAOReserve; import com.anjho.exceptions.InvalidGenreException; import com.anjho.pojo.Client; import com.anjho.pojo.Product; import com.anjho.pojo.Reserve; @ManagedBean(name = "reserveBean") @ViewScoped public class ReserveBean extends GenericBean { private static final long serialVersionUID = -462607283491688642L; private Client client; private Product product; private Product reservedProduct; private List<Reserve> reserveList; private List<Product> reservedProductList; private List<Product> productList; public ReserveBean() { super(); this.clearForm(); } public void clearForm(){ this.reserveList = new ArrayList<Reserve>(); this.reservedProductList = new ArrayList<Product>(); this.productList = new ArrayList<Product>(); this.product = new Product(); this.client = new Client(); } public void setReservedProductList(List<Product> reservedProductList) { this.reservedProductList = reservedProductList; } public void setProductList(List<Product> productList) { this.productList = productList; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public List<Reserve> getReserveList() { return reserveList; } public void setReserveList(List<Reserve> reserveList) { this.reserveList = reserveList; } public List<Product> getProductList() { synchronized (this) { DAOProduct daoProduct = new DAOProduct(); try { productList = daoProduct.getProductList(); } catch (Exception e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } return productList; } } public List<Product> getReservedProductList() { this.acClientSelect(null); return reservedProductList; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Product getReservedProduct() { return reservedProduct; } public void setReservedProduct(Product reservedProduct) { this.reservedProduct = reservedProduct; } public void acClientSelect(SelectEvent event) { DAOReserve daoReserve = new DAOReserve(); DAOProduct daoProduct = new DAOProduct(); this.reservedProductList = new ArrayList<Product>(); try { if (this.client != null){ this.reserveList = daoReserve.getReserveListByClient(this.client); for (Reserve reserve : this.reserveList){ this.reservedProductList.add(daoProduct.getProductByBarcode(reserve.getBarcode())); } } } catch (Exception e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick(ActionEvent actionEvent){ try { Reserve aux = new Reserve(); aux.setBarcode(this.product.getBarcode()); aux.setClient(this.client); DAOReserve daoReserve = new DAOReserve(); daoReserve.insert(aux); daoReserve = null; } catch (Exception e){ FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onDeleteClick(ActionEvent actionEvent) { try { if (this.reservedProduct.getBarcode().equals("")){ throw new Exception("É necessário selecionar uma reserva antes de executar esta operação!"); } Reserve aux = null; for (Reserve reserve : this.getReserveList()){ if (reserve.getBarcode().equals(this.reservedProduct.getBarcode())){ aux = reserve; break; } } if (aux == null){ throw new Exception("Operação não permitida"); } DAOReserve daoReserve = new DAOReserve(); daoReserve.delete(aux); daoReserve = null; } catch (DatabaseException ex){ FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Erro ao excluir", "Verifique se o gênero selecionado não possui produtos vinculados!"); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (SQLException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na base de dados", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (InvalidGenreException ex){ FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Gênero inválido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.persistence.NoResultException; import com.anjho.dao.DAOAddress; import com.anjho.dao.DAOClient; import com.anjho.pojo.Address; import com.anjho.pojo.Client; import com.anjho.pojo.PersonType; @ManagedBean(name = "clientBean") @ViewScoped public class ClientBean extends GenericBean implements Serializable { private static final long serialVersionUID = -6018881894794967212L; private List<Client> filteredClients; private List<Client> clientList; private List<Address> addressList; private Address address; private Client client; private String cpf; private String name; private int addNumber; private String complement; private Date birthDate; private String phone1; private String phone2; private String email; private long addCode; public ClientBean() { super(); clearForm(); } public void clearForm() { this.setClientList(new ArrayList<Client>()); this.setAddressList(new ArrayList<Address>()); this.setAddress(new Address()); this.setCpf(""); this.setName(""); this.addNumber = 0; this.complement = ""; this.birthDate = new Date(); this.phone1 = ""; this.phone2 = ""; this.email = ""; this.addCode = 0; } public List<Client> getClientList() { synchronized (this) { DAOClient daoClient = new DAOClient(); try { this.clientList = daoClient.getClientList(); } catch (NoResultException e) { this.clientList = new ArrayList<Client>(); } catch (Exception e) { e.printStackTrace(); } return this.clientList; } } public List<Client> completeClients(String query) { List<Client> suggestions = new ArrayList<Client>(); for (Client c : this.getClientList()) { if (c.getPerson().getName().startsWith(query)) { suggestions.add(c); } } return suggestions; } public List<Address> getAddressList() { return addressList; } public void setClientList(List<Client> clientList) { this.clientList = clientList; } public void setAddressList(List<Address> addressList) { this.addressList = addressList; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAddNumber() { return addNumber; } public void setAddNumber(int addNumber) { this.addNumber = addNumber; } public String getComplement() { return complement; } public void setComplement(String complement) { this.complement = complement; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { phone1 = phone1.replaceAll("[^0-9]", ""); this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { phone2 = phone2.replaceAll("[^0-9]", ""); this.phone2 = phone2; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public long getAddCode() { return addCode; } public void setAddCode(long addCode) { this.addCode = addCode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public List<Client> getFilteredClients() { return filteredClients; } public void setFilteredClients(List<Client> filteredClients) { this.filteredClients = filteredClients; } public void selAddressChanged(AjaxBehaviorEvent event) { try { if (this.getAddCode() != 0) { DAOAddress daoAddress = new DAOAddress(); this.setAddress(daoAddress.getAddressByAdCode(this.getAddCode())); daoAddress = null; } else { this.setAddress(new Address()); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() throws Exception { try { Client aux = new Client(); aux.getPerson().setAddress(this.getAddress()); aux.getPerson().setAddressNumber(this.getAddNumber()); aux.getPerson().setDocument(this.getCpf().replaceAll("[^0-9]", "")); aux.getPerson().setName(this.getName()); aux.getPerson().setPersonType(new PersonType(1, "Física")); aux.getPerson().setBirthDate(this.getBirthDate()); aux.getPerson().setEmail(this.getEmail()); aux.getPerson().setComplement(this.getComplement()); aux.getPerson().setPhone1(this.getPhone1()); aux.getPerson().setPhone2(this.getPhone2()); DAOClient daoClient = new DAOClient(); daoClient.insert(aux); daoClient = null; this.clearForm(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import com.anjho.dao.DAOGenre; import com.anjho.exceptions.InvalidGenreException; import com.anjho.pojo.Genre; import org.eclipse.persistence.exceptions.DatabaseException; @ManagedBean(name = "genreBean") @RequestScoped public class GenreBean extends GenericBean implements Serializable { private static final long serialVersionUID = -1219853811120929598L; private List<Genre> genreList; private Genre genre; private String description; private DAOGenre daoGenre; public GenreBean() { super(); this.genre = new Genre(); this.genreList = new ArrayList<Genre>(); daoGenre = new DAOGenre(); } public void setGenreList(List<Genre> genreList) { this.genreList = genreList; } public List<Genre> getGenreList() throws Exception { synchronized (this) { genreList = daoGenre.getGenreList(); return genreList; } } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void onDeleteClick(ActionEvent actionEvent) { try { if ((this.genre == null) || (this.genre.getDescription().equals(""))){ throw new InvalidGenreException("É necessário selecionar um gênero antes de executar esta operação!"); } daoGenre.delete(this.genre); this.genre = new Genre(); } catch (DatabaseException ex){ FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Erro ao excluir", "Verifique se o gênero selecionado não possui produtos vinculados!"); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (SQLException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na base de dados", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (InvalidGenreException ex){ FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Gênero inválido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onSaveClick() { try { daoGenre.update(this.genre); } catch (Exception e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, null, "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() { try { Genre aux = new Genre(); aux.setDescription(description); daoGenre.insert(aux); this.description = ""; } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, null, "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.persistence.NoResultException; import org.primefaces.event.SelectEvent; import com.anjho.dao.DAOClient; import com.anjho.dao.DAOProduct; import com.anjho.dao.DAOSale; import com.anjho.pojo.Client; import com.anjho.pojo.Product; import com.anjho.pojo.Sale; import com.anjho.pojo.User; import com.anjho.utils.Constants; @ManagedBean(name = "saleBean") @ViewScoped public class SaleBean extends GenericBean { private static final long serialVersionUID = 7208611040506239884L; private List<Product> productList; private Product product; private String barcode; private String proNumber; private Sale sale; private Client client; private boolean allowSelectClient; private BigDecimal total; private Product prodAuxTbl; public SaleBean() { super(); this.clearForm(); } public void clearForm() { this.productList = new ArrayList<Product>(); this.product = new Product(); this.prodAuxTbl = new Product(); this.allowSelectClient = false; this.total = new BigDecimal(0); this.barcode = ""; this.proNumber = ""; try { DAOClient daoClient = new DAOClient(); this.client = (Client) daoClient.getObjectByParameter( new String[] { "clcode" }, new Object[] { 1 }, "Client.getClientByClcode"); this.sale = new Sale(); } catch (Exception e) { FacesMessage facesMsg = new FacesMessage( FacesMessage.SEVERITY_FATAL, "Erro", e.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public List<Product> getProductList() { return productList; } public void setProductList(List<Product> productList) { this.productList = productList; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getProNumber() { return proNumber; } public void setProNumber(String proNumber) { this.proNumber = proNumber; } public Sale getSale() { return sale; } public void setSale(Sale sale) { this.sale = sale; } public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } public boolean isAllowSelectClient() { return allowSelectClient; } public void setAllowSelectClient(boolean allowSelectClient) { this.allowSelectClient = allowSelectClient; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } public Product getProdAuxTbl() { return prodAuxTbl; } public void setProdAuxTbl(Product prodAuxTbl) { this.prodAuxTbl = prodAuxTbl; } public void onTxtProductBarcodeBlur() throws Exception { try { DAOProduct daoProduct = new DAOProduct(); this.product = daoProduct.getProductByBarcode(this.barcode); daoProduct = null; } catch (NoResultException ex) { this.product = new Product(); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void acClientSelect(SelectEvent event) { this.sale.setClient(this.client); } public void onAddToSaleList() { try { this.productList.add(this.product); this.total = new BigDecimal(0); for (Product prod : this.productList) { this.total = this.total.add(prod.getPrice()); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRemoveFromSaleList() { try { this.productList.remove(this.prodAuxTbl); this.total = new BigDecimal(0); for (Product prod : this.productList) { this.total = this.total.add(prod.getPrice()); } } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onCloseSale() { try { this.sale.setClient(this.client); this.sale.setUser((User) super.getFromSession(Constants.LOGGED_USER)); this.sale.setValue(this.total); this.sale.setSaleDate(new Date()); this.sale.setProductList(this.productList); DAOSale daoSale = new DAOSale(); daoSale.insert(this.sale); daoSale = null; //TODO : Corrigir assim que surgir uma melhor forma de fazer DAOProduct daoProduct = new DAOProduct(); for (Product pro : this.sale.getProductList()){ pro.setQtd(pro.getQtd()-1); daoProduct.update(pro); } daoProduct = null; this.clearForm(); FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso", "Venda efetuada com sucesso!"); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.bean; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.event.AjaxBehaviorEvent; import javax.persistence.NoResultException; import com.anjho.dao.DAOAddress; import com.anjho.dao.DAOCity; import com.anjho.pojo.Address; import com.anjho.pojo.City; import com.anjho.pojo.Estate; import com.anjho.pojo.Neighborhood; @ManagedBean(name = "addressBean") @ViewScoped public class AddressBean extends GenericBean { private static final long serialVersionUID = 1197156706786459597L; private String zip; private List<Address> addressList; private Address address; private Neighborhood neighborhood; private City city; private Estate estate; private long addCode; private boolean addressFound; public AddressBean() { super(); this.clearForm(); } public void clearForm() { this.zip = ""; this.addressList = new ArrayList<Address>(); this.address = new Address(); this.neighborhood = new Neighborhood(); this.city = new City(); this.estate = new Estate(); this.addressFound = false; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public List<Address> getAddressList() { return addressList; } public void setAddressList(List<Address> addressList) { this.addressList = addressList; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Neighborhood getNeighborhood() { return neighborhood; } public void setNeighborhood(Neighborhood neighborhood) { this.neighborhood = neighborhood; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public Estate getEstate() { return estate; } public void setEstate(Estate estate) { this.estate = estate; } public long getAddCode() { return addCode; } public void setAddCode(long addCode) { this.addCode = addCode; } public boolean isAddressFound() { return addressFound; } public void setAddressFound(boolean addressFound) { this.addressFound = addressFound; } public void loadAddresses(AjaxBehaviorEvent event) { DAOAddress daoAddress = null; zip = zip.replaceAll("[^0-9]", ""); try { daoAddress = new DAOAddress(); this.addressList = daoAddress.getAddressListByZip(zip); if (this.addressList.isEmpty()) { throw new NoResultException(); } this.setNeighborhood(this.addressList.get(0).getNeighborhood()); this.setCity(this.neighborhood.getCity()); this.setEstate(this.city.getEstate()); } catch (NoResultException e) { try { /* ALGUMAS CIDADES MENORES PODEM POSSUIR UM ÚNICO CEP E POR */ /* ESSE MOTIVO AS LINHAS ABAIXO FORAM IMPLEMENTADAS. */ DAOCity daoCity = new DAOCity(); this.setCity(daoCity.getCityByZip(zip)); this.setEstate(this.getCity().getEstate()); this.setNeighborhood(new Neighborhood()); this.neighborhood.setCity(this.getCity()); this.setAddress(new Address()); this.address.setNeighborhood(this.getNeighborhood()); this.setAddressFound(false); } catch (NoResultException ex) { this.clearForm(); this.setAddressFound(false); } catch (Exception ex) { this.clearForm(); this.setAddressFound(false); ex.printStackTrace(); } } catch (Exception e) { this.clearForm(); this.setAddressFound(false); e.printStackTrace(); } } }
Java
package com.anjho.bean; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import com.anjho.dao.DAOPublisher; import com.anjho.exceptions.InvalidGenreException; import com.anjho.exceptions.InvalidPublisherException; import com.anjho.pojo.Publisher; @ManagedBean(name = "publisherBean") @RequestScoped public class PublisherBean extends GenericBean implements Serializable { private static final long serialVersionUID = -3134517238480190041L; private List<Publisher> publisherList; private Publisher publisher; private String description; private DAOPublisher daoPublisher; public PublisherBean() { super(); this.setPublisher(new Publisher()); this.setPublisherList(new ArrayList<Publisher>()); daoPublisher = new DAOPublisher(); } public void setPublisherList(List<Publisher> publisherList) { this.publisherList = publisherList; } public List<Publisher> getPublisherList() throws Exception { synchronized (this) { publisherList = daoPublisher.getPublisherList(); return publisherList; } } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void onDeleteClick() { try { if ((this.publisher == null) || (this.publisher.getDescription().equals(""))){ throw new InvalidGenreException("É necessário selecionar uma editora antes de executar esta operação!"); } daoPublisher.delete(publisher); } catch (SQLException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na base de dados", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (InvalidPublisherException ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Editora inválida", ex.getMessage()); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro desconhecido", "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onSaveClick() { try { daoPublisher.update(this.publisher); } catch (Exception e) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, null, "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } public void onRegisterClick() { try { Publisher aux = new Publisher(); aux.setDescription(this.description); daoPublisher.insert(aux); this.description = ""; } catch (Exception ex) { FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_FATAL, null, "Houve um erro não identificado."); FacesContext.getCurrentInstance().addMessage(null, facesMsg); } } }
Java
package com.anjho.dao; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; import com.anjho.pojo.Client; @FacesConverter(value = "clientConverter") public class DAOClient extends DAOGeneric implements Converter { private static final long serialVersionUID = -7622407981574104674L; public DAOClient() { super(); } @SuppressWarnings("unchecked") public List<Client> getClientList() throws Exception { return (List<Client>) super.getList("Client.getClientList"); } public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) { if (submittedValue.trim().equals("")) { return null; } else { try { long clcode = Long.parseLong(submittedValue); for (Client c : getClientList()) { if (c.getClcode() == clcode) { return c; } } } catch (Exception ex) { throw new ConverterException(new FacesMessage( FacesMessage.SEVERITY_ERROR, "Erro de conversão", "Cliente inválido")); } } return null; } public String getAsString(FacesContext facesContext, UIComponent component, Object value) { if (value == null || value.equals("")) { return ""; } else { return String.valueOf(((Client) value).getClcode()); } } }
Java
package com.anjho.dao; public class DAOSaleProducts extends DAOGeneric { private static final long serialVersionUID = -2072818636131249000L; public DAOSaleProducts(){ super(); } }
Java
package com.anjho.dao; public class DAOPage extends DAOGeneric { private static final long serialVersionUID = 9071953535030669298L; public DAOPage() { super(); } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.List; import javax.persistence.Query; import com.anjho.pojo.City; public class DAOCity extends DAOGeneric implements Serializable { private static final long serialVersionUID = 6522206391994327208L; public DAOCity() { super(); } @SuppressWarnings("unchecked") public List<City> getCityList() throws Exception { return (List<City>)super.getList("City.getCityList"); } public City getCityByZip(String zip) { Query query = entityManager.createNamedQuery("City.getCityByZip"); query.setParameter("zip", zip); System.out.println(query.toString()); City city = (City) query.getSingleResult(); return city; } }
Java
package com.anjho.dao; import java.util.List; import com.anjho.pojo.Profile; public class DAOProfile extends DAOGeneric { private static final long serialVersionUID = -6797093276771933283L; public DAOProfile() { super(); } public Profile getProfileByProCode(int procode) throws Exception { return (Profile)super.getObjectByParameter(new String[]{"procode"}, new Object[]{procode}, "Profile.getProfileByProCode"); //return (Profile)super.getObjectBy(procode, "Profile.getProfileByProCode", "procode"); } @SuppressWarnings("unchecked") public List<Profile> getProfileList() throws Exception { return (List<Profile>)super.getList("Profile.getProfileList"); } }
Java
package com.anjho.dao; import java.util.List; import com.anjho.pojo.Product; public class DAOProduct extends DAOGeneric { private static final long serialVersionUID = -2073101124124204476L; public DAOProduct() { super(); } @SuppressWarnings("unchecked") public List<Product> getProductList() throws Exception { return (List<Product>)super.getList("Product.getProductList"); } @SuppressWarnings("unchecked") public List<Product> getProductListWhereReturnIsNull() throws Exception { return (List<Product>)super.getList("Product.getProductListWhereReturnIsNull"); } public Product getProductByBarcode(String barcode) throws Exception { return (Product)super.getObjectByParameter(new String[] {"barcode"}, new Object[]{barcode}, "Product.getProductByBarcode"); } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.List; import javax.persistence.Query; import com.anjho.pojo.Address; public class DAOAddress extends DAOGeneric implements Serializable { private static final long serialVersionUID = 6522206391994327208L; public DAOAddress() { super(); } @SuppressWarnings("unchecked") public List<Address> getAddressList() throws Exception { return (List<Address>)super.getList("Address.getAddressList"); } @SuppressWarnings("unchecked") public List<Address> getAddressListByZip(String zip) { Query query = entityManager.createNamedQuery("Address.getAddressListByZip"); query.setParameter("zip", zip); System.out.println(query.toString()); List<Address> addresses = null; try { addresses = query.getResultList(); } catch (Exception e){ //TODO: TRATAMENTO DE ERROS e.printStackTrace(); } return addresses; } public Address getAddressByAdCode(Long adcode) { Query query = entityManager.createNamedQuery("Address.getAddressByAdCode"); query.setParameter("adcode", adcode); System.out.println(query.toString()); Address address = null; try { address = (Address)query.getSingleResult(); } catch (Exception e){ //TODO: TRATAMENTO DE ERROS e.printStackTrace(); } return address; } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.List; import javax.persistence.NoResultException; import com.anjho.exceptions.InvalidLoginException; import com.anjho.pojo.User; public class DAOUser extends DAOGeneric implements Serializable { private static final long serialVersionUID = -4538459926877845629L; public DAOUser() { super(); } @SuppressWarnings("unchecked") public List<User> getUserList() throws Exception { return (List<User>) super.getList("User.getUserList"); } public User getUser(User user) throws Exception { User userReturn = null; try { userReturn = (User) entityManager .createNamedQuery("User.findByLoginAndPassword") .setParameter("login", user.getLogin()) .setParameter("password", user.getPassword()) .getSingleResult(); if (userReturn == null) { throw new InvalidLoginException("Login e senha inválidos!"); } } catch (InvalidLoginException e) { throw e; } catch (NoResultException e) { throw new InvalidLoginException("Login e senha inválidos!"); } catch (Exception e) { throw e; } return userReturn; } }
Java
package com.anjho.dao; public class DAOSale extends DAOGeneric { private static final long serialVersionUID = 6083028868068378230L; public DAOSale(){ super(); } }
Java
package com.anjho.dao; import java.util.List; import javax.persistence.Query; import com.anjho.pojo.Distributor; public class DAODistributor extends DAOGeneric { private static final long serialVersionUID = -602976644471340449L; public DAODistributor() { super(); } @SuppressWarnings("unchecked") public List<Distributor> getDistributorList() throws Exception { return (List<Distributor>)super.getList("Distributor.getDistributorList"); } public Distributor getDistributorByDicode(int dicode){ Query query = entityManager.createNamedQuery("Distributor.getDistributorByDicode"); query.setParameter("dicode", dicode); Distributor distributor = null; try { distributor = (Distributor)query.getSingleResult(); } catch (Exception e){ //TODO: TRATAMENTO DE ERROS e.printStackTrace(); } return distributor; } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.List; import com.anjho.pojo.Publisher; public class DAOPublisher extends DAOGeneric implements Serializable { private static final long serialVersionUID = 8615324497658512118L; public DAOPublisher() { super(); } @SuppressWarnings("unchecked") public List<Publisher> getPublisherList() throws Exception { return (List<Publisher>)super.getList("Publisher.getPublisherList"); } public Publisher getPublisherByPucode(int pucode) throws Exception{ return (Publisher)super.getObjectByParameter(new String[]{"pucode"}, new Object[]{pucode}, "Publisher.getPublisherByPucode"); //return (Publisher)super.getObjectById(pucode, "Publisher.getPublisherByPucode", "pucode"); } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.List; import com.anjho.pojo.Genre; public class DAOGenre extends DAOGeneric implements Serializable { private static final long serialVersionUID = 3068785072737688771L; public DAOGenre() { super(); } @SuppressWarnings("unchecked") public List<Genre> getGenreList() throws Exception { return (List<Genre>)super.getList("Genre.getGenreList"); } public Genre getGenreByGecode(int gecode) throws Exception{ return (Genre)super.getObjectByParameter(new String[] {"gecode"}, new Object[]{gecode}, "Genre.getGenreByGecode"); //return (Genre)super.getObjectById(gecode, "Genre.getGenreByGecode", "gecode"); } }
Java
package com.anjho.dao; import java.util.List; import com.anjho.pojo.Client; import com.anjho.pojo.Reserve; public class DAOReserve extends DAOGeneric { private static final long serialVersionUID = 2585460796120735865L; public DAOReserve(){ super(); } @SuppressWarnings("unchecked") public List<Reserve> getReserveListByClient(Client client) throws Exception { return (List<Reserve>) super.getListByParameter(new String[]{"client"}, new Object[]{client}, "Reserve.getReserveListByClient"); } }
Java
package com.anjho.dao; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.NoResultException; import javax.persistence.Persistence; import javax.persistence.Query; public abstract class DAOGeneric implements Serializable { private static final long serialVersionUID = -2816886614097588323L; protected EntityManager entityManager; protected DAOGeneric() { EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("Anjho"); entityManager = entityManagerFactory.createEntityManager(); } public EntityManager getEntityManager() { return this.entityManager; } public void insert(Object object) { try { entityManager.getTransaction().begin(); entityManager.persist(object); entityManager.flush(); entityManager.getTransaction().commit(); } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw e; } } public void delete(Object object) throws Exception { try { entityManager.getTransaction().begin(); object = entityManager.merge(object); entityManager.remove(object); entityManager.flush(); entityManager.getTransaction().commit(); } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw e; } } public void update(Object object) throws Exception { try { entityManager.getTransaction().begin(); entityManager.merge(object); entityManager.flush(); entityManager.getTransaction().commit(); } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } throw e; } } public List<?> getList(String namedQuery) throws Exception { List<?> objectList = null; try { objectList = entityManager.createNamedQuery(namedQuery) .getResultList(); } catch (NoResultException e) { objectList = new ArrayList<>(); } catch (Exception e) { throw e; } return objectList; } public List<?> getListByParameter(String[] parameters, Object[] values, String namedQuery) throws Exception { if (parameters.length != values.length) { throw new Exception( "A quantidade de parâmetros informados é diferente da quantidade de valores"); } Query query = entityManager.createNamedQuery(namedQuery); int currentValue = 0; for (String parameter : parameters) { query.setParameter(parameter, values[currentValue]); currentValue++; } List<?> objectList = null; try { objectList = query.getResultList(); } catch (NoResultException e) { objectList = new ArrayList<>(); } catch (Exception e) { throw e; } return objectList; } public Object getObjectByParameter(String[] parameters, Object[] values, String namedQuery) throws Exception { if (parameters.length != values.length) { throw new Exception( "A quantidade de parâmetros informados é diferente da quantidade de valores"); } Query query = entityManager.createNamedQuery(namedQuery); int currentValue = 0; for (String parameter : parameters) { query.setParameter(parameter, values[currentValue]); currentValue++; } Object object = null; try { object = query.getSingleResult(); } catch (Exception e) { throw e; } return object; } }
Java
package com.anjho.utils; public class Security { /** * @param String password * @return String MD5password */ public static String getMD5(String password) { try { java.security.MessageDigest md = java.security.MessageDigest .getInstance("MD5"); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } password = hexString.toString(); } catch (Exception e) { e.printStackTrace(); } return password; } }
Java
package com.anjho.utils; public class Constants { public static final String LOGGED_USER = "logged_user"; public static final String INDEX = "/index?faces-redirect=true"; public static final String LOGIN_PAGE = "/pages/login.jsf?faces-redirect=true"; }
Java
package com.anjian.taobao; import java.util.List; import java.util.logging.Logger; import com.anjian.Constants; import com.taobao.api.ApiException; import com.taobao.api.DefaultTaobaoClient; import com.taobao.api.TaobaoClient; import com.taobao.api.domain.ArticleUserSubscribe; import com.taobao.api.request.ItemGetRequest; import com.taobao.api.request.ItemUpdateListingRequest; import com.taobao.api.request.ItemUpdateRequest; import com.taobao.api.request.ItemsInventoryGetRequest; import com.taobao.api.request.ItemsOnsaleGetRequest; import com.taobao.api.request.SellercatsListGetRequest; import com.taobao.api.request.UserGetRequest; import com.taobao.api.request.VasSubscribeGetRequest; import com.taobao.api.response.ItemGetResponse; import com.taobao.api.response.ItemUpdateListingResponse; import com.taobao.api.response.ItemUpdateResponse; import com.taobao.api.response.ItemsInventoryGetResponse; import com.taobao.api.response.ItemsOnsaleGetResponse; import com.taobao.api.response.SellercatsListGetResponse; import com.taobao.api.response.UserGetResponse; import com.taobao.api.response.VasSubscribeGetResponse; public class TaobaoProxy implements Constants { static Logger _log = Logger.getLogger(TaobaoProxy.class.getName()); public static final String INVALID_PIC_PATH = "isv.invalid-parameter:picPath"; private static String _authKey; private static boolean _test = false; public static boolean isTest() { return _test; } private static String getApiUrl() { if (!isTest()) { return "http://gw.api.taobao.com/router/rest"; } else { return SANDBOX_API_URL; } } private static String getAppKey() { return APP_KEY; } private static String getAppSecret() { if (!isTest()) { return SECRET; } else { return SANDBOX_SERCET; } } private static TaobaoClient createClient() { return new DefaultTaobaoClient(getApiUrl(), getAppKey(), getAppSecret()); } public static ItemGetResponse getItem(String session, long numIid) throws ApiException { ItemGetRequest req = new ItemGetRequest(); req.setFields("num_iid,title,pic_url,price"); req.setNumIid(numIid); return createClient().execute(req, session); } public static ItemGetResponse getItem(long numIid) throws ApiException { ItemGetRequest req = new ItemGetRequest(); req.setFields("num_iid"); req.setNumIid(numIid); return createClient().execute(req); } public static ItemsOnsaleGetResponse getOnSales(String session, long pageNumber, long pageSize, String sellerCids, String keyWord) throws ApiException { TaobaoClient client = createClient(); ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest(); req.setFields("num_iid,title,pic_url,price,cid"); if (sellerCids != null) { req.setSellerCids(sellerCids); } if (keyWord != null) { req.setQ(keyWord); } //req.setOrderBy("list_time:desc"); req.setPageNo(pageNumber); req.setPageSize(pageSize); return client.execute(req, session); } public static ItemsInventoryGetResponse getInventory(String sessionKey, long pageNumber, long pageSize, String banner, String sellerCids, String keyWord) throws ApiException { TaobaoClient client = createClient(); ItemsInventoryGetRequest req = new ItemsInventoryGetRequest(); req.setFields("num_iid,title,pic_url,price,cid"); if (sellerCids != null) { req.setSellerCids(sellerCids); } if (keyWord != null) { req.setQ(keyWord); } if (banner != null) { req.setBanner(banner); } //req.setOrderBy("list_time:desc"); req.setPageNo(pageNumber);//default 1 req.setPageSize(pageSize);// default 200 ItemsInventoryGetResponse rsp = client.execute(req, sessionKey); return rsp; } public static ItemUpdateResponse updateItem(String sessionKey, long numIid) throws ApiException { ItemUpdateRequest req = new ItemUpdateRequest(); req.setNumIid(numIid); _log.info("aaaaaaaaaaaaaaaaa"); ItemUpdateResponse rsp = createClient().execute(req, sessionKey); _log.info("bbbbbbbbbbbbbbbbb"); return rsp; } public static SellercatsListGetResponse getSellerCategories(String nick) throws ApiException { SellercatsListGetRequest req = new SellercatsListGetRequest(); req.setNick(nick); SellercatsListGetResponse rsp = createClient().execute(req); return rsp; } public static String updateListing(long numIid, long num, String sessionKey) throws ApiException { TaobaoClient client = new DefaultTaobaoClient(getApiUrl(), getAppKey(), getAppSecret()); ItemUpdateListingRequest req = new ItemUpdateListingRequest(); req.setNumIid(numIid); req.setNum(num); ItemUpdateListingResponse rsp = client.execute(req, sessionKey); return rsp.getBody(); } public static void setAuthKey(String authKey) { _authKey = authKey; } public static String getAuthKey() { return _authKey; } public static String getUserInfo(String nick) throws ApiException { TaobaoClient client = new DefaultTaobaoClient(getApiUrl(), getAppKey(), getAppSecret()); UserGetRequest req = new UserGetRequest(); req.setNick(nick); req.setFields("alipay_account"); UserGetResponse rsp = client.execute(req); return rsp.getBody(); } public static List<ArticleUserSubscribe> getSubscription(String nick, String articleCode) throws ApiException { TaobaoClient client = new DefaultTaobaoClient(getApiUrl(), getAppKey(), getAppSecret()); VasSubscribeGetRequest req = new VasSubscribeGetRequest(); req.setNick(nick); req.setArticleCode(articleCode); VasSubscribeGetResponse rsp = client.execute(req); return rsp.getArticleUserSubscribes(); } }
Java
package com.anjian; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; public class DBUtils { static Logger _logger = Logger.getLogger(DBUtils.class.getName()); public static final String LOCAL_DS_NAME = "jdbc/tuqianyi"; public static Connection getConnection() throws NamingException, SQLException { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); DataSource ds = (DataSource) envContext.lookup(LOCAL_DS_NAME); return ds.getConnection(); } public static DataSource getDataSource(String dsName) throws NamingException, SQLException { if(dsName == null) { dsName = LOCAL_DS_NAME; } Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); return (DataSource) envContext.lookup(dsName); } public static void close(Connection conn, Statement statement, ResultSet rs) { try { if(rs != null) { rs.close(); } if(statement != null) { statement.close(); } if(conn != null) { conn.close(); } } catch(SQLException e) { _logger.log(Level.SEVERE, "error", e); } } public static void rollback(Connection conn) { try { if(conn != null) { conn.rollback(); } } catch(SQLException ex) { _logger.log(Level.SEVERE, "error", ex); } } }
Java
package com.anjian.utils; import java.util.List; public class PagingResult<T> { private List<T> items; private long total; private PagingOption option; public void setItems(List<T> items) { this.items = items; } public List<T> getItems() { return items; } public void setOption(PagingOption option) { this.option = option; } public PagingOption getOption() { return option; } public void setTotal(long total) { this.total = total; } public long getTotal() { return total; } /** * * @return page index, begins from 0 */ public int getCurrentPage() { return option.getCurrentPage(); } public int getTotalPages() { // return (int)(total / option.getLimit() + 1); return getPageCount(total, option.getLimit()); } public static int getPageCount(long total, int pageSize) { return (int)(total / pageSize + (total % pageSize == 0 ? 0 : 1)); } }
Java
package com.anjian.utils; public class PagingOption { private int offset; private int limit = 50; public void setOffset(int offset) { this.offset = offset; } public int getOffset() { return offset; } public void setLimit(int limit) { this.limit = limit; } public int getLimit() { return limit; } public int getCurrentPage() { return getOffset() / getLimit(); } public String toString() { return "offset: " + offset + ", limit: " + limit; } }
Java
package com.anjian; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.naming.NamingException; import com.anjian.model.User; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemUpdateResponse; public class Dao { static Logger _logger = Logger.getLogger(Dao.class.getName()); public static final Dao INSTANCE = new Dao(); private Dao() { } public int clearErrorItems(String nick) throws Exception { Connection conn = null; PreparedStatement statement = null; try { conn = DBUtils.getConnection(); String sql = "delete from error_item_t where nick_c=?"; statement = conn.prepareStatement(sql); statement.setString(1, nick); return statement.executeUpdate(); } finally { DBUtils.close(conn, statement, null); } } public void addErrorItem(ItemUpdateResponse error) throws Exception { Connection conn = null; PreparedStatement statement = null; try { conn = DBUtils.getConnection(); String sql = "insert into error_item_t values(?,?,?,?,?)"; statement = conn.prepareStatement(sql); statement.setLong(1, error.getItem().getNumIid()); statement.setString(2, error.getItem().getNick()); statement.setString(3, error.getItem().getTitle()); statement.setString(4, error.getSubCode()); statement.setString(5, error.getSubMsg()); statement.executeUpdate(); } finally { DBUtils.close(conn, statement, null); } } public List<ItemUpdateResponse> getErrorItems(String nick) throws Exception { Connection conn = null; PreparedStatement statement = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); String sql = "select * from error_item_t where nick_c=?"; statement = conn.prepareStatement(sql); statement.setString(1, nick); rs = statement.executeQuery(); List<ItemUpdateResponse> items = new ArrayList<ItemUpdateResponse>(); while (rs.next()) { Item item = new Item(); item.setNumIid(rs.getLong("num_iid_c")); item.setTitle(rs.getString("title_c")); ItemUpdateResponse response = new ItemUpdateResponse(); response.setItem(item); items.add(response); } return items; } finally { DBUtils.close(conn, statement, rs); } } public void updateUser(long uid, String nick, String userAgent, String session) throws NamingException, SQLException { Connection conn = null; PreparedStatement statement = null; try { conn = DBUtils.getConnection(); String sql = "update user_t set session_c=?, last_login_c=?, user_agent_c=? where user_id_c=?"; statement = conn.prepareStatement(sql); statement.setString(1, session); statement.setTimestamp(2, new Timestamp(System.currentTimeMillis())); statement.setString(3, userAgent); statement.setLong(4, uid); int result = statement.executeUpdate(); if (result == 0) { sql = "insert into user_t(user_id_c, nick_c, session_c, last_login_c, user_agent_c=?) values(?,?,?,?,?)"; statement = conn.prepareStatement(sql); statement.setLong(1, uid); statement.setString(2, nick); statement.setString(3, session); statement.setTimestamp(4, new Timestamp(System.currentTimeMillis())); statement.setString(5, userAgent); } statement.executeUpdate(); } finally { DBUtils.close(conn, statement, null); } } public List<User> getUsers() throws NamingException, SQLException { Connection conn = null; PreparedStatement statement = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); String sql = "select * from user_t order by last_login_c limit 50 offset 0"; statement = conn.prepareStatement(sql); rs = statement.executeQuery(); List<User> users = new ArrayList<User>(); while (rs.next()) { User user = new User(); user.setNick(rs.getString("nick_c")); user.setLastLogin(rs.getDate("last_login_c")); user.setUserAgent(rs.getString("user_agent_c")); users.add(user); } return users; } finally { DBUtils.close(conn, statement, rs); } } }
Java
package com.anjian; public interface Constants { String APP_KEY = "12321428"; String SECRET = "d76dfdfdba8f979233cc356df6b25164"; String SANDBOX_SERCET = "sandbox8ca8b480ea0c0d0721aaaeb84"; String SANDBOX_API_URL = "http://gw.api.tbsandbox.com/router/rest"; String SANDBOX_SESSION_URL = "http://container.api.tbsandbox.com/container"; String ENTRY = "http://fuwu.taobao.com/using/app_ins_processor.htm?service_id=6371";//"http://container.open.taobao.com/container?appkey=" + APP_KEY; long ADMIN_ID = 62112477; String ERROR_CODE_SESSION_NOT_EXISTS = "27"; String SESSION_TIMEOUT = "SESSION_TIMEOUT"; String OUT_OF_ALLOWED_ITEMS = "OUT_OF_ALLOWED_ITEMS"; String API_EXCEPTION = "API_EXCEPTION"; String TAOBAO_PIC_TAIL_80 = "_80x80.jpg"; String TAOBAO_PIC_TAIL_310 = "_310x310.jpg"; String TOP_SESSION = "TOP_SESSION"; String USER_ID = "USER_ID"; String USER = "USER"; String VERSION = "VERSION"; String TOTAL = "TOTAL"; String PROCESSED = "PROCESSED"; String LAST_SCAN = "lastScan"; String PROGRESS = "progress"; int MAX_ERROR = 30; int PAGE_SIZE = 200; String SCANING_SCOPE = "scaning.scope"; String SCANING_PAGE = "scaning.page"; String SCANING_ITEMS = "scaning.items"; String SCANING_ITEM = "scaning.item"; String TIME_SPENT = "time_spent"; String ERROR_ITEMS = "error_items"; String STATUS = "status"; String ONSALE = "出售中"; String INVENTORY = "库存中"; String DONE = "done"; }
Java
package com.anjian.action; import java.util.List; import com.anjian.taobao.TaobaoProxy; import com.anjian.utils.PagingOption; import com.anjian.utils.PagingResult; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemsInventoryGetResponse; import com.taobao.api.response.ItemsOnsaleGetResponse; public class ItemsAction extends ActionBase { public static final int SCOPE_ONSALE = 0; public static final int SCOPE_INVENTORY = 1; private int scope = SCOPE_ONSALE; private PagingOption option; private PagingResult<Item> pagingItems; public String execute() { String sessionId = getSessionId(); try { if (scope == SCOPE_ONSALE) { getOnsaleItems(sessionId); } else if (scope == SCOPE_INVENTORY) { getInventory(sessionId); } } catch (Exception e) { error(e); } return SUCCESS; } private long getOnsaleItems(String sessionId) throws Exception { ItemsOnsaleGetResponse onsales = TaobaoProxy.getOnSales(sessionId, option.getCurrentPage() + 1, option.getLimit(), null, null); if (onsales.isSuccess()) { long total = onsales.getTotalResults(); _log.info("onsale.total: " + total); List<Item> items = onsales.getItems(); pagingItems = new PagingResult<Item>(); pagingItems.setOption(option); pagingItems.setItems(items); pagingItems.setTotal(total); return total; } else { error(onsales); // if ("accesscontrol.limited-by-app-access-count".equals(onsales.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } private long getInventory(String sessionId) throws Exception { ItemsInventoryGetResponse inventory = TaobaoProxy.getInventory(sessionId, option.getCurrentPage() + 1, option.getLimit(), null, null, null); if (inventory.isSuccess()) { long total = inventory.getTotalResults(); _log.info("inventory.total: " + total); List<Item> items = inventory.getItems(); pagingItems = new PagingResult<Item>(); pagingItems.setOption(option); pagingItems.setItems(items); pagingItems.setTotal(total); return total; } else { error(inventory); // if ("accesscontrol.limited-by-app-access-count".equals(inventory.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } public void setOption(PagingOption option) { this.option = option; } public PagingOption getOption() { return option; } public void setScope(int scope) { this.scope = scope; } public int getScope() { return scope; } public void setPagingItems(PagingResult<Item> pagingItems) { this.pagingItems = pagingItems; } public PagingResult<Item> getPagingItems() { return pagingItems; } }
Java
package com.anjian.action; import java.util.List; import java.util.Map; import com.anjian.taobao.TaobaoProxy; import com.opensymphony.xwork2.ActionContext; import com.taobao.api.ApiException; import com.taobao.api.domain.SellerCat; import com.taobao.api.response.SellercatsListGetResponse; public class InitAction extends ActionBase{ private List<SellerCat> categories; public String execute() throws Exception { retriveCategories(); return SUCCESS; } private void retriveCategories() throws ApiException { Map<String, Object> session = ActionContext.getContext().getSession(); String nick = (String)session.get(USER); SellercatsListGetResponse catRsp = TaobaoProxy.getSellerCategories(nick); setCategories(catRsp.getSellerCats()); } public void setCategories(List<SellerCat> categories) { this.categories = categories; } public List<SellerCat> getCategories() { return categories; } }
Java
package com.anjian.action; import com.opensymphony.xwork2.ActionContext; public class StatusAction extends ActionBase{ public String execute() throws Exception { Boolean b = (Boolean)ActionContext.getContext().getSession().get(DONE); if (b != null && b) { return "done"; } return "scanning"; } }
Java
package com.anjian.action; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.anjian.taobao.TaobaoProxy; import com.anjian.utils.PagingResult; import com.opensymphony.xwork2.ActionContext; import com.taobao.api.ApiException; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemUpdateResponse; import com.taobao.api.response.ItemsInventoryGetResponse; import com.taobao.api.response.ItemsOnsaleGetResponse; public class DetectPageAction extends ActionBase { static Logger _log = Logger.getLogger(DetectAction.class.getName()); public static final int SCOPE_ONSALE = 0; public static final int SCOPE_INVENTORY = 1; private int scope = SCOPE_ONSALE; private int pageNo; private long total = -1; public String execute() throws Exception { Map<String, Object> session = ActionContext.getContext().getSession(); String sessionId = getSessionId(); if (scope == SCOPE_ONSALE) { session.put(STATUS, ONSALE); setTotal(detectSales(pageNo, sessionId, session)); } else if (scope == SCOPE_INVENTORY) { session.put(STATUS, INVENTORY); setTotal(detectInventory(1, sessionId, session)); } return SUCCESS; } private long detectSales(int pageNo, String sessionId, Map<String, Object> session) throws Exception { ItemsOnsaleGetResponse onsales = TaobaoProxy.getOnSales(sessionId, pageNo, PAGE_SIZE, null, null); if (onsales.isSuccess()) { long total = onsales.getTotalResults(); _log.info("onsale.total: " + total); session.put(TOTAL, total); List<Item> items = onsales.getItems(); if (items != null) { detectItems(items, sessionId); } return total; } else { error(onsales); // if ("accesscontrol.limited-by-app-access-count".equals(onsales.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } private long detectInventory(int pageNo, String sessionId, Map<String, Object> session) throws Exception { ItemsInventoryGetResponse inventory = TaobaoProxy.getInventory(sessionId, pageNo, PAGE_SIZE, null, null, null); if (inventory.isSuccess()) { long total = inventory.getTotalResults(); _log.info("inventory.total: " + total); session.put(TOTAL, total); List<Item> items = inventory.getItems(); if (items != null) { detectItems(items, sessionId); } return total; } else { error(inventory); // if ("accesscontrol.limited-by-app-access-count".equals(inventory.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } private void detectItems(List<Item> items, String sessionId) { Map<Long,Long> notRepeatCids = new HashMap<Long,Long>(); List<ItemUpdateResponse> errorItems = getErrorItems(); for (Item item : items) { _log.info("checking: " + item.getNumIid() + " - " + item.getTitle()); if (!notRepeatCids.containsKey(item.getCid())) { try { ItemUpdateResponse rsp = TaobaoProxy.updateItem(sessionId, item.getNumIid()); if (!rsp.isSuccess()) { _log.info("code: " + rsp.getErrorCode() + " msg: " + rsp.getMsg() + " subCode: " + rsp.getSubCode() + " subMsg: " + rsp.getSubMsg()); String subCode = rsp.getSubCode(); if (isRepeatError(subCode)) { _log.info("ignore cid: " + item.getCid()); notRepeatCids.put(item.getCid(), item.getCid()); } if (subCode != null && !isSystemError(subCode)) { rsp.setItem(item); errorItems.add(rsp); } if (errorItems.size() >= MAX_ERROR) { return; } } } catch (ApiException e) { _log.log(Level.SEVERE, "", e); } catch (Exception e) { _log.log(Level.SEVERE, "", e); } } increaceProgress(); } } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageNo() { return pageNo; } public void setScope(int scope) { this.scope = scope; } public int getScope() { return scope; } public void setTotal(long total) { this.total = total; } public long getTotal() { return total; } public int getPages() { return PagingResult.getPageCount(total, PAGE_SIZE); } }
Java
package com.anjian.action; import java.util.Date; import java.util.Map; import java.util.logging.Logger; import org.apache.commons.lang.time.DateUtils; import com.opensymphony.xwork2.ActionContext; public class CheckIntervalAction extends ActionBase { static Logger _log = Logger.getLogger(CheckIntervalAction.class.getName()); private int interval = 5; //minutes private boolean limit; public String execute() throws Exception { if (isAdmin()) { limit = false; return SUCCESS; } Map<String, Object> session = ActionContext.getContext().getSession(); Date lastScan = (Date)session.get(LAST_SCAN); if (lastScan != null) { Long l = lastScan.getTime(); if (System.currentTimeMillis() - l < DateUtils.MILLIS_PER_MINUTE * interval) { limit = true; return SUCCESS; } } limit = false; return SUCCESS; } public boolean isLimit() { return limit; } public int getInterval() { return interval; } }
Java
package com.anjian.action; import java.util.logging.Level; import com.anjian.taobao.TaobaoProxy; import com.taobao.api.ApiException; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemUpdateResponse; public class DetectItemAction extends ActionBase { private int index; public String execute() { Item item = getItem(index); String sessionId = getSessionId(); detectItem(item.getNumIid(), sessionId); return SUCCESS; } private void detectItem(long numIid, String sessionId) { // if (!notRepeatCids.containsKey(item.getCid())) // { try { ItemUpdateResponse rsp = TaobaoProxy.updateItem(sessionId, numIid); if (!rsp.isSuccess()) { _log.info("code: " + rsp.getErrorCode() + " msg: " + rsp.getMsg() + " subCode: " + rsp.getSubCode() + " subMsg: " + rsp.getSubMsg()); String subCode = rsp.getSubCode(); // if (isRepeatError(subCode)) // { // _log.info("ignore cid: " + item.getCid()); // notRepeatCids.put(item.getCid(), item.getCid()); // } // if (subCode != null && !isSystemError(subCode)) // { // rsp.setItem(item); // errorItems.add(rsp); // } // if (errorItems.size() >= MAX_ERROR) // { // return; // } } else { Item item = rsp.getItem(); _log.info("checked: " + item.getNumIid() + " - " + item.getTitle()); } } catch (ApiException e) { _log.log(Level.SEVERE, "", e); } catch (Exception e) { _log.log(Level.SEVERE, "", e); } // } increaceProgress(); } public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } }
Java
package com.anjian.action; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.anjian.Constants; import com.anjian.utils.PagingResult; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.taobao.api.TaobaoResponse; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemUpdateResponse; public class ActionBase extends ActionSupport implements Constants{ static Logger _log = Logger.getLogger(ActionBase.class.getName()); protected String getUser() { return (String)ActionContext.getContext().getSession().get(USER); } protected long getUserId() { Map<String, Object> session = ActionContext.getContext().getSession(); String userId = (String)session.get(USER_ID); if (userId != null) { return Long.parseLong(userId); } return -1; } public boolean isAdmin() { return getUserId() == ADMIN_ID; } protected String getSessionId() { Map<String, Object> session = ActionContext.getContext().getSession(); return (String)session.get(TOP_SESSION); } protected void resetProgress() { Map<String, Object> session = ActionContext.getContext().getSession(); _log.info("sssssssssss: " + session); session.put(PROGRESS, 0); } protected void increaceProgress() { Map<String, Object> session = ActionContext.getContext().getSession(); Integer progress = (Integer)session.get(PROGRESS); _log.info(getUser() + "progress: " + progress); if (progress == null) { progress = 0; } session.put(PROGRESS, ++progress); } protected static void error(Throwable e) { _log.log(Level.SEVERE, "", e); } protected void error(TaobaoResponse rsp) { _log.info(rsp.getErrorCode() + " - " + rsp.getMsg() + " - " + rsp.getSubCode() + " - " + rsp.getSubMsg()); } protected boolean isRepeatError(String subCode) { return "isv.item-update-service-error:IC_PERMISSION_FOR_TBCP_ONLY".equals(subCode) || "isv.item-update-service-error:QUANTITY_ITEM_CAT_TOO_LARGE".equals(subCode) || "isv.item-update-service-error:ERROR_SHOP_CATEGORY_HAS_SUB_CATEGORIES".equals(subCode) || "isv.item-update-service-error:IC_CHECKSTEP_SPU_NOT_EXIST".equals(subCode) || "isv.item-update-service-error:IC_APPLICATION_PERMISSION_INVALID".equals(subCode) || "isv.item-update-service-error:IC_STUFF_STATUS_NEW_LIMITED_WITH_NOPREPAY".equals(subCode); } protected boolean isSystemError(String subCode) { return (subCode != null && subCode.startsWith("isp.")) || (subCode != null && subCode.contains("isv.item-update-service-error:GENERIC_FAILURE")) || "accesscontrol.limited-by-app-access-count".equals(subCode) || "isv.item-is-delete:invalid-numIid-or-iid".equals(subCode) || "isv.item-get-service-error:ITEM_NOT_FOUND".equals(subCode) || "isv.item-update-service-error:ITEM_SALE_HAS_BID".equals(subCode); } protected List<Item> getItems() { PagingResult<Item> pagingItems = (PagingResult<Item>) ActionContext.getContext().getSession().get(SCANING_ITEMS); if (pagingItems == null) { return null; } return pagingItems.getItems(); } protected Item getItem(int index) { List<Item> items = getItems(); if (items != null) { return items.get(index); } return null; } protected List<ItemUpdateResponse> getErrorItems() { Map<String, Object> session = ActionContext.getContext().getSession(); List<ItemUpdateResponse> errorItems = (List<ItemUpdateResponse>)session.get(ERROR_ITEMS); if (errorItems == null) { errorItems = new ArrayList<ItemUpdateResponse>(); session.put(ERROR_ITEMS, errorItems); } return errorItems; } }
Java
package com.anjian.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import com.anjian.model.Scope; import com.anjian.taobao.TaobaoProxy; import com.anjian.utils.PagingResult; import com.opensymphony.xwork2.ActionContext; import com.taobao.api.ApiException; import com.taobao.api.domain.Item; import com.taobao.api.response.ItemUpdateResponse; import com.taobao.api.response.ItemsInventoryGetResponse; import com.taobao.api.response.ItemsOnsaleGetResponse; public class DetectAction extends ActionBase { static Logger _log = Logger.getLogger(DetectAction.class.getName()); private static final String TOTAL = "total"; private Scope scope; private List<ItemUpdateResponse> errorItems; private Map<String, Object> session; private long spend; public String execute() throws Exception { session = ActionContext.getContext().getSession(); session.remove(DONE); new Thread() { public void run() { try { detect(); } catch (Exception e) { error(e); } } }.start(); _log.info("thread starteddddddddddddddddddddddd"); return SUCCESS; } private String detect() throws Exception { long t0 = System.currentTimeMillis(); errorItems = new ArrayList<ItemUpdateResponse>(); String sessionId = (String)session.get(TOP_SESSION); _log.info("scope: " + scope); if (!StringUtils.isEmpty(scope.getSaleStatus()) && scope.getSaleStatus().contains("onsale")) { resetProgress(); session.put(STATUS, ONSALE); long total = detectSales(1, sessionId, session); int pages = PagingResult.getPageCount(total, PAGE_SIZE); _log.info(getUser() + " - pages: " + pages + ", total: " + total); if (total != -1) { for (int i = 2; i <= pages; i++) { if (errorItems.size() >= MAX_ERROR) { break; } _log.info(getUser() + "...scanning onsales on page " + i); detectSales(i, sessionId, session); } } } if (!StringUtils.isEmpty(scope.getSaleStatus()) && scope.getSaleStatus().contains("inventory")) { resetProgress(); session.put(STATUS, INVENTORY); long total = detectInventory(1, sessionId, session); int pages = PagingResult.getPageCount(total, PAGE_SIZE); _log.info(getUser() + " - pages: " + pages + ", total: " + total); if (total != -1) { for (int i = 2; i <= pages; i++) { if (errorItems.size() >= MAX_ERROR) { break; } _log.info(getUser() + "...scanning inventory on page " + i); detectInventory(i, sessionId, session); } } } spend = (System.currentTimeMillis() - t0) / 1000; if (errorItems != null) { _log.info("complete scanning and found error items: " + errorItems.size()); } session.put(ERROR_ITEMS, errorItems); session.put(TIME_SPENT, spend); session.put(LAST_SCAN, new Date()); session.put(DONE, true); return SUCCESS; } private long detectSales(int pageNo, String sessionId, Map<String, Object> session) throws Exception { ItemsOnsaleGetResponse onsales = TaobaoProxy.getOnSales(sessionId, pageNo, PAGE_SIZE, scope.getSellerCids(), null); if (onsales.isSuccess()) { long total = onsales.getTotalResults(); _log.info("onsale.total: " + total); session.put(TOTAL, total); List<Item> items = onsales.getItems(); if (items != null) { detectItems(items, sessionId); } return total; } else { error(onsales); // if ("accesscontrol.limited-by-app-access-count".equals(onsales.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } private long detectInventory(int pageNo, String sessionId, Map<String, Object> session) throws Exception { ItemsInventoryGetResponse inventory = TaobaoProxy.getInventory(sessionId, pageNo, PAGE_SIZE, null, scope.getSellerCids(), null); if (inventory.isSuccess()) { long total = inventory.getTotalResults(); _log.info("inventory.total: " + total); session.put(TOTAL, total); List<Item> items = inventory.getItems(); if (items != null) { detectItems(items, sessionId); } return total; } else { error(inventory); // if ("accesscontrol.limited-by-app-access-count".equals(inventory.getSubCode())) // { // throw new Exception("out-of-band"); // } } return -1L; } private void detectItems(List<Item> items, String sessionId) { Map<Long,Long> notRepeatCids = new HashMap<Long,Long>(); for (Item item : items) { _log.info("checking: " + item.getNumIid()); if (!notRepeatCids.containsKey(item.getCid())) { _log.info("11111"); try { ItemUpdateResponse rsp = TaobaoProxy.updateItem(sessionId, item.getNumIid()); _log.info("22222"); if (!rsp.isSuccess()) { _log.info("code: " + rsp.getErrorCode() + " msg: " + rsp.getMsg() + " subCode: " + rsp.getSubCode() + " subMsg: " + rsp.getSubMsg()); String subCode = rsp.getSubCode(); if (isRepeatError(subCode)) { _log.info("ignore cid: " + item.getCid()); notRepeatCids.put(item.getCid(), item.getCid()); } if (subCode != null && !isSystemError(subCode)) { rsp.setItem(item); errorItems.add(rsp); } if (errorItems.size() >= MAX_ERROR) { return; } } } catch (ApiException e) { _log.log(Level.SEVERE, "", e); } catch (Exception e) { _log.log(Level.SEVERE, "", e); } } increaceProgress(); } } public List<ItemUpdateResponse> getErrorItems() { if (errorItems != null) { _log.info("size: " + errorItems.size()); } return errorItems; } public long getSpend() { return spend; } protected void resetProgress() { _log.info("sssssssssss: " + session); session.put(PROGRESS, 0); } protected void increaceProgress() { Integer progress = (Integer)session.get(PROGRESS); _log.info(getUser() + "progress: " + progress); if (progress == null) { progress = 0; } session.put(PROGRESS, ++progress); } protected String getUser() { return (String)session.get(USER); } public Scope getScope() { return scope; } public void setScope(Scope scope) { this.scope = scope; } }
Java
package com.anjian; import java.io.IOException; import java.net.URLEncoder; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.anjian.taobao.TaobaoProxy; import com.taobao.api.internal.util.TaobaoUtils; public class SessionFilter implements Filter, Constants{ static Logger _log = Logger.getLogger(SessionFilter.class.getName()); public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } private boolean verify(ServletRequest req) throws IOException, ServletException { //req.setCharacterEncoding("GBK"); String queryString = ((HttpServletRequest)req).getQueryString(); _log.info(queryString); HttpSession session = ((HttpServletRequest)req).getSession(false); if (session != null && session.getAttribute(USER) != null) { return true; } String topParams = req.getParameter("top_parameters"); String topSession = req.getParameter("top_session"); String topSign = req.getParameter("top_sign"); String appKey = req.getParameter("top_appkey"); if (topParams == null || topSession == null || topSign==null || appKey == null) { return false; } boolean verifiedTopParameters = TaobaoUtils.verifyTopResponse(topParams, topSession, topSign, appKey, TaobaoProxy.SECRET); _log.info("top parameters verified: " + verifiedTopParameters); if (TaobaoProxy.isTest() || (verifiedTopParameters)) { String browser = ((HttpServletRequest)req).getHeader("user-agent"); _log.info("browser: " + browser); Map<String, String> topMap = TaobaoUtils.decodeTopParams(URLEncoder.encode(topParams, "GBK")); _log.warning("parsed top params: " + topMap); String uid = topMap.get("visitor_id"); String nick = topMap.get("visitor_nick"); String userId = topMap.get("visitor_id"); session = ((HttpServletRequest)req).getSession(true); session.setAttribute(TOP_SESSION, topSession); session.setAttribute(USER_ID, userId); session.setAttribute(USER, nick); session.setAttribute("query", queryString); session.setAttribute("browser", browser); session.setAttribute("admin", (Long.parseLong(userId) == ADMIN_ID)); return true; } else { return false; } } public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { try { if (verify(req)) { chain.doFilter(req, rsp); } else { rsp.setContentType("text/html;charset=UTF-8"); rsp.getWriter().println("未授权。"); } } catch (IOException e) { _log.log(Level.SEVERE, "", e); throw e; } } public void destroy() { // TODO Auto-generated method stub } }
Java
package com.anjian.model; import java.util.Date; public class User{ private String nick; private Date lastLogin; private String userAgent; public void setNick(String nick) { this.nick = nick; } public String getNick() { return nick; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public Date getLastLogin() { return lastLogin; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public String getUserAgent() { return userAgent; } }
Java
package com.anjian.model; import java.io.Serializable; public class Scope implements Serializable{ private String saleStatus; private String sellerCids; public void setSaleStatus(String saleStatus) { this.saleStatus = saleStatus; } public String getSaleStatus() { return saleStatus; } public void setSellerCids(String sellerCids) { this.sellerCids = sellerCids; } public String getSellerCids() { return sellerCids; } }
Java
package com.anjian.model; public class Progress { private long total; private long progress; private String status; public void setTotal(long total) { this.total = total; } public long getTotal() { return total; } public void setProgress(long progress) { this.progress = progress; } public long getProgress() { return progress; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } }
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.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class LvSurfaceBase extends SurfaceView implements SurfaceHolder.Callback, Runnable { private static final String TAG = "LvSurfaceBase"; private SurfaceHolder mHolder; private int mFrameWidth; private int mFrameHeight; private LvSurfaceHelper mHelper = null; private Paint mPaintBlack, mPaintRed, mPaintGreen, mPaintBlue, mPaintYellow; private Thread mDrawThread; private Context mContext; private boolean mThreadRun; private final Object mSyncRoot = new Object(); public LvSurfaceBase(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mHolder = getHolder(); mHolder.addCallback(this); mPaintBlack = new Paint(); mPaintBlack.setStyle(Paint.Style.FILL); mPaintBlack.setColor(Color.BLACK); mPaintYellow = new Paint(); mPaintYellow.setStyle(Paint.Style.FILL); mPaintYellow.setColor(Color.YELLOW); mPaintRed = new Paint(); mPaintRed.setStyle(Paint.Style.FILL); mPaintRed.setColor(Color.RED); mPaintGreen = new Paint(); mPaintGreen.setStyle(Paint.Style.FILL); mPaintGreen.setColor(Color.GREEN); mPaintBlue = new Paint(); mPaintBlue.setStyle(Paint.Style.FILL); mPaintBlue.setColor(Color.BLUE); // mPaint = new Paint(); // mPaint.setColor(Color.GREEN); // mPaint.setAntiAlias(true); // mPaint.setStyle(Style.STROKE); // 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; } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surface created"); mDrawThread = new Thread(this); mDrawThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface destroyed"); mDrawThread.interrupt(); mThreadRun = false; } public void processLvObject(LvSurfaceHelper helper) { synchronized (mSyncRoot) { mHelper = helper; mSyncRoot.notify(); } } long mTime = 0; public void setDefaultImage() { synchronized (mSyncRoot) { mHelper = null; // mLvo = null; mSyncRoot.notify(); } } private void doDraw(Canvas canvas) { long time = System.currentTimeMillis(); double fps = 0; if (mTime != 0) fps = 1000 / (time - mTime); mTime = time; Bitmap mBitmap = null; if (canvas != null) { if (mHelper == null || mHelper.mLvo == null) { canvas.drawColor(Color.BLACK); return; } mBitmap = BitmapFactory.decodeByteArray(mHelper.mLvo.data, mHelper.mLvo.imgPos, mHelper.mLvo.imgLen);// processLvImage(mLvo); if (mBitmap != null) { canvas.drawBitmap(mBitmap, new Rect(0, 0, mHelper.mLvo.jpegImageSize.horizontal, mHelper.mLvo.jpegImageSize.vertical), new RectF(0, 0, mFrameWidth, mFrameHeight), null); mPaintGreen.setStyle(Paint.Style.STROKE); mPaintGreen.clearShadowLayer(); mPaintYellow.setStyle(Paint.Style.STROKE); mPaintYellow.clearShadowLayer(); mPaintRed.setStyle(Paint.Style.STROKE); mPaintRed.clearShadowLayer(); // draw focus rect canvas.drawRect(mHelper.mLvo.afRects[0], mPaintGreen); // draw rects for face detection if (mHelper.mLvo.faceDetectionPersonNo > 0) { for(int i = 1; i <= mHelper.mLvo.faceDetectionPersonNo; i++){ canvas.drawRect(mHelper.mLvo.afRects[i], mPaintYellow); } } // mPaint.setTextSize(20); // mPaint.setShadowLayer(3, 1, 1, Color.BLACK); // canvas.drawText(String.format("%.1f", fps), 100, 20, mPaint); float fontSize = (mFrameWidth * 32) / 1280; mPaintBlack.setTextSize(fontSize); mPaintGreen.setTextSize(fontSize); mPaintRed.setTextSize(fontSize); mPaintYellow.setTextSize(fontSize); String tmpStr; if ((mHelper.mOsdDisplay & 1) == 1) { //mPaintGreen.setStrokeWidth(1); float thirdx = mFrameWidth / 3; float thirdy = mFrameHeight / 3; if (mHelper.mLvZoom != null && (Integer)mHelper.mLvZoom.getValue() == 0) { canvas.drawLine(thirdx, 0, thirdx, mFrameHeight, mPaintGreen); canvas.drawLine(2 * thirdx, 0, 2 * thirdx, mFrameHeight, mPaintGreen); canvas.drawLine(0, thirdy, mFrameWidth, thirdy, mPaintGreen); canvas.drawLine(0, thirdy * 2, mFrameWidth, thirdy * 2, mPaintGreen); } } mPaintGreen.setShadowLayer(3, 1, 1, Color.BLACK); mPaintRed.setShadowLayer(3, 1, 1, Color.BLACK); mPaintYellow.setShadowLayer(3, 1, 1, Color.BLACK); if ((mHelper.mOsdDisplay & 2) == 2) { //mPaintGreen.setTextSize(20); canvas.drawText(String.format("LV remain %d s", mHelper.mLvo.countDownTime), 20, 25, mPaintGreen); if ((mHelper.mLvo.shutterSpeedUpper / mHelper.mLvo.shutterSpeedLower) >= 1) tmpStr = String.format("f %.1f %.1f \"", (double)mHelper.mLvo.apertureValue / 100, (double)(mHelper.mLvo.shutterSpeedUpper / mHelper.mLvo.shutterSpeedLower)); else tmpStr = String.format("f %.1f %d / %d", (double)mHelper.mLvo.apertureValue / 100, mHelper.mLvo.shutterSpeedUpper, mHelper.mLvo.shutterSpeedLower); if (mHelper.mLvo.hasApertureAndShutter) { float tWidth = mPaintGreen.measureText(tmpStr); canvas.drawText(tmpStr, (mFrameWidth / 2) - (tWidth / 2) , 25, mPaintGreen); } if (mHelper.mLvo.focusDrivingStatus == 1) canvas.drawText("AF", 70, 60, mPaintGreen); // canvas.drawText(String.format("Focus %d / %d", mHelper.mFocusCurrent, mHelper.mFocusMax ), 80, 75, mPaintGreen); // switch(mHelper.mTouchMode){ // case LVFOCUS: // canvas.drawText("Manual focus", 80, 105, mPaintGreen); // canvas.drawText(String.format("Focus step: %d", mMfDriveStep), 50, 370, mPaintGreen); // break; // case LVZOOM: // canvas.drawText("Zoom", 80, 105, mPaintGreen); // break; // } if (mHelper.mLvo.hasRolling) { tmpStr = String.format("Rolling %.2f", mHelper.mLvo.rolling); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 105, mPaintGreen); } if (mHelper.mLvo.hasPitching) { tmpStr = String.format("Pitching %.2f", mHelper.mLvo.pitching); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 135, mPaintGreen); } if (mHelper.mLvo.hasYawing) { tmpStr = String.format("Yawing %.2f", mHelper.mLvo.yawing); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 165, mPaintGreen); } if (mHelper.mLvo.movieRecording) { tmpStr = String.format("REC remaining %d s", mHelper.mLvo.movieRecordingTime / 1000); canvas.drawText(tmpStr, mFrameWidth - mPaintGreen.measureText(tmpStr) - 20, 75, mPaintRed); } mPaintGreen.setStyle(Paint.Style.FILL); mPaintYellow.setStyle(Paint.Style.FILL); mPaintRed.setStyle(Paint.Style.FILL); switch(mHelper.mLvo.focusingJudgementResult){ case 0: canvas.drawCircle(50, 50, 10, mPaintYellow); break; case 1: canvas.drawCircle(50, 50, 10, mPaintRed); break; case 2: canvas.drawCircle(50, 50, 10, mPaintGreen); break; } // focus position drawin // paint.setColor(Color.GREEN); // paint.setStyle(Style.FILL_AND_STROKE); // // float fx = (mFrameWidth * mHelper.mFocusCurrent) / mHelper.mFocusMax; // canvas.drawCircle(fx, mFrameHeight - 20, 10, paint); } if (mHelper.mHistogramEnabled) { Bitmap histBmp = NativeMethods.getInstance().createHistogramBitmap(mBitmap,mHelper.mHistogramSeparate); int hWidth = histBmp.getWidth(); int hHeight = histBmp.getHeight(); if (hWidth > (int)(mFrameWidth / 3)) { //hHeight = (int)(hHeight * (hWidth / (mFrameWidth / 3)) ); hWidth = (int)(mFrameWidth / 3); } if (hHeight > mFrameHeight) { //hWidth = (int)(hWidth * (hHeight / mFrameHeight)); hHeight = mFrameHeight; } canvas.drawBitmap(histBmp, new Rect(0, 0, histBmp.getWidth(), histBmp.getHeight()), new RectF(0, 0, hWidth, hHeight), null); histBmp.recycle(); } mBitmap.recycle(); } else { canvas.drawColor(Color.BLACK); } } } public void run() { mThreadRun = true; Log.d(TAG, "Starting LV image processing thread"); while (mThreadRun) { synchronized (mSyncRoot) { try { mSyncRoot.wait(); } catch (InterruptedException e) { Log.d(TAG, "Draw thread interrupted"); } } try { Canvas canvas = mHolder.lockCanvas(); doDraw(canvas); mHolder.unlockCanvasAndPost(canvas); } catch (Exception e) { Log.e(TAG, "LVSurface draw exception: " + e.getMessage()); } } } }
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 PtpServiceEvent { UsbDeviceFount, UsbDeviceInitialized, UsbDeviceRemoved }
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 PtpPropertyListItem { private String mTitle; private int mImage; private Object mValue; private int mNameId; public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public int getImage() { return mImage; } public void setImage(int image) { this.mImage = image; } public Object getValue(){ return mValue; } public void setValue(Object value){ mValue = value; } public int getNameId(){ return mNameId; } public void setNameId(int value){ mNameId = value; } public PtpPropertyListItem(){ } public PtpPropertyListItem(Object propValue, int propNameId, int propImgId){ mValue = propValue; mNameId = propNameId; mImage = propImgId; } public PtpPropertyListItem(String title) { mTitle = title; } }
Java
package com.dslr.dashboard; import java.io.File; import java.util.LinkedList; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; public class GpsLocationHelper { private final static String TAG = GpsLocationHelper.class.getSimpleName(); private Context mContext = null; private LocationManager mLocationManager; private Location mLastLocation = null; private LinkedList<File> mGpsList; private boolean mIsWaitingForGpsUpdate = false; private int mGpsSampleInterval = 1; public int mGpsSampleCount = 3; private int mGpsUpdateCount = 0; private Thread mGpsThread; private Handler mGpsHandler = null; public void setGpsSampleCount(int value) { mGpsSampleCount = value; } public void setGpsSampleInterval(int value) { mGpsSampleInterval = value; } public GpsLocationHelper(Context context) { mContext = context; mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mGpsList = new LinkedList<File>(); mGpsThread = new Thread() { public void run() { Log.d( TAG,"Creating handler ..." ); Looper.prepare(); mGpsHandler = new Handler(); Looper.loop(); Log.d( TAG, "Looper thread ends" ); } }; mGpsThread.start(); } public void stopGpsLocator() { Log.d(TAG, "stopGpsLocator"); mGpsHandler.getLooper().quit(); mGpsHandler = null; mLocationManager.removeUpdates(locationListener); } // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.i(TAG, "New location latitude: " + location.getLatitude() + " longituted: " + location.getLongitude() + " altitude: " + location.getAltitude() + " count: " + mGpsUpdateCount); if (isBetterLocation(location, mLastLocation)) mLastLocation = location; mGpsUpdateCount++; //Log.i(TAG, "GPS time: " + location.getTime()); //Log.i(TAG, "Time: " + System.currentTimeMillis()); // wait for 3 location updates if (mGpsUpdateCount == mGpsSampleCount) { mLocationManager.removeUpdates(locationListener); //_gpsUpdateCount = 0; synchronized (mGpsList) { while(!mGpsList.isEmpty()){ File file = mGpsList.poll(); setImageGpsLocation(location, file); } mIsWaitingForGpsUpdate = false; } } } public void onStatusChanged(String provider, int status, Bundle extras) { Log.i(TAG, "Status changes: " + status); } public void onProviderEnabled(String provider) { Log.i(TAG, "Provider enabled: " + provider); } public void onProviderDisabled(String provider) { Log.i(TAG, "Provider disable: " + provider); } }; /** Determines whether one Location reading is better than the current Location fix * @param location The new Location that you want to evaluate * @param currentBestLocation The current Location fix, to which you want to compare the new one */ protected boolean isBetterLocation(Location location, Location currentBestLocation) { if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > getSampleInterval(); boolean isSignificantlyOlder = timeDelta < -getSampleInterval(); boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } private int getSampleInterval(){ return 1000 * 60 * mGpsSampleInterval; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } private void setImageGpsLocation(Location location, File file) { NativeMethods.getInstance().setGPSExifData(file.getAbsolutePath(), location.getLatitude(), location.getLongitude(), location.getAltitude()); runMediaScanner(file); } private void runMediaScanner(File file) { Uri contentUri = Uri.fromFile(file); Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE"); mediaScanIntent.setData(contentUri); mContext.sendBroadcast(mediaScanIntent); } private boolean needLocationUpdate() { if (mLastLocation != null) { long utcTime = System.currentTimeMillis(); if ((utcTime - mLastLocation.getTime()) < getSampleInterval()) return false; } return true; } public void updateGpsLocation() { if (mGpsHandler != null) mGpsHandler.post(new Runnable() { public void run() { Log.d(TAG, "Getting new GPS Location"); if (!mIsWaitingForGpsUpdate) { mIsWaitingForGpsUpdate = true; mGpsUpdateCount = 0; Log.d(TAG, "Need GPS location update"); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } } }); } public void addGpsLocation(File file) { synchronized (mGpsList) { Log.d(TAG, "Getting exif gps data"); if (needLocationUpdate()) { mGpsList.push(file); Log.d(TAG, "Need new GPS Location"); updateGpsLocation(); } else { setImageGpsLocation(mLastLocation, file); } } } }
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
// 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
/* <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.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; public class TimelapseDialog { private final static String TAG = "TimelapseDialog"; private Context mContext; private DslrHelper mDslrHelper; private PtpDevice mPtpDevice; private View mView; private TextView txtCaptureDuration; private TextView txtMovieLength; private TextView txtInterval; private TextView txtFrameRate; private TextView txtFrameCount; private Button mStartTimelapse; private SeekBar mSeekBar; private CustomDialog mDialog; private TimeSpan mCaptureDuration; private TimeSpan mMovieLength; private TimeSpan mInterval; private int mFrameRate = 25; private int mFrameCount= 0; public TimelapseDialog(Context context) { mContext = context; mDslrHelper = DslrHelper.getInstance(); mPtpDevice = mDslrHelper.getPtpDevice(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.timelapsedialog, null); mCaptureDuration = new TimeSpan(0, 0, 0); mMovieLength = new TimeSpan(0, 0, 0); mInterval = new TimeSpan(0, 0, 0); txtCaptureDuration = (TextView)mView.findViewById(R.id.txtcaptureduration); txtMovieLength = (TextView)mView.findViewById(R.id.txtmovielength); txtInterval = (TextView)mView.findViewById(R.id.txtinterval); txtFrameRate = (TextView)mView.findViewById(R.id.txtframerate); txtFrameCount = (TextView)mView.findViewById(R.id.txtframecount); mStartTimelapse = (Button)mView.findViewById(R.id.timelapse_start); mSeekBar = (SeekBar)mView.findViewById(R.id.timelapse_framerate); mSeekBar.setProgress(mFrameRate); if (mPtpDevice != null) { Log.d(TAG, "Interval: " + mPtpDevice.getTimelapseInterval()); Log.d(TAG, "Iterations: " + mPtpDevice.getTimelapseIterations()); mInterval = TimeSpan.FromMilliseconds(mPtpDevice.getTimelapseInterval()); mFrameCount = mPtpDevice.getTimelapseIterations(); mMovieLength = TimeSpan.FromSeconds(mFrameCount / mFrameRate); mCaptureDuration = TimeSpan.FromSeconds(mInterval.TotalSeconds() * mFrameCount); } // calculateRecordingLength(); updateDisplay(); txtCaptureDuration.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TimePickerDialog tpd = new TimePickerDialog(mContext, "", mCaptureDuration, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mCaptureDuration = new TimeSpan(hourOfDay, minute, second); mFrameCount = (int)(mCaptureDuration.TotalMilliseconds() / mInterval.TotalMilliseconds()); mMovieLength = TimeSpan.FromSeconds(mFrameCount * mFrameRate); updateDisplay(); //calculateInterval(); } }); tpd.show(); } }); txtMovieLength.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new TimePickerDialog(mContext, "", mMovieLength, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mMovieLength = new TimeSpan(hourOfDay, minute, second); mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); //calculateFrameCount(); //calculateInterval(); } }).show(); } }); txtInterval.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new TimePickerDialog(mContext, "", mInterval, new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(int hourOfDay, int minute, int second) { mInterval = new TimeSpan(hourOfDay, minute, second); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); //calculateRecordingLength(); } }).show(); } }); mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { if (progress > 0) { mFrameRate = progress; mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); mCaptureDuration = TimeSpan.FromMilliseconds(mInterval.TotalMilliseconds() * mFrameCount); updateDisplay(); } } } }); // txtFrameRate.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) { // try { // mFrameRate = Integer.parseInt(s.toString()); // // //calculateFrameCount(); // //calculateInterval(); // } catch (NumberFormatException e) { // // } // } // }); mStartTimelapse.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Interval: " + mInterval.TotalMilliseconds()); Log.d(TAG, "Iterations: " + mFrameCount); mPtpDevice.startTimelapse((long)mInterval.TotalMilliseconds(), mFrameCount); mDialog.dismiss(); } }); } private void calculateRecordingLength(){ double recordingLength = mFrameRate * mMovieLength.TotalSeconds() * mInterval.TotalSeconds(); mCaptureDuration = TimeSpan.FromSeconds(recordingLength); txtCaptureDuration.setText(mCaptureDuration.toString()); Log.d(TAG, "Recording length " + recordingLength / 3600); } private void calculateInterval() { double frameCount = mFrameRate * mMovieLength.TotalSeconds(); double interval = 0; if (frameCount > 0) interval = (mCaptureDuration.TotalHours() * 3600) / frameCount; mInterval = TimeSpan.FromSeconds(interval); txtInterval.setText(mInterval.toString()); Log.d(TAG, "interval " + interval); } private void calculateFrameCount(){ mFrameCount = (int)(mMovieLength.TotalSeconds() * mFrameRate); txtFrameCount.setText(String.format("%d", mFrameCount)); } private void updateDisplay(){ txtFrameRate.setText(String.format("%d", mFrameRate)); txtCaptureDuration.setText(mCaptureDuration.toString()); txtMovieLength.setText(mMovieLength.toString()); txtInterval.setText(mInterval.toString()); txtFrameCount.setText(String.format("%d", mFrameCount)); } public void show() { CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder.setTitle("Timelapse settings") .setContentView(mView); mDialog = customBuilder .create(); mDialog.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; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class PtpPropertyListAdapter extends BaseAdapter { private ArrayList<PtpPropertyListItem> mItemList; private Context mContext; private LayoutInflater mInflater; private int mSelectedItem; public PtpPropertyListAdapter(Context context, ArrayList<PtpPropertyListItem> itemList, int selectedItem){ super(); mSelectedItem = selectedItem; mContext = context; mItemList = itemList; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return mItemList.size(); } public Object getItem(int position) { return mItemList.get(position); } public long getItemId(int position) { return 0; } public static class ViewHolder { ImageView mImageViewLogo; TextView mTextViewTitle; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView==null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.property_list_item, null); holder.mImageViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo); holder.mTextViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle); convertView.setTag(holder); } else holder=(ViewHolder)convertView.getTag(); PtpPropertyListItem listItem = (PtpPropertyListItem) mItemList.get(position); if (listItem.getImage() > 0) { holder.mImageViewLogo.setImageResource(listItem.getImage()); holder.mImageViewLogo.setVisibility(View.VISIBLE); } else { holder.mImageViewLogo.setImageDrawable(null); holder.mImageViewLogo.setVisibility(View.GONE); } if (listItem.getNameId() > 0) holder.mTextViewTitle.setText(listItem.getNameId()); else holder.mTextViewTitle.setText(listItem.getTitle()); 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 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 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
/* <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; public interface IDslrActivity { public PtpDevice getPtpDevice(); public void toggleFullScreen(); public boolean getIsFullScreen(); public void toggleLvLayout(); public void toggleLvLayout(boolean showLvLayout); public boolean getIsLvLayoutEnabled(); public void zoomLiveView(boolean up); }
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.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import com.dslr.dashboard.imgzoom.*; import android.app.Activity; import android.content.ComponentName; import android.content.ContentValues; import android.content.Intent; import android.content.res.Configuration; 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.RectF; import android.net.Uri; import android.os.Bundle; import android.os.Vibrator; import android.provider.MediaStore; import android.util.FloatMath; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class ImagePreviewActivity extends ActivityBase { private static String TAG = "ImagePreviewActivity"; private ListView mExifList; private ImageView mHistogramView; private boolean mHistogramSeparate = true; private Boolean mIsExifVisible = false; private String[] mExifNames; /** Image zoom view */ private ImageZoomView mZoomView; private TextView mTxtLoading; private LinearLayout mProgressLayout; /** Zoom control */ private DynamicZoomControl mZoomControl; /** Decoded bitmap image */ private Bitmap mBitmap = null; /** On touch listener for zoom view */ // private LongPressZoomListener mZoomListener; private String _imgPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); if (savedInstanceState != null) { String tmpPath = savedInstanceState.getString("tmpFile"); if (!tmpPath.isEmpty()) { Log.i(TAG, "Restore from tmp file: " + tmpPath); File f = new File(tmpPath); mBitmap = BitmapFactory.decodeFile(f.getAbsolutePath()); Log.i(TAG, "Delete temp file"); if (!f.delete()) Log.d(TAG, "tmp file not deleted"); } //mBitmap = savedInstanceState.getParcelable("bitmap"); _imgPath = savedInstanceState.getString("imgPath"); } mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); mScaledTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); mScaledMaximumFlingVelocity = ViewConfiguration.get(this) .getScaledMaximumFlingVelocity(); mVibrator = (Vibrator)getSystemService("vibrator"); setContentView(R.layout.activity_image_preview); getActionBar().setDisplayShowTitleEnabled(false); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayUseLogoEnabled(true); mZoomControl = new DynamicZoomControl(); mZoomView = (ImageZoomView)findViewById(R.id.zoomview); mZoomView.setZoomState(mZoomControl.getZoomState()); mZoomView.setOnTouchListener(mZoomListener); mZoomControl.setAspectQuotient(mZoomView.getAspectQuotient()); mZoomView.setVisibility(View.GONE); mHistogramView = (ImageView)findViewById(R.id.histogram_view); mHistogramView.setAlpha((float)0.4); mHistogramView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mHistogramSeparate = !mHistogramSeparate; mHistogramView.setImageBitmap(NativeMethods.getInstance().createHistogramBitmap(mBitmap, mHistogramSeparate)); } }); mTxtLoading = (TextView)findViewById(R.id.txtLoading); mProgressLayout = (LinearLayout)findViewById(R.id.progresslayout); mExifList = (ListView)findViewById(R.id.exifList); mExifNames = getResources().getStringArray(R.array.exifNames); } private void toggleActionBar(){ if (getActionBar().isShowing()) getActionBar().hide(); else getActionBar().show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG, "onCreateOptionsMenu"); getMenuInflater().inflate(R.menu.menu_image_preview, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_histogram: if (mHistogramView.getVisibility() == View.GONE) { mHistogramView.setImageBitmap(NativeMethods.getInstance().createHistogramBitmap(mBitmap, mHistogramSeparate)); mHistogramView.setVisibility(View.VISIBLE); } else mHistogramView.setVisibility(View.GONE); return true; case R.id.menu_exif: displayExif(); return true; case R.id.menu_share: shareImage(); return true; default: return true; } } private void displayExif() { if (_imgPath != null && !_imgPath.isEmpty()){ if (!mIsExifVisible) { ArrayList<ExifDataHelper> exifs = NativeMethods.getInstance().getImageExif(mExifNames, _imgPath); ExifAdapter adapter = new ExifAdapter(this, exifs); mExifList.setAdapter(adapter); } mIsExifVisible = !mIsExifVisible; mExifList.setVisibility(mIsExifVisible ? View.VISIBLE : View.GONE); } } private int reqCode = 1; private String tmpPath; private boolean isTemporary = false; private void shareImage(){ tmpPath = _imgPath; if (!tmpPath.isEmpty() && mBitmap != null) { // if nef we need to save to jpg if (tmpPath.substring((tmpPath.lastIndexOf(".") + 1), tmpPath.length()).toLowerCase().equals("nef")) { tmpPath = tmpPath.substring(0, tmpPath.lastIndexOf(".") + 1) + "jpg"; isTemporary = saveAsJpeg(new File(tmpPath)); if (isTemporary) NativeMethods.getInstance().copyExifData(_imgPath, tmpPath); } File f = new File(tmpPath); ContentValues values = new ContentValues(2); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg"); values.put(MediaStore.Images.Media.DATA, f.getAbsolutePath()); Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_TEXT, "Shared with DslrDashboard"); startActivityForResult(Intent.createChooser(intent , "How do you want to share?"), reqCode); } } private boolean saveAsJpeg(File f) { FileOutputStream fOut; try { fOut = new FileOutputStream(f); mBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); return true; } catch (Exception e) { return false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult"); if (requestCode == reqCode) { Log.d(TAG, "Result: " + resultCode); if (isTemporary) { Log.d(TAG, "Temporary file, delete"); File f = new File(tmpPath); f.delete(); } else Log.d(TAG, "Original file shared"); } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); if (mBitmap != null) { Log.d(TAG, "displaying image"); displayBitmap(mBitmap); } } @Override protected void onPause() { Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onStart() { Log.d(TAG, "onStart"); if (mBitmap != null) loadImage(null); else { Intent intent = getIntent(); if (intent != null){ Log.d(TAG, "Image from intent"); Uri data = intent.getData(); if (data != null) { String path = data.getEncodedPath(); Log.d(TAG, "Image path " + path); _imgPath = path; loadImage(path); } else if (intent.hasExtra("data")){ Log.d(TAG, "Image from bitmap "); mBitmap = BitmapFactory.decodeByteArray( intent.getByteArrayExtra("data"),0,getIntent().getByteArrayExtra("data").length); loadImage(null); } else { Log.d(TAG, "No data in intent"); loadImage(null); } } else { Log.d(TAG, "No Intent"); loadImage(null); } } super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy - bitmap recycle"); mZoomView.setImage(null); if (mBitmap != null) mBitmap.recycle(); mBitmap = null; super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { if (mBitmap != null) { // check if this is a nef file, then save as temp file File cache = getCacheDir(); File f; try { f = File.createTempFile("dslr", "jpg", cache); if (saveAsJpeg(f)) { Log.d(TAG, "Tmp file: " + f.getAbsolutePath()); outState.putString("tmpFile", f.getAbsolutePath()); } } catch (IOException e) { } } if (_imgPath != null && !_imgPath.isEmpty()) outState.putString("imgPath", _imgPath); Log.d(TAG, "onSaveInstanceState"); super.onSaveInstanceState(outState); } @Override public void onConfigurationChanged(Configuration newConfig) { Log.d(TAG, "onConfigurationChanged"); super.onConfigurationChanged(newConfig); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_BACK: if (mBitmap != null) { mBitmap.recycle(); //mBitmap = null; } finish(); return true; default: return super.onKeyDown(keyCode, event); } } private Bitmap loadJpeg(String path) { Log.i(TAG,"loading:"+path); //final int IMAGE_MAX_SIZE = 8000000; // 1.2MP Bitmap bm = null; File file=new File(path); BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; try { FileInputStream fis = new FileInputStream(file); BitmapFactory.decodeStream(fis, null, o); fis.close(); } catch (IOException e) { return null; } int scale = 1; int width = o.outWidth; int height = o.outHeight; while ((int)(width / scale) > 2048 || (int)(height / scale) > 2048) scale++; scale++; // while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > IMAGE_MAX_SIZE) { // scale++; // } Log.i(TAG, "Sample size: " + scale); BitmapFactory.Options bfOptions=new BitmapFactory.Options(); bfOptions.inMutable = true; bfOptions.inSampleSize = scale; bfOptions.inDither=false; //Disable Dithering mode bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future bfOptions.inTempStorage=new byte[32 * 1024]; FileInputStream fs=null; try { fs = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } try { if(fs!=null) bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); } catch (IOException e) { } finally{ if(fs!=null) { try { fs.close(); } catch (IOException e) { } } } return bm; } private void displayBitmap(final Bitmap bmp){ runOnUiThread(new Runnable() { public void run() { if (bmp != null) { Log.d(TAG, "displayBitmap"); mProgressLayout.setVisibility(View.GONE); mZoomView.setImage(bmp); mZoomView.setVisibility(View.VISIBLE); resetZoomState(); } } }); } private float calcBarHeight(int value, int max, int height) { float proc = (float)(100 * value) / (float)max; return (float) height * proc / (float) 100; } private void loadImage(final String path){ new Thread(new Runnable() { public void run() { try { if (path != null && !path.isEmpty()) { File f = new File(path); if (f.exists()) { if (path.substring((path.lastIndexOf(".") + 1), path.length()).toLowerCase().equals("nef")) { mBitmap = (Bitmap)NativeMethods.getInstance().loadRawImage(path); Log.d(TAG, "IsMutable: " + mBitmap.isMutable()); //drawHistogram(mBitmap); } else { mBitmap = loadJpeg(path); } } } } catch (Exception e) { Log.e(TAG, "Exeption: " + e.getMessage()); } if (mBitmap != null) { displayBitmap(mBitmap); } } }).start(); } private void resetZoomState() { mZoomControl.getZoomState().setPanX(0.5f); mZoomControl.getZoomState().setPanY(0.5f); mZoomControl.getZoomState().setZoom(1f); mZoomControl.getZoomState().notifyObservers(); } /** * 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, FULLSCREEN } /** Time of tactile feedback vibration when entering zoom mode */ private static final long VIBRATE_TIME = 50; /** Current listener mode */ private Mode mMode = Mode.UNDEFINED; /** 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 int mScaledTouchSlop; /** Duration in ms before a press turns into a long press */ private int mLongPressTimeout; /** Vibrator for tactile feedback */ private Vibrator mVibrator; /** Maximum velocity for fling */ private int mScaledMaximumFlingVelocity; float dist0, distCurrent, mCenterx, mCentery; private View.OnTouchListener mZoomListener = new View.OnTouchListener() { /** * 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; mMode = Mode.FULLSCREEN; 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); mCenterx = ((event.getX(0) + event.getX(1)) / 2) / v.getWidth(); mCentery = ((event.getY(0) + event.getY(1)) / 2) / v.getHeight(); Log.d(TAG, "Pinch mode"); break; case MotionEvent.ACTION_POINTER_UP: mMode = Mode.UNDEFINED; 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 = (float)Math.pow(2, -(dist0 - distCurrent)/1000); mZoomControl.zoom(factor, mCenterx, mCentery); } else if (mMode == Mode.FULLSCREEN) { mMode = Mode.PAN; } 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: switch (mMode) { case PAN: mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity); mZoomControl.startFling(-mVelocityTracker.getXVelocity() / v.getWidth(), -mVelocityTracker.getYVelocity() / v.getHeight()); break; case FULLSCREEN: toggleActionBar(); break; case PINCH: break; default: mZoomControl.startFling(0, 0); break; } 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; } }; @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 } @Override protected void processArduinoButtons( EnumSet<ArduinoButtonEnum> pressedButtons, EnumSet<ArduinoButtonEnum> releasedButtons) { for (ArduinoButtonEnum button : releasedButtons) { switch (button) { 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 android.app.Activity; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; public class LeftFragment extends DslrFragmentBase { private static final String TAG = "LeftFragment"; private LinearLayout mLeftLayout, mLeftScrollLayout; private CheckableImageView mInitiateCapture, mAutoFocus, mMovieRec; private PorterDuffColorFilter mColorFilterRed; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_left, container, false); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mLeftLayout = (LinearLayout)view.findViewById(R.id.left_layout); mLeftScrollLayout = (LinearLayout)view.findViewById(R.id.left_scroll_layout); mInitiateCapture = (CheckableImageView)view.findViewById(R.id.initiatecapture); mAutoFocus = (CheckableImageView)view.findViewById(R.id.autofocus); mMovieRec = (CheckableImageView)view.findViewById(R.id.movierec); mInitiateCapture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().initiateCaptureCmd(true); } }); mInitiateCapture.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { getPtpDevice().setCaptureToSdram(!getPtpDevice().getCaptureToSdram()); //mInitiateCapture.setColorFilter(getPtpDevice().getCaptureToSdram() ? mColorFilterRed : null); return true; } }); mAutoFocus.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().startAfDriveCmd(); } }); mAutoFocus.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { getPtpDevice().setAFBeforeCapture(!getPtpDevice().getAFBeforeCapture()); setAfColor(); return true; } }); mMovieRec.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (!getPtpDevice().getIsMovieRecordingStarted()) getPtpDevice().startMovieRecCmd(); else getPtpDevice().stopMovieRecCmd(); } }); 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()) { if (getPtpDevice().getIsLiveViewEnabled()){ // toggle movie recording button; toggleMovieRecVisibility(); } else mMovieRec.setVisibility(View.GONE); if (getPtpDevice().getIsCommandSupported(PtpCommand.AfDrive)) { mAutoFocus.setVisibility(View.VISIBLE); setAfColor(); } else mAutoFocus.setVisibility(View.GONE); if (getPtpDevice().getCaptureToSdram()) mInitiateCapture.setColorFilter(mColorFilterRed); else mInitiateCapture.setColorFilter(null); } } private void toggleMovieRecVisibility(){ if (getPtpDevice().getIsCommandSupported(PtpCommand.StartMovieRecInCard)) { mMovieRec.setVisibility(View.VISIBLE); if (getPtpDevice().getIsMovieRecordingStarted()) mMovieRec.setColorFilter(mColorFilterRed); else mMovieRec.setColorFilter(null); } else mMovieRec.setVisibility(View.GONE); } @Override protected void internalPtpPropertyChanged(PtpProperty property) { // TODO Auto-generated method stub } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch (event) { case LiveviewStart: toggleMovieRecVisibility(); break; case LiveviewStop: mMovieRec.setVisibility(View.GONE); break; case MovieRecordingStart: mMovieRec.setColorFilter(mColorFilterRed); break; case MovieRecordingEnd: mMovieRec.setColorFilter(null); break; case BusyBegin: Log.d(TAG, "Busy begin"); DslrHelper.getInstance().enableDisableControls(mLeftLayout, false); DslrHelper.getInstance().enableDisableControls(mLeftScrollLayout, false); break; case BusyEnd: Log.d(TAG, "Busy end"); DslrHelper.getInstance().enableDisableControls(mLeftLayout, true); DslrHelper.getInstance().enableDisableControls(mLeftScrollLayout, true); break; case RecordingDestinationChanged: mInitiateCapture.setColorFilter(getPtpDevice().getCaptureToSdram() ? mColorFilterRed : null); break; } } private void setAfColor(){ if (getPtpDevice().getAFBeforeCapture()) mAutoFocus.setColorFilter(mColorFilterRed); else mAutoFocus.setColorFilter(null); } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { if (key.equals(PtpDevice.PREF_KEY_SHOOTING_AF)) { setAfColor(); } } }
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
package com.dslr.dashboard; /** * @author Ashok Gelal * copyright: Ashok */ public class TimeSpan{ public static final long TicksPerMillisecond = 10000L; public static final long TicksPerSecond = 10000000L; public static final long TicksPerMinute = 600000000L; public static final long TicksPerHour = 36000000000L; public static final long TicksPerDay = 864000000000L; public static final TimeSpan Zero = new TimeSpan(0); public static final TimeSpan MinValue = new TimeSpan(Long.MIN_VALUE); public static final TimeSpan MaxValue = new TimeSpan(Long.MAX_VALUE); private long ticks; public int Hours() { return hours; } public int Minutes() { return minutes; } public int Seconds() { return seconds; } public int Days() { return days; } public int Milliseconds() { return milliseconds; } private int days; private int hours; private int minutes; private int seconds; private int milliseconds; private void TotalDays(double totalDays) { this.totalDays = totalDays; } private void TotalHours(double totalHours) { this.totalHours = totalHours; } private void TotalMinutes(double totalMinutes) { this.totalMinutes = totalMinutes; } private void TotalSeconds(double totalSeconds) { this.totalSeconds = totalSeconds; } public double TotalDays() { return totalDays; } public double TotalHours() { return totalHours; } public double TotalMinutes() { return totalMinutes; } public double TotalSeconds() { return totalSeconds; } public double TotalMilliseconds() { return totalMilliseconds; } private void TotalMilliseconds(double totalMilliseconds) { this.totalMilliseconds = totalMilliseconds; } private double totalDays; private double totalHours; private double totalMinutes; private double totalSeconds; private double totalMilliseconds; public long Ticks() { return ticks; } public TimeSpan(long ticks) { this.ticks = ticks; ConvertTicksToTotalTime(); ConvertTicksToTime(); } private void ConvertTicksToTime() { days = (int)(ticks / (TicksPerDay+0.0)); long diff = (ticks - TicksPerDay * days); hours = (int)(diff / (TicksPerHour+0.0)); diff = (diff - TicksPerHour * hours); minutes = (int)(diff / (TicksPerMinute+0.0)); diff = (diff - TicksPerMinute * minutes); seconds = (int)(diff / (TicksPerSecond + 0.0)); diff = (diff - TicksPerSecond * seconds); milliseconds = (int)((diff / TicksPerMillisecond+0.0)); } private void ConvertTicksToTotalTime() { TotalDays(ticks / (TicksPerDay + 0.0f)); TotalHours(ticks / (TicksPerHour + 0.0f)); TotalMinutes(ticks / (TicksPerMinute + 0.0f)); TotalSeconds(ticks/(TicksPerSecond+0.0f)); TotalMilliseconds(ticks/(TicksPerMillisecond+0.0f)); } public TimeSpan(int hours, int minutes, int seconds) { this(0, hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) { this(days, hours, minutes, seconds, 0); } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { this.days = days; this.hours = hours; this.minutes = minutes; this.seconds = seconds; this.milliseconds = milliseconds; CalculateTicks(); } private void CalculateTicks(){ this.ticks = days * TicksPerDay + hours * TicksPerHour + minutes * TicksPerMinute + seconds * TicksPerSecond + milliseconds * TicksPerMillisecond; ConvertTicksToTotalTime(); } public static TimeSpan Add(TimeSpan t1, TimeSpan t2) { return new TimeSpan(t1.ticks+t2.ticks); } public TimeSpan Add(TimeSpan t1) { return new TimeSpan(this.ticks + t1.ticks); } @Override public boolean equals(Object other){ if(other == null) return false; if(other == this) return true; if(this.getClass() != other.getClass()) return false; TimeSpan otherClass = (TimeSpan) other; return (ticks==otherClass.Ticks()); } public boolean Equals(TimeSpan other) { return equals(other); } public static boolean Equals(TimeSpan time1, TimeSpan time2) { return time1.Equals(time2); } public boolean GreaterThan(TimeSpan time) { return ticks > time.Ticks(); } public boolean GreaterThanOrEqual(TimeSpan time) { return ticks >= time.Ticks(); } public boolean NotEquals(TimeSpan time) { return !Equals(time); } public boolean LessThan(TimeSpan time) { return ticks < time.Ticks(); } public boolean LessThanOrEqual(TimeSpan time) { return ticks <= time.Ticks(); } public TimeSpan Subtract(TimeSpan time) { return new TimeSpan(ticks - time.Ticks()); } public static TimeSpan Subtract(TimeSpan time1, TimeSpan time2) { return new TimeSpan(time1.Ticks() - time2.Ticks()); } public TimeSpan Duration() { return new TimeSpan(Math.abs(ticks)); } public static TimeSpan FromDays(double days) { return new TimeSpan((long)(Math.ceil(days * 24 * 3600 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromHours(double hours) { return new TimeSpan((long)(Math.ceil(hours * 3600 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromMinutes(double minutes) { return new TimeSpan((long)(Math.ceil(minutes * 60 * 1000) * TicksPerMillisecond)); } public static TimeSpan FromSeconds(double seconds) { return new TimeSpan((long)(Math.ceil(seconds * 1000) * TicksPerMillisecond)); } public static TimeSpan FromMilliseconds(double milliseconds) { return new TimeSpan((long)(Math.ceil(milliseconds) * TicksPerMillisecond)); } public static TimeSpan FromTicks(long ticks) { return new TimeSpan(ticks); } @Override public String toString() { StringBuilder str = new StringBuilder(); if(days>=1 || days<=-1) str.append(String.format("%02d.", days)); str.append(String.format("%02d:", hours)); str.append(String.format("%02d:", minutes)); str.append(String.format("%02d", seconds)); if(milliseconds>=1) str.append(String.format(".%d%s", milliseconds, TRAILING_ZEROS.substring(Integer.toString(milliseconds).length()))); return str.toString(); } private static final String TRAILING_ZEROS = "0000000"; }
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 android.util.Log; public class PtpSession { private static String TAG = "PtpSession"; private int sessionId; private int xid; private boolean active; public PtpSession () { } int getNextXID () { return (active ? xid++ : 0); } int getNextSessionID () { if (!active) return ++sessionId; else return xid++; } public boolean isActive () { return active; } public void open () { xid = 1; active = true; Log.d(TAG, "**** sesion opened");} public void close () { active = false; } int getSessionId () { return sessionId; } // track objects and their info by handles; // hookup to marshaling system and event framework }
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
/* <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 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
// 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 PtpResponse { /** ResponseCode: */ public static final int Undefined = 0x2000; /** ResponseCode: */ public static final int OK = 0x2001; /** ResponseCode: */ public static final int GeneralError = 0x2002; /** ResponseCode: */ public static final int SessionNotOpen = 0x2003; /** ResponseCode: */ public static final int InvalidTransactionID = 0x2004; /** ResponseCode: */ public static final int OperationNotSupported = 0x2005; /** ResponseCode: */ public static final int ParameterNotSupported = 0x2006; /** ResponseCode: */ public static final int IncompleteTransfer = 0x2007; /** ResponseCode: */ public static final int InvalidStorageID = 0x2008; /** ResponseCode: */ public static final int InvalidObjectHandle = 0x2009; /** ResponseCode: */ public static final int DevicePropNotSupported = 0x200a; /** ResponseCode: */ public static final int InvalidObjectFormatCode = 0x200b; /** ResponseCode: */ public static final int StoreFull = 0x200c; /** ResponseCode: */ public static final int ObjectWriteProtected = 0x200d; /** ResponseCode: */ public static final int StoreReadOnly = 0x200e; /** ResponseCode: */ public static final int AccessDenied = 0x200f; /** ResponseCode: */ public static final int NoThumbnailPresent = 0x2010; /** ResponseCode: */ public static final int SelfTestFailed = 0x2011; /** ResponseCode: */ public static final int PartialDeletion = 0x2012; /** ResponseCode: */ public static final int StoreNotAvailable = 0x2013; /** ResponseCode: */ public static final int SpecificationByFormatUnsupported = 0x2014; /** ResponseCode: */ public static final int NoValidObjectInfo = 0x2015; /** ResponseCode: */ public static final int InvalidCodeFormat = 0x2016; /** ResponseCode: */ public static final int UnknownVendorCode = 0x2017; /** ResponseCode: */ public static final int CaptureAlreadyTerminated = 0x2018; /** ResponseCode: */ public static final int DeviceBusy = 0x2019; /** ResponseCode: */ public static final int InvalidParentObject = 0x201a; /** ResponseCode: */ public static final int InvalidDevicePropFormat = 0x201b; /** ResponseCode: */ public static final int InvalidDevicePropValue = 0x201c; /** ResponseCode: */ public static final int InvalidParameter = 0x201d; /** ResponseCode: */ public static final int SessionAlreadyOpen = 0x201e; /** ResponseCode: */ public static final int TransactionCanceled = 0x201f; /** ResponseCode: */ public static final int SpecificationOfDestinationUnsupported = 0x2020; public static final int HardwareError = 0xa001; public static final int OutOfFocus = 0xa002; public static final int ChangeCameraModeFailed = 0xa003; public static final int InvalidStatus = 0xa004; public static final int SetPropertyNotSupport = 0xa005; public static final int WbPresetError = 0xa006; public static final int DustRefenreceError = 0xa007; public static final int ShutterSpeedBulb = 0xa008; public static final int MirrorUpSquence = 0xa009; public static final int CameraModeNotAdjustFnumber = 0xa00a; public static final int NotLiveView = 0xa00b; public static final int MfDriveStepEnd = 0xa00c; public static final int MfDriveStepInsufficiency = 0xa00e; public static final int InvalidObjectPropCode = 0xa801; public static final int InvalidObjectPropFormat = 0xa802; public static final int ObjectPropNotSupported = 0xa80a; }
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 UsbAttachedActivity extends Activity { private static final String TAG = "UsbAttachedActivity"; @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("UsbAttached", 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.os.Bundle; import android.preference.PreferenceFragment; public class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
Java
package com.dslr.dashboard; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.TextView; public class FlashCommanderFragment extends DslrFragmentBase { private final static String TAG = FlashCommanderFragment.class.getSimpleName(); private TextView txtInternalFlashRPTIntense, txtInternalFlashRPTCount, txtInternalFlashRPTInterval; private TextView txtInternalFlashCommanderChannel; private CheckableImageView btnInternalFlashCommanderSelf, btnInternalFlashCommanderGroupA, btnInternalFlashCommanderGroupB; private TextView txtInternalFlashCommanderSelfComp, txtInternalFlashCommanderSelfIntense; private TextView txtInternalFlashCommanderGroupAComp, txtInternalFlashCommanderGroupAIntense; private TextView txtInternalFlashCommanderGroupBComp, txtInternalFlashCommanderGroupBIntense; private GridLayout mGridLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mView = inflater.inflate(R.layout.flash_commander_fragment, container, false); getDialog().setTitle("Flash Commander"); mGridLayout = (GridLayout)mView.findViewById(R.id.flash_grid_layout); // repeat flash properties txtInternalFlashRPTIntense = (TextView)mView.findViewById(R.id.txtflashrptintense); txtInternalFlashRPTCount = (TextView)mView.findViewById(R.id.txtflashrptcout); txtInternalFlashRPTInterval = (TextView)mView.findViewById(R.id.txtflashrptinterval); // commander channel txtInternalFlashCommanderChannel = (TextView)mView.findViewById(R.id.txtflashcommanderchannel); // commander self btnInternalFlashCommanderSelf = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommanderself); txtInternalFlashCommanderSelfComp = (TextView)mView.findViewById(R.id.txtflashcommanderselfcomp); txtInternalFlashCommanderSelfIntense = (TextView)mView.findViewById(R.id.txtflashcommanderselfintense); // commander group A btnInternalFlashCommanderGroupA = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommandergroupa); txtInternalFlashCommanderGroupAComp = (TextView)mView.findViewById(R.id.txtflashcommandergroupacomp); txtInternalFlashCommanderGroupAIntense = (TextView)mView.findViewById(R.id.txtflashcommandergroupaintense); // commander group B btnInternalFlashCommanderGroupB = (CheckableImageView)mView.findViewById(R.id.imginternalflashcommandergroupb); txtInternalFlashCommanderGroupBComp = (TextView)mView.findViewById(R.id.txtflashcommandergroupbcomp); txtInternalFlashCommanderGroupBIntense = (TextView)mView.findViewById(R.id.txtflashcommandergroupbintense); // repeat flash properties txtInternalFlashRPTIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTIntense, "Internal Flash Repeat mode intensity", null); } }); txtInternalFlashRPTCount.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTCount, "Internal Flash Repeat mode count", null); } }); txtInternalFlashRPTInterval.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashManualRPTInterval, "Internal Flash Repeat mode interval", null); } }); // commander channel txtInternalFlashCommanderChannel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderChannel, "Internal Flash Commander channel", null); } }); // commander self btnInternalFlashCommanderSelf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfMode, "Commander-Self mode", null); } }); txtInternalFlashCommanderSelfComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfComp, "Commander-Self compensation", null); } }); txtInternalFlashCommanderSelfIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderSelfIntense, "Commander-Self intensity", null); } }); // commander group A btnInternalFlashCommanderGroupA.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAMode, "Commander-Group A mode", null); } }); txtInternalFlashCommanderGroupAComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAComp, "Commander-Group A compensation", null); } }); txtInternalFlashCommanderGroupAIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupAIntense, "Commander-Group A intensity", null); } }); // commander group B btnInternalFlashCommanderGroupB.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBMode, "Commander-Group B mode", null); } }); txtInternalFlashCommanderGroupBComp.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBComp, "Commander-Group B compensation", null); } }); txtInternalFlashCommanderGroupBIntense.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.InternalFlashCommanderGroupBIntense, "Commander-Group B intensity", null); } }); return mView; } @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() { initializePtpPropertyView(txtInternalFlashRPTIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTIntense)); initializePtpPropertyView(txtInternalFlashRPTCount, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTCount)); initializePtpPropertyView(txtInternalFlashRPTInterval, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashManualRPTInterval)); initializePtpPropertyView(txtInternalFlashCommanderChannel, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderChannel)); initializePtpPropertyView(btnInternalFlashCommanderSelf, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfMode)); initializePtpPropertyView(txtInternalFlashCommanderSelfComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfComp)); initializePtpPropertyView(txtInternalFlashCommanderSelfIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderSelfIntense)); initializePtpPropertyView(btnInternalFlashCommanderGroupA, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAMode)); initializePtpPropertyView(txtInternalFlashCommanderGroupAComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAComp)); initializePtpPropertyView(txtInternalFlashCommanderGroupAIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupAIntense)); initializePtpPropertyView(btnInternalFlashCommanderGroupB, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBMode)); initializePtpPropertyView(txtInternalFlashCommanderGroupBComp, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBComp)); initializePtpPropertyView(txtInternalFlashCommanderGroupBIntense, getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCommanderGroupBIntense)); } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch(property.getPropertyCode()) { case PtpProperty.InternalFlashManualRPTIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTIntense, property); break; case PtpProperty.InternalFlashManualRPTCount: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTCount, property); break; case PtpProperty.InternalFlashManualRPTInterval: DslrHelper.getInstance().setDslrTxt(txtInternalFlashRPTInterval, property); break; case PtpProperty.InternalFlashCommanderChannel: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderChannel, property); break; case PtpProperty.InternalFlashCommanderSelfMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderSelf, property); break; case PtpProperty.InternalFlashCommanderSelfComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderSelfComp, property); break; case PtpProperty.InternalFlashCommanderSelfIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderSelfIntense, property); break; case PtpProperty.InternalFlashCommanderGroupAMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderGroupA, property); break; case PtpProperty.InternalFlashCommanderGroupAComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupAComp, property); break; case PtpProperty.InternalFlashCommanderGroupAIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupAIntense, property); break; case PtpProperty.InternalFlashCommanderGroupBMode: DslrHelper.getInstance().setDslrImg(btnInternalFlashCommanderGroupB, property); break; case PtpProperty.InternalFlashCommanderGroupBComp: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupBComp, property); break; case PtpProperty.InternalFlashCommanderGroupBIntense: DslrHelper.getInstance().setDslrTxt(txtInternalFlashCommanderGroupBIntense, property); break; } } } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case BusyBegin: Log.d(TAG, "Busy begin"); DslrHelper.getInstance().enableDisableControls(mGridLayout, false); break; case BusyEnd: Log.d(TAG, "Busy end"); DslrHelper.getInstance().enableDisableControls(mGridLayout, 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 java.util.Hashtable; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class BottomFragment extends DslrFragmentBase { private static final String TAG = "BottomFragment"; private RelativeLayout mBottomLayout; private ImageView mFullScreen, mFlashIndicator, mEvCompensationIndicator, mFlashCompensationIndicator, mLvLayoutSwitch; private TextView txtAperture, txtShutter, mSdcard1, mSdcard2, mAeLockStatus; private PorterDuffColorFilter mColorFilterGreen, mColorFilterRed; private ExposureIndicatorDisplay mExposureIndicator; private View.OnClickListener mSdcardClickListener = new View.OnClickListener() { public void onClick(View v) { Intent ipIntent = new Intent(getActivity(), DslrImageBrowserActivity.class); ipIntent.setAction(Intent.ACTION_VIEW); ipIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getActivity().startActivity(ipIntent); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_bottom, container, false); mBottomLayout = (RelativeLayout)view.findViewById(R.id.bottom_layout); txtAperture = (TextView)view.findViewById(R.id.txt_aperture); txtAperture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Aperture click"); DslrHelper.getInstance().showApertureDialog(getActivity()); //showApertureDialog(); } }); txtShutter = (TextView)view.findViewById(R.id.txt_shutter); txtShutter.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().showExposureTimeDialog(getActivity()); //showExposureTimeDialog(); } }); // mFlexibleProgram = (TextView)view.findViewById(R.id.flexibleprogram); // mExposureIndicateStatus = (TextView)view.findViewById(R.id.exposureindicatestatus); mFullScreen = (ImageView)view.findViewById(R.id.fullscreen); mLvLayoutSwitch = (ImageView)view.findViewById(R.id.lvlayoutswitch); mFlashIndicator = (ImageView)view.findViewById(R.id.flashindicator); mEvCompensationIndicator = (ImageView)view.findViewById(R.id.evcompensationindicator); mFlashCompensationIndicator = (ImageView)view.findViewById(R.id.flashcompensationindicator); mExposureIndicator = (ExposureIndicatorDisplay)view.findViewById(R.id.exposureindicator); mColorFilterGreen = new PorterDuffColorFilter(getResources().getColor(R.color.HoloGreenLight), android.graphics.PorterDuff.Mode.SRC_ATOP); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mFullScreen.setColorFilter(mColorFilterGreen); mFlashIndicator.setColorFilter(mColorFilterGreen); mEvCompensationIndicator.setColorFilter(mColorFilterGreen); mFlashCompensationIndicator.setColorFilter(mColorFilterGreen); mLvLayoutSwitch.setColorFilter(mColorFilterGreen); mFullScreen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IDslrActivity activity = getDslrActivity(); if (activity != null) { activity.toggleFullScreen(); if (activity.getIsFullScreen()) { mFullScreen.setImageResource(R.drawable.full_screen_return); mLvLayoutSwitch.setVisibility(View.INVISIBLE); } else { mFullScreen.setImageResource(R.drawable.full_screen); mLvLayoutSwitch.setVisibility(View.VISIBLE); } } } }); mLvLayoutSwitch.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { IDslrActivity activity = getDslrActivity(); if (activity != null) { activity.toggleLvLayout(); if (activity.getIsLvLayoutEnabled()) mLvLayoutSwitch.setImageResource(R.drawable.initiate_capture); else mLvLayoutSwitch.setImageResource(R.drawable.i0xd1a20x0000); } } }); mSdcard1 = (TextView)view.findViewById(R.id.txt_sdcard1); mSdcard2 = (TextView)view.findViewById(R.id.txt_sdcard2); mSdcard1.setOnClickListener(mSdcardClickListener); mSdcard2.setOnClickListener(mSdcardClickListener); mAeLockStatus = (TextView)view.findViewById(R.id.txt_aelockstatus); return view; } public void initFragment() { Log.d(TAG, "initFragment"); } @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() { try { if (getIsPtpDeviceInitialized()) { IDslrActivity activity = getDslrActivity(); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.FStop)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureTime)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.AeLockStatus)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashPopup)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashStatus)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureBiasCompensation)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.InternalFlashCompensation)); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.FlexibleProgram)); mExposureIndicator.invalidate(); internalPtpPropertyChanged(getPtpDevice().getPtpProperty(PtpProperty.ExposureIndicateStatus)); Hashtable<Integer, PtpStorageInfo> tmp = getPtpDevice().getPtpStorages(); PtpStorageInfo[] storages = tmp.values().toArray(new PtpStorageInfo[tmp.values().size()]); mSdcard1.setText("[E]"); mSdcard2.setVisibility(View.INVISIBLE); if (storages.length > 0) { if (storages.length > 1) { mSdcard2.setVisibility(View.VISIBLE); mSdcard2.setText(String.format("[%d]", storages[1].freeSpaceInImages)); } mSdcard1.setText(String.format("[%d]", storages[0].freeSpaceInImages)); } mFullScreen.setVisibility(getPtpDevice().getIsLiveViewEnabled() ? View.VISIBLE : View.INVISIBLE); if (activity != null) { if (activity.getIsFullScreen()) mLvLayoutSwitch.setVisibility(View.INVISIBLE); else mLvLayoutSwitch.setVisibility(mFullScreen.getVisibility()); } } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch (property.getPropertyCode()) { case PtpProperty.FStop: updateAperture(property); break; case PtpProperty.ExposureTime: updateExposureTime(property); break; case PtpProperty.AeLockStatus: if ((Integer)property.getValue() == 1) mAeLockStatus.setVisibility(View.VISIBLE); else mAeLockStatus.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashPopup: if ((Integer)property.getValue() == 1) { mFlashIndicator.setVisibility(View.VISIBLE); } else mFlashIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashStatus: Integer flashStatus = (Integer)property.getValue(); Log.d(TAG, "Flash status " + flashStatus); if (flashStatus == 1) // flash ready mFlashIndicator.setColorFilter(mColorFilterGreen); else // flash charging mFlashIndicator.setColorFilter(mColorFilterRed); break; case PtpProperty.ExposureBiasCompensation: if ((Integer)property.getValue() != 0) mEvCompensationIndicator.setVisibility(View.VISIBLE); else mEvCompensationIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.InternalFlashCompensation: if ((Integer)property.getValue() != 0) mFlashCompensationIndicator.setVisibility(View.VISIBLE); else mFlashCompensationIndicator.setVisibility(View.INVISIBLE); break; case PtpProperty.FlexibleProgram: Integer val = (Integer)property.getValue(); //mFlexibleProgram.setText(val.toString()); mExposureIndicator.processValue((float)val / 6); break; case PtpProperty.ExposureIndicateStatus: Integer eval = (Integer)property.getValue(); //mExposureIndicateStatus.setText(eval.toString()); mExposureIndicator.processValue((float)eval / 6); break; default: break; } } } private void updateAperture(PtpProperty property) { int fStop = (Integer)property.getValue(); txtAperture.setVisibility(View.VISIBLE); txtAperture.setText("F" + (double)fStop / 100); txtAperture.setEnabled(property.getIsWritable()); } private void updateExposureTime(PtpProperty property) { Long nesto = (Long)property.getValue(); Log.i(TAG, "Exposure " + nesto); //double value = 1 / ((double)nesto / 10000); if (nesto == 4294967295L) txtShutter.setText("Bulb"); else { if (nesto >= 10000) txtShutter.setText(String.format("%.1f \"", (double)nesto / 10000)); else txtShutter.setText(String.format("1/%.1f" , 10000 / (double)nesto)); } txtShutter.setEnabled(property.getIsWritable()); } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { int card; TextView txtCard = null; switch(event) { case LiveviewStart: mFullScreen.setVisibility(View.VISIBLE); mLvLayoutSwitch.setVisibility(View.VISIBLE); break; case LiveviewStop: mFullScreen.setVisibility(View.INVISIBLE); mLvLayoutSwitch.setVisibility(View.INVISIBLE); break; case SdCardInserted: case SdCardRemoved: card = (Integer)data; txtCard = card == 1 ? mSdcard1 : mSdcard2; if (txtCard != null) { txtCard.setVisibility(View.VISIBLE); if (event == PtpDeviceEvent.SdCardRemoved) { txtCard.setText(" [E] "); } } break; case SdCardInfoUpdated: PtpStorageInfo sInfo = (PtpStorageInfo)data; card = sInfo.storageId >> 16; txtCard = card == 1 ? mSdcard1 : mSdcard2; if (txtCard != null) txtCard.setText(String.format("[%d]", sInfo.freeSpaceInImages)); break; case BusyBegin: Log.d(TAG, "BusyBegin"); DslrHelper.getInstance().enableDisableControls(mBottomLayout, false, false); break; case BusyEnd: Log.d(TAG, "BusyEnd"); DslrHelper.getInstance().enableDisableControls(mBottomLayout, true, false); 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.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 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 java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class PtpPartialObjectProccessor implements IPtpCommandFinalProcessor { private static String TAG = "GetPartialObjectProcessor"; public interface PtpPartialObjectProgressListener { public void onProgress(int offset); } 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 PtpPartialObjectProccessor(PtpObjectInfo objectInfo, File file){ this(objectInfo, 0x100000, file); } public PtpPartialObjectProccessor(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; if (cmd.isResponseOk()) { try { mStream.write(cmd.incomingData().data(), 12, count); } catch (IOException e) { } //System.arraycopy(cmd.incomingData().data(), 12, _objectData, _offset, count); if ((mOffset + count) < mObjectInfo.objectCompressedSize) { mOffset += count; cmd.getParams().set(1, mOffset); if ((mOffset + mMaxSize) > mObjectInfo.objectCompressedSize) cmd.getParams().set(2, mObjectInfo.objectCompressedSize - mOffset); else cmd.getParams().set(2, mMaxSize); result = true; } else { mOffset += count; try { mStream.flush(); mStream.close(); } catch (IOException e) { } } if (mProgressListener != null){ mProgressListener.onProgress(mOffset); } } return result; } }
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 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 java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.util.Log; import com.hoho.android.usbserial.driver.UsbSerialDriver; import com.hoho.android.usbserial.driver.UsbSerialProber; import com.hoho.android.usbserial.util.SerialInputOutputManager; public class UsbSerialService extends ServiceBase { private final static String TAG = UsbSerialService.class.getSimpleName(); @Override public void onCreate() { Log.d(TAG, "onCreate"); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent( ACTION_USB_PERMISSION), 0); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(mUsbPermissionReceiver, filter); try { mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); } catch (Exception e) { Log.d(TAG, "UsbManager not available: " + e.getMessage()); } super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand"); searchForSerialUsb(); return START_STICKY; } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); stopIoManager(); unregisterReceiver(mUsbPermissionReceiver); super.onDestroy(); } public interface ButtonStateChangeListener { void onButtonStateChanged(int buttons); } private ButtonStateChangeListener mButtonStateListener = null; public void setButtonStateChangeListener(ButtonStateChangeListener listener) { mButtonStateListener = listener; } private final ExecutorService mExecutor = Executors .newSingleThreadExecutor(); private UsbSerialDriver mSerialDevice; private UsbManager mUsbManager; private UsbDevice mUsbSerialDevice; PendingIntent mPermissionIntent; private SerialInputOutputManager mSerialIoManager; private static final String ACTION_USB_PERMISSION = "com.dslr.dashboard.USB_SERIAL_PERMISSION"; private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() { public void onRunError(Exception e) { Log.d(TAG, "Runner stopped."); } public void onNewData(final byte[] data) { updateReceivedData(data); } }; private void startUsbSerialDevice() { Log.d(TAG, "Starting USB Serial device"); mSerialDevice = UsbSerialProber.acquire(mUsbManager); Log.d(TAG, "Resumed, mSerialDevice=" + mSerialDevice); if (mSerialDevice == null) { Log.d(TAG, "No serial device."); } else { try { mSerialDevice.open(); } catch (IOException e) { Log.e(TAG, "Error setting up device: " + e.getMessage(), e); try { mSerialDevice.close(); } catch (IOException e2) { // Ignore. } mSerialDevice = null; return; } Log.d(TAG, "Serial device: " + mSerialDevice); } onDeviceStateChange(); } private void stopIoManager() { if (mSerialIoManager != null) { Log.i(TAG, "Stopping io manager .."); mSerialIoManager.stop(); mSerialIoManager = null; mUsbSerialDevice = null; } } private void startIoManager() { if (mSerialDevice != null) { Log.i(TAG, "Starting io manager .."); mSerialIoManager = new SerialInputOutputManager(mSerialDevice, mListener); mExecutor.submit(mSerialIoManager); } } private void onDeviceStateChange() { stopIoManager(); startIoManager(); } private boolean mNeedMoreBytes = false; private byte[] mData = new byte[1024]; private int mOffset = 0; private boolean mSyncFound = false; private int mSyncPos = 0; private void updateReceivedData(byte[] data) { // Log.d(TAG, "Incomind size: " + data.length); System.arraycopy(data, 0, mData, mOffset, data.length); mOffset += data.length; if (!mSyncFound) { int i = 0; do { if ((mData[i] & 0xff) == 0xaa) { //Log.d(TAG, "First sync found 0xaa"); if ((i + 1) < mOffset) { if ((mData[i+1] & 0xff) == 0x55) { //Log.d(TAG, "Second sync found 0x55"); mSyncFound = true; mSyncPos = i+2; mNeedMoreBytes = false; break; } } else { //Log.d(TAG, "Need more bytes for second sync"); mNeedMoreBytes = true; } } i++; } while (i < mOffset); } if (mSyncFound) { int length = 0; if (mNeedMoreBytes) { //Log.d(TAG, "Sync found need more byte"); length = (0xff & mData[mSyncPos + 1] << 8) + 0xff & mData[mSyncPos]; // Log.d(TAG, "Need size: " + length + " Offset: " + mOffset); if ((mSyncPos + length) == mOffset) { // Log.d(TAG, String.format("got all data: %d, %d",length, // mOffset) ); mNeedMoreBytes = false; mOffset = 0; } } else { //Log.d(TAG, "Sync found first check for bytes"); //Log.d(TAG, "Packet syncpos: " + mSyncPos + " offset: " + mOffset); if ((mSyncPos + 1) < mOffset) { //if (data.length > 1) { length = (0xff & mData[mSyncPos + 1] << 8) + 0xff & mData[mSyncPos]; //Log.d(TAG, "Packet length: " + length + " syncpos: " + mSyncPos + " offset: " + mOffset); //length = (0xff & data[1] << 8) + 0xff & data[0]; if ((mSyncPos + length) > mOffset) { //if (length != mOffset) { mNeedMoreBytes = true; } else { // Log.d(TAG, // String.format("got right size: %d, %d",length, // mOffset) ); mOffset = 0; } } else { mNeedMoreBytes = true; } } } if (!mNeedMoreBytes && mSyncFound) { int command = ((0xff & mData[mSyncPos + 3]) << 8) + (0xff & mData[mSyncPos +2]); switch (command) { case 0x0001: int buttons = ((0xff & mData[mSyncPos + 5]) << 8) + (0xff & mData[mSyncPos +4]); mSyncFound = false; mSyncPos = 0; //Log.d(TAG, "Serial button change detected"); if (mButtonStateListener != null) mButtonStateListener.onButtonStateChanged(buttons); break; } } } public void searchForSerialUsb() { if (mUsbSerialDevice == null) { Log.d(TAG, "Ptp Serial USB device not initialized, search for one"); if (mUsbManager != null) { HashMap<String, UsbDevice> devices = mUsbManager .getDeviceList(); Log.d(TAG, "Found USB devices count: " + devices.size()); Iterator<UsbDevice> iterator = devices.values().iterator(); while (iterator.hasNext()) { UsbDevice usbDevice = iterator.next(); Log.d(TAG, "USB Device: " + usbDevice.getDeviceName() + " Product ID: " + usbDevice.getProductId() + " Vendor ID: " + usbDevice.getVendorId() + " Interface count: " + usbDevice.getInterfaceCount()); if (usbDevice.getVendorId() == 0x2341) {// check if arduino Log.d(TAG, "Found Arduino"); mUsbManager.requestPermission(usbDevice, mPermissionIntent); break; } } } else Log.d(TAG, "USB Manager is unavailable"); } } private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "USB Serial permission Intent received " + action); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice usbDevice = (UsbDevice) intent .getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra( UsbManager.EXTRA_PERMISSION_GRANTED, false)) { Log.d(TAG, "USB device permission granted"); // if arduino, then start USB serial communication if (usbDevice.getVendorId() == 0x2341) { mUsbSerialDevice = usbDevice; startUsbSerialDevice(); } } } } } }; }
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.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Comparator; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class ImageObjectHelper { public final static int DSLR_PICTURE = 0; public final static int PHONE_PICTURE = 1; private static String TAG = "ImageObjectHelper"; public PtpObjectInfo objectInfo = null; public File file = null; public int progress = 0; public boolean isChecked = false; public int galleryItemType = 0; public ImageObjectHelper(){ } public String getFileExt(String FileName) { String ext = FileName.substring((FileName.lastIndexOf(".") + 1), FileName.length()); return ext.toLowerCase(); } public boolean tryLoadThumb(String ext) { File thumbFile = getThumbFilePath(ext); if (thumbFile.exists()){ if (!ext.equals("ppm")) { return true; } else return true; } return false; } public File getThumbFilePath( String ext){ File f = new File(file.getParent() + "/.thumb"); if (!f.exists()) f.mkdir(); String fname = file.getName(); if (!ext.isEmpty()) return new File(f, fname + "." + ext); else return new File(f, fname); } public void saveThumb(PtpBuffer data, boolean fromSdram){ Bitmap bmp = null; switch(objectInfo.objectFormatCode){ case PtpObjectInfo.EXIF_JPEG: bmp = BitmapFactory.decodeByteArray(data.data(), 12, data.data().length - 12); break; case PtpObjectInfo.Undefined: if (fromSdram) // if from sdram the the thumb is in raw format bmp = createThumbFromRaw(data); else bmp = BitmapFactory.decodeByteArray(data.data(), 12, data.data().length - 12); break; } if (bmp != null) { FileOutputStream fOut; try { fOut = new FileOutputStream(getThumbFilePath("jpg")); bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut); fOut.flush(); fOut.close(); bmp.recycle(); } catch (Exception e) { } } } public void deleteImage(){ if (file.exists()) file.delete(); File tf = getThumbFilePath("png"); if (tf.exists()) tf.delete(); tf = getThumbFilePath("jpg"); if (tf.exists()) tf.delete(); } private Bitmap createThumbFromRaw(PtpBuffer data){ int stride = ((160 * 24 + 25) & ~25) / 8; int[] colors = createColors(160,120,stride, data); return Bitmap.createBitmap(colors, 0, stride, 160, 120, Bitmap.Config.ARGB_8888); } private static int[] createColors(int width, int height, int stride, PtpBuffer data) { data.parse(); int[] colors = new int[stride * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int r = data.nextU8(); int g = data.nextU8(); int b = data.nextU8(); int a = 255; colors[y * stride + x] = (a << 24) | (r << 16) | (g << 8) | b; } } return colors; } // public boolean savePictureData(byte[] data){ // if (file != null){ // OutputStream out = null; // try { // out = new BufferedOutputStream(new FileOutputStream(file, false)); // out.write(data); // return true; // } catch (Exception e) { // Log.d(TAG, "File open error"); // return false; // } // finally { // if (out != null) // try { // out.close(); // } catch (IOException e) { // Log.d(TAG, "Error closing stream"); // } // } // } // else { // Log.d(TAG, "Error file name not set!"); // 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 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
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
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 java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import android.util.Log; public class PtpCommand implements Callable<PtpCommand> { private static String TAG = "PtpCommand"; public interface OnCommandFinishedListener { public void onCommandFinished(PtpCommand command); } private OnCommandFinishedListener _cmdFinishedListener = null; private int mCommandCode; protected ArrayList<Integer> mParams; private int mSessionId = 0; private boolean mHasSessionId = false; private PtpBuffer mBuffer; private byte[] mCommandData = null; private boolean mHasSendData = false; private PtpCommunicatorBase mCommunicator; private IPtpCommandFinalProcessor mFinalProcessor = null; private String mNotificationMsg; public int getCommandCode(){ return mCommandCode; } public IPtpCommandFinalProcessor getFinalProcessor(){ return mFinalProcessor; } public ArrayList<Integer> getParams(){ return mParams; } public int getSssionId(){ return mSessionId; } public boolean getHasSessionId(){ return mHasSessionId; } public boolean getHasSendData(){ return mHasSendData; } public PtpCommunicatorBase getCommunicator(){ return mCommunicator; } public String getNotificatinMsg(){ return mNotificationMsg; } public PtpCommand addParam(int param) { mParams.add(param); return this; } public PtpCommand setCommandData(byte[] commandData){ mCommandData = commandData; mHasSendData = true; return this; } public PtpCommand setOnCommandFinishedListener(OnCommandFinishedListener listener){ _cmdFinishedListener = listener; return this; } public PtpCommand setFinalProcessor(IPtpCommandFinalProcessor processor){ mFinalProcessor = processor; return this; } public FutureTask<PtpCommand> getTask(PtpCommunicatorBase communicator){ mCommunicator = communicator; return new FutureTask<PtpCommand>(this); } public PtpCommand(int commandCode){ mCommandCode = commandCode; mParams = new ArrayList<Integer>(); mBuffer = new PtpBuffer(); } public PtpCommand(String notification){ mNotificationMsg = notification; mCommandCode = 0; } public PtpCommand call() throws Exception { //Log.d(TAG, "Before sending command: " + _communicator); try { mCommunicator.processCommand(this); } catch (Exception e) { Log.d(TAG, e.getMessage()); throw e; } if (_cmdFinishedListener != null) _cmdFinishedListener.onCommandFinished(this); //Log.d(TAG, String.format("Command finished: %#04x", _commandCode)); return this; } protected byte[] getCommandPacket(int sessionId){ mSessionId = sessionId; mHasSessionId = true; int bufLen = 12 + (4 * mParams.size()); byte[] data = new byte[bufLen]; mBuffer.wrap(data); mBuffer.put32(bufLen); // size of the packet mBuffer.put16(1); // this is a command packet mBuffer.put16(mCommandCode); // command code mBuffer.put32(mSessionId); // session id for(int i = 0; i < mParams.size(); i++){ mBuffer.put32(mParams.get(i)); } return data; } protected byte[] getCommandDataPacket(){ if (mHasSessionId && mHasSendData){ mBuffer.wrap(new byte[12 + mCommandData.length]); mBuffer.put32(mBuffer.length()); // size will be later set; mBuffer.put16(2); // this is a data packet mBuffer.put16(mCommandCode); // the command code mBuffer.put32(mSessionId); // session id // copy the data byte[] to the packet System.arraycopy(mCommandData, 0, mBuffer.data(), 12, mCommandData.length); return mBuffer.data(); } else return null; } private boolean mHasData = false; private boolean mHasResponse = false; private PtpBuffer mIncomingData = null; private PtpBuffer mIncomingResponse = null; private boolean _needMoreBytes = false; private int _bytesCount = 0; private int _packetLen = 0; private byte[] _tmpData = null; public boolean hasData(){ return mHasData; } public boolean hasResponse(){ return mHasResponse; } public boolean isResponseOk(){ return mHasResponse ? mIncomingResponse.getPacketCode() == PtpResponse.OK : false; } public int getResponseCode() { return mHasResponse ? mIncomingResponse.getPacketCode() : 0; } public boolean isDataOk(){ return mHasData ? isResponseOk() : false; } public PtpBuffer incomingData(){ return mIncomingData; } public PtpBuffer incomingResponse(){ return mIncomingResponse; } public int responseParam(){ if (mHasResponse){ mIncomingResponse.parse(); return mIncomingResponse.nextS32(); } return 0; } protected boolean newPacket(byte[] packet, int size){ if (_needMoreBytes){ System.arraycopy(packet, 0, _tmpData, _bytesCount, size); _bytesCount += size; if (_bytesCount >= _packetLen){ _needMoreBytes = false; processPacket(); return false; } else return true; } else { mBuffer.wrap(packet); _packetLen = mBuffer.getPacketLength(); int packetType = mBuffer.getPacketType(); switch(packetType){ case 2: // data mIncomingData = new PtpBuffer(new byte[_packetLen]); _tmpData = mIncomingData.data(); break; case 3: // response mIncomingResponse = new PtpBuffer(new byte[_packetLen]); _tmpData = mIncomingResponse.data(); break; } System.arraycopy(packet, 0, _tmpData, 0, size); if (_packetLen > size) {// we need more bytes _needMoreBytes = true; _bytesCount = size; return true; } else { processPacket(); return false; } } } protected void processPacket(){ mBuffer.wrap(_tmpData); switch (mBuffer.getPacketType()) { case 2: //Log.d(TAG, "--- Incoming data packet"); mHasData = true; break; case 3: //Log.d(TAG, "--- Incoming response packet"); mHasResponse = true; //Log.d(TAG, "--- Response code " + Integer.toHexString(_incomingResponse.getPacketCode())); break; default: break; } } private void reset(){ mHasSessionId = false; mHasData = false; mHasResponse = false; _needMoreBytes = false; mIncomingData = null; mIncomingResponse = null; _tmpData = null; } public boolean weFinished() { boolean result = doFinalProcessing(); if (!result){ // we finished } else { // we need another run, reset evrything reset(); } return result; } protected boolean doFinalProcessing(){ return mFinalProcessor == null ? false : mFinalProcessor.doFinalProcessing(this); } public static final int GetDeviceInfo = 0x1001; public static final int OpenSession = 0x1002; public static final int CloseSession = 0x1003; public static final int GetStorageIDs = 0x1004; public static final int GetStorageInfo = 0x1005; public static final int GetNumObjects = 0x1006; public static final int GetObjectHandles = 0x1007; public static final int GetObjectInfo = 0x1008; public static final int GetObject = 0x1009; public static final int GetThumb = 0x100a; public static final int DeleteObject = 0x100b; public static final int SendObjectInfo = 0x100c; public static final int SendObject = 0x100d; public static final int InitiateCapture = 0x100e; public static final int FormatStore = 0x100f; public static final int ResetDevice = 0x1010; public static final int SelfTest = 0x1011; public static final int SetObjectProtection = 0x1012; public static final int PowerDown = 0x1013; public static final int GetDevicePropDesc = 0x1014; public static final int GetDevicePropValue = 0x1015; public static final int SetDevicePropValue = 0x1016; public static final int ResetDevicePropValue = 0x1017; public static final int TerminateOpenCapture = 0x1018; public static final int MoveObject = 0x1019; public static final int CopyObject = 0x101a; public static final int GetPartialObject = 0x101b; public static final int InitiateOpenCapture = 0x101c; public static final int InitiateCaptureRecInSdram = 0x90c0; public static final int AfDrive = 0x90c1; public static final int ChangeCameraMode = 0x90c2; public static final int DeleteImagesInSdram = 0x90c3; public static final int GetLargeThumb = 0x90c4; public static final int GetEvent = 0x90c7; public static final int DeviceReady = 0x90c8; public static final int SetPreWbData = 0x90c9; public static final int GetVendorPropCodes = 0x90ca; public static final int AfAndCaptureRecInSdram = 0x90cb; public static final int GetPicCtrlData = 0x90cc; public static final int SetPicCtrlData = 0x90cd; public static final int DeleteCustomPicCtrl = 0x90ce; public static final int GetPicCtrlCapability = 0x90cf; public static final int GetPreviewImage = 0x9200; public static final int StartLiveView = 0x9201; public static final int EndLiveView = 0x9202; public static final int GetLiveViewImage = 0x9203; public static final int MfDrive = 0x9204; public static final int ChangeAfArea = 0x9205; public static final int AfDriveCancel = 0x9206; public static final int InitiateCaptureRecInMedia = 0x9207; public static final int StartMovieRecInCard = 0x920a; public static final int EndMovieRec = 0x920b; public static final int MtpGetObjectPropsSupported = 0x9801; public static final int MtpGetObjectPropDesc = 0x9802; public static final int MtpGetObjectPropValue = 0x9803; public static final int MtpSetObjectPropValue = 0x9804; public static final int MtpGetObjPropList = 0x9805; }
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.ImageView; public class CheckableImageView extends ImageView implements Checkable { private boolean mChecked; private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; public CheckableImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public 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
/* <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.app.Fragment; import android.content.SharedPreferences; import android.graphics.PorterDuffColorFilter; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; public class LiveViewFragment extends DslrFragmentBase { private LvSurfaceBase mLvSurface; private boolean mIsAttached = false; private final static String TAG = "LiveViewFragment"; private LiveviewThread mLvThread = null; private ImageView mLvHistgoram, mOsdToggle; private int mHistogramMode = 0; //0 - no histogram, 1 - separate, 2 - one private PorterDuffColorFilter mColorFilterRed; private ImageView mFocsuToggle; private RelativeLayout mFocusLayout; private CheckableImageView mFocusMin, mFocusMax; private AutoRepeatImageView mFocusLeft, mFocusRight; private TextView mFocusStepDisplay; private SeekBar mFocusStepSeekBar; private int mFocusStep = 10; private int mOsdMode = 3; private boolean mFocusLayoutVisible = false; @Override public void onAttach(Activity activity) { mIsAttached = true; super.onAttach(activity); } @Override public void onDetach() { mIsAttached = false; super.onDetach(); } @Override public void onStart() { Log.d(TAG, "onStart"); super.onStart(); } @Override public void onResume() { Log.d(TAG, "onResume"); mLvThread = new LiveviewThread(); mLvThread.start(); super.onResume(); } @Override public void onPause() { Log.d(TAG, "onPause"); stopLvThread(); super.onPause(); } @Override public void onStop() { Log.d(TAG, "onStop"); super.onStop(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.liveview_fragment, container, false); mColorFilterRed = new PorterDuffColorFilter(getResources().getColor(R.color.Red), android.graphics.PorterDuff.Mode.SRC_ATOP); mLongPressTimeout = ViewConfiguration.getLongPressTimeout(); mScaledTouchSlop = ViewConfiguration.get(getActivity()).getScaledTouchSlop(); mVibrator = (Vibrator)getActivity().getSystemService("vibrator"); mScaledMaximumFlingVelocity = ViewConfiguration.get(getActivity()).getScaledMaximumFlingVelocity(); mOsdToggle = (ImageView)view.findViewById(R.id.lvosdtoggle); mFocsuToggle = (ImageView)view.findViewById(R.id.lvfocustoggle); mFocusLayout = (RelativeLayout)view.findViewById(R.id.lvfocuslayout); mFocusMin = (CheckableImageView)view.findViewById(R.id.lvfocusmin); mFocusMax = (CheckableImageView)view.findViewById(R.id.lvfocusmax); mFocusLeft = (AutoRepeatImageView)view.findViewById(R.id.lvfocusleft); mFocusRight = (AutoRepeatImageView)view.findViewById(R.id.lvfocusright); mFocusStepDisplay = (TextView)view.findViewById(R.id.lvfocusstep); mFocusStepSeekBar = (SeekBar)view.findViewById(R.id.lvfocusstepseekbar); mFocusLayout.setVisibility(View.GONE); mFocusStepSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mFocusStep = progress; mFocusStepDisplay.setText(Integer.toString(mFocusStep)); } } }); mFocusMin.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocusMin(); } }); mFocusMax.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocusMax(); } }); mFocusLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocus(1, mFocusStep); } }); mFocusRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { getPtpDevice().seekFocus(2, mFocusStep); } }); mFocsuToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mFocusLayoutVisible = !mFocusLayoutVisible; mFocusLayout.setVisibility(mFocusLayoutVisible ? View.VISIBLE : View.GONE); mFocsuToggle.setColorFilter(mFocusLayoutVisible ? mColorFilterRed : null); } }); mOsdToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mOsdMode == 0) mOsdMode = 3; else mOsdMode--; } }); mLvHistgoram = (ImageView)view.findViewById(R.id.lv_histogram); mLvHistgoram.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mHistogramMode == 2) mHistogramMode = 0; else mHistogramMode++; if (mHistogramMode > 0) mLvHistgoram.setColorFilter(mColorFilterRed); else mLvHistgoram.setColorFilter(null); } }); mLvSurface = (LvSurfaceBase)view.findViewById(R.id.lvsurface); mLvSurface.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (getIsPtpDeviceInitialized()){ final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(event); switch (action) { case MotionEvent.ACTION_DOWN: v.postDelayed(mLongPressRunnable, mLongPressTimeout); mDownX = x; mDownY = y; calculateMfDriveStep(v.getHeight(), y); break; case MotionEvent.ACTION_MOVE: { switch(mMode) { case TOUCH: 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 = TouchMode.PAN; } break; case PAN: break; case LVZOOM: int mdy = Math.round(((x - mDownX) / v.getWidth()) * 10); if (mdy > mZoomY){ zoomLiveView(true); } else if (mdy < mZoomY){ zoomLiveView(false); } mZoomY = mdy; break; case LVFOCUSSTART: Log.d(TAG, "Focus start"); getPtpDevice().seekFocusMin(); mMode = TouchMode.LVFOCUS; break; case LVFOCUSEND: Log.d(TAG, "Focus end"); getPtpDevice().seekFocusMax(); mMode = TouchMode.LVFOCUS; break; case LVFOCUS: // int focusValue = Math.round((_dslrHelper.getPtpService().getPreferences().mFocusMax * x) / v.getWidth()); // _dslrHelper.getPtpService().seekFocus(focusValue); break; } break; } case MotionEvent.ACTION_UP: switch(mMode) { case LVZOOM: break; case LVFOCUS: break; case PAN: if ((x - mDownX) > 200){ getPtpDevice().initiateCaptureCmd(); Log.d(TAG, "Pan left to right"); } // else if ((mDownX - x) > 200) { // _dslrHelper.getPtpService().initiateCaptureRecInSdramCmd(); // Log.d(TAG, "Pan right to lef"); // } else if ((y - mDownY) > 200) { if (getPtpDevice().getIsMovieRecordingStarted()) getPtpDevice().stopMovieRecCmd(); else getPtpDevice().startMovieRecCmd(); Log.d(TAG, "Pan top to bottom"); } // else if ((mDownY - y) > 200) { // Log.d(TAG, "Pan bottom to top"); // } // // mVelocityTracker.computeCurrentVelocity(1000, mScaledMaximumFlingVelocity); break; case TOUCH: lvAfx = x; lvAfy = y; long currentTime = System.currentTimeMillis(); if ((currentTime - lastTime) < 200) { lastTime = -1; v.removeCallbacks(mSingleTapRunnable); // lvSurfaceDoubleTap(); } else { lastTime = currentTime; v.postDelayed(mSingleTapRunnable, 200); } break; } mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = TouchMode.TOUCH; break; default: mVelocityTracker.recycle(); mVelocityTracker = null; v.removeCallbacks(mLongPressRunnable); mMode = TouchMode.TOUCH; break; } } return true; } }); return view; } public enum TouchMode { TOUCH, PAN, LVZOOM, LVFOCUS, LVFOCUSSTART, LVFOCUSEND } private long lastTime = -1; private int mfDriveStep = 200; /** Time of tactile feedback vibration when entering zoom mode */ private static final long VIBRATE_TIME = 50; /** Current listener mode */ private TouchMode mMode = TouchMode.TOUCH; /** X-coordinate of latest down event */ private float mDownX; /** Y-coordinate of latest down event */ private float mDownY; private int mZoomY; private float focusX; /** Velocity tracker for touch events */ private VelocityTracker mVelocityTracker; /** Distance touch can wander before we think it's scrolling */ private int mScaledTouchSlop; /** Duration in ms before a press turns into a long press */ private int mLongPressTimeout; /** Vibrator for tactile feedback */ private Vibrator mVibrator; /** Maximum velocity for fling */ private int mScaledMaximumFlingVelocity; private boolean mLiveViewNeedFocusChanged = false; private Object _syncRoot = new Object(); private float lvAfx, lvAfy; private final Runnable mLongPressRunnable = new Runnable() { public void run() { if (mDownY < 100) { mMode = TouchMode.LVZOOM; mZoomY = 0; mVibrator.vibrate(VIBRATE_TIME); } else { if (mDownX < 150) mMode = TouchMode.LVFOCUSSTART; else if (mDownX > (mLvSurface.getWidth() - 150)) mMode = TouchMode.LVFOCUSEND; else mMode = TouchMode.LVFOCUS; focusX = mDownX; mVibrator.vibrate(VIBRATE_TIME); } } }; private final Runnable mSingleTapRunnable = new Runnable() { public void run() { synchronized (_syncRoot) { mLiveViewNeedFocusChanged = true; } } }; private void calculateMfDriveStep(int height, float y){ float inv = height - y; float step = inv * 0.205f; int testy = Math.round(inv * step); if (testy < 1) testy = 1; else if (testy > 32767) testy = 32767; mfDriveStep = testy; } private void zoomLiveView(boolean up){ IDslrActivity activity = (IDslrActivity)getActivity(); if (activity != null) activity.zoomLiveView(up); } public synchronized void updateLiveViewImage(PtpLiveViewObject lvo) { lvo.parse(mLvSurface.getFrameWidth(), mLvSurface.getFrameHeight()); if (mLiveViewNeedFocusChanged){ mLiveViewNeedFocusChanged = false; float x = ((lvAfx / lvo.sDw) / lvo.ox) + lvo.dLeft; float y = ((lvAfy / lvo.sDh) / lvo.oy) + lvo.dTop; getPtpDevice().changeAfAreaCmd((int)x, (int)y); } LvSurfaceHelper helper = new LvSurfaceHelper(lvo, getPtpDevice().getPtpProperty(PtpProperty.LiveViewImageZoomRatio), mOsdMode); helper.mHistogramEnabled = mHistogramMode > 0; helper.mHistogramSeparate = mHistogramMode == 1; mLvSurface.processLvObject(helper); } @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 LiveviewStop: if (mLvThread != null) mLvThread.interrupt(); break; } } private void stopLvThread() { Log.d(TAG, "Stop LV thread"); if (mLvThread != null) { mLvThread.setIsEnabled(false); mLvThread.interrupt(); } } private class LiveviewThread extends ThreadBase { private Boolean mIsEnabled = true; public synchronized void setIsEnabled(boolean isEnabled) { mIsEnabled = true; } public LiveviewThread() { mSleepTime = 100; } @Override public void codeToExecute() { try{ if (!interrupted()) { if (mIsEnabled) { PtpLiveViewObject lvo = getPtpDevice().getLiveViewImage(); if (lvo != null) updateLiveViewImage(lvo); else { Log.d(TAG, "null lvo"); this.interrupt(); } } } } catch (Exception e) { Log.d(TAG, "Live view thread exception " + e.getMessage()); } } } @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.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; public class RightFragmentLv extends DslrFragmentBase { private static final String TAG = "RightFragmentLv"; private LinearLayout mRightLvLayout; private CheckableImageView mZoomIn, mZoomOut, mLvFocusMode, mMovieRecordWithVoice, mMovieRecordMicrophoneLevel, mMovieRecordSize; private TextView mVideoMode, mAfAtLiveView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_right_lv, container, false); mRightLvLayout = (LinearLayout)view.findViewById(R.id.right_lv_layout); mZoomIn = (CheckableImageView)view.findViewById(R.id.lvzoomin); mZoomOut = (CheckableImageView)view.findViewById(R.id.lvzoomout); mLvFocusMode = (CheckableImageView)view.findViewById(R.id.lvfocusmode); mAfAtLiveView = (TextView)view.findViewById(R.id.afatliveview); mVideoMode = (TextView)view.findViewById(R.id.videomode); mMovieRecordSize = (CheckableImageView)view.findViewById(R.id.movierecordsize); mMovieRecordWithVoice = (CheckableImageView)view.findViewById(R.id.movierecordwithvoice); mMovieRecordMicrophoneLevel = (CheckableImageView)view.findViewById(R.id.movierecordmicrophonelevel); mZoomIn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getDslrActivity() != null) getDslrActivity().zoomLiveView(true); } }); mZoomOut.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (getDslrActivity() != null) getDslrActivity().zoomLiveView(false); } }); mLvFocusMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.AfAtLiveView, "Select LV Focus Mode", null); } }); mVideoMode.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.VideoMode, "Select Video mode", null); } }); mMovieRecordSize.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordScreenSize, getMovieRecordSizeOffset(), "Select Movie recording screen size", null); } }); mMovieRecordWithVoice.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordWithVoice, "Select Movie voice recording mode", null); } }); mMovieRecordMicrophoneLevel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DslrHelper.getInstance().createDslrDialog(getActivity(), PtpProperty.MovieRecordMicrophoneLevel, "Select Movie recording Microphone level", 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(); } private int getMovieRecordSizeOffset() { Integer offset = 0; switch(getPtpDevice().getProductId()) { case 0x0428: case 0x0429: PtpProperty vMode = getPtpDevice().getPtpProperty(PtpProperty.VideoMode); if (vMode != null) { if ((Integer)vMode.getValue() == 1) offset = 16; } break; default: break; } return offset; } @Override protected void internalInitFragment() { if (getIsPtpDeviceInitialized()) { initializePtpPropertyView(mLvFocusMode, getPtpDevice().getPtpProperty(PtpProperty.AfAtLiveView)); initializePtpPropertyView(mAfAtLiveView, getPtpDevice().getPtpProperty(PtpProperty.AfModeAtLiveView)); initializePtpPropertyView(mVideoMode, getPtpDevice().getPtpProperty(PtpProperty.VideoMode)); initializePtpPropertyView(mMovieRecordSize, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordScreenSize)); initializePtpPropertyView(mMovieRecordWithVoice, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordWithVoice)); initializePtpPropertyView(mMovieRecordMicrophoneLevel, getPtpDevice().getPtpProperty(PtpProperty.MovieRecordMicrophoneLevel)); } } @Override protected void internalPtpPropertyChanged(PtpProperty property) { if (property != null) { switch (property.getPropertyCode()) { case PtpProperty.AfAtLiveView: DslrHelper.getInstance().setDslrImg(mLvFocusMode, property); break; case PtpProperty.AfModeAtLiveView: DslrHelper.getInstance().setDslrTxt(mAfAtLiveView, property); break; case PtpProperty.VideoMode: DslrHelper.getInstance().setDslrTxt(mVideoMode, property); break; case PtpProperty.MovieRecordScreenSize: DslrHelper.getInstance().setDslrImg(mMovieRecordSize,getMovieRecordSizeOffset(), property); break; case PtpProperty.MovieRecordWithVoice: DslrHelper.getInstance().setDslrImg(mMovieRecordWithVoice, property); break; case PtpProperty.MovieRecordMicrophoneLevel: DslrHelper.getInstance().setDslrImg(mMovieRecordMicrophoneLevel, property); break; } } } @Override protected void ptpDeviceEvent(PtpDeviceEvent event, Object data) { switch(event) { case BusyBegin: DslrHelper.getInstance().enableDisableControls(mRightLvLayout, false); break; case BusyEnd: DslrHelper.getInstance().enableDisableControls(mRightLvLayout, true); break; } } @Override protected void internalSharedPrefsChanged(SharedPreferences prefs, String key) { // TODO Auto-generated method stub } }
Java