diff --git a/.idea/artifacts/docviewer.xml b/.idea/artifacts/docviewer.xml index 0510fb1..bb12d2a 100644 --- a/.idea/artifacts/docviewer.xml +++ b/.idea/artifacts/docviewer.xml @@ -1,10 +1,9 @@ - + $PROJECT_DIR$/out/artifacts/docviewer - + - @@ -12,12 +11,17 @@ + + + + + diff --git a/.idea/compiler.xml b/.idea/compiler.xml index a1b41c5..4088721 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -14,6 +14,9 @@ + + + diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..f6e673a --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,3 @@ + + + diff --git a/.idea/dictionaries/icode.xml b/.idea/dictionaries/icode.xml index 13b2b18..cc38639 100644 --- a/.idea/dictionaries/icode.xml +++ b/.idea/dictionaries/icode.xml @@ -3,6 +3,7 @@ conf docviewer + jdbc \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 25c03e8..e448dc5 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -1,7 +1,7 @@ - + diff --git a/.idea/libraries/berby.xml b/.idea/libraries/berby.xml new file mode 100644 index 0000000..4329159 --- /dev/null +++ b/.idea/libraries/berby.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/j2ee1_4.xml b/.idea/libraries/j2ee1_4.xml deleted file mode 100644 index 3a98f19..0000000 --- a/.idea/libraries/j2ee1_4.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/j2ee6.xml b/.idea/libraries/j2ee6.xml new file mode 100644 index 0000000..6e49801 --- /dev/null +++ b/.idea/libraries/j2ee6.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index b4e74ee..046cd3d 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,8 +1,5 @@ - - @@ -24,12 +21,37 @@ diff --git a/.idea/workspace.xml b/.idea/workspace.xml index f8c2ad7..5b67f6b 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,5 +1,10 @@ + + + + + - + @@ -29,27 +34,15 @@ + + + + - - - - - + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + @@ -104,7 +265,205 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -124,21 +483,21 @@ @@ -157,6 +516,11 @@ + + @@ -190,8 +554,8 @@ - - + + @@ -208,16 +572,16 @@ - + - + - - - - + + + + - + - + + + - + - + - - + + + + + + + + - - - - + + + + + + + + + + + + + + - + - - + + + - - - - - - + - - - + - - + + - + - - - - + + + + + - - + + + - - - + + + + + - - + + + + - - + + + + file://$PROJECT_DIR$/docviewerflex/src/com/devaldi/streaming/AVM2Loader.as + 237 + + + file://$PROJECT_DIR$/docviewerflex/src/com/devaldi/controls/flexpaper/Viewer.as + 509 + + + file://$PROJECT_DIR$/docviewerflex/src/com/devaldi/streaming/DupImage.as + 197 + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - + - + + + - - - - - - - - - - + - + - - - - + + @@ -1362,7 +1798,9 @@ - + + false + docviewer - Android + Web - 1.5 + 1.6 - docviewerflex + docviewer @@ -1436,7 +1873,7 @@ - j2ee1.4 + berby diff --git a/docviewer/src/com/log4ic/dao/IDocumentRelationDao.java b/docviewer/src/com/log4ic/dao/IDocumentRelationDao.java new file mode 100644 index 0000000..292444d --- /dev/null +++ b/docviewer/src/com/log4ic/dao/IDocumentRelationDao.java @@ -0,0 +1,20 @@ +package com.log4ic.dao; + +import com.log4ic.entity.DocumentRelation; + +import javax.naming.NamingException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-23 + * @time: 上午2:36 + */ +public interface IDocumentRelationDao { + void save(DocumentRelation relation) throws NamingException, SQLException; + List getAllRelation() throws NamingException, SQLException; + DocumentRelation getRelation(int id) throws NamingException, SQLException; + DocumentRelation getRelationByLocation(String location) throws NamingException, SQLException ; +} diff --git a/docviewer/src/com/log4ic/dao/impl/DocumentRelationDao.java b/docviewer/src/com/log4ic/dao/impl/DocumentRelationDao.java new file mode 100644 index 0000000..1227661 --- /dev/null +++ b/docviewer/src/com/log4ic/dao/impl/DocumentRelationDao.java @@ -0,0 +1,105 @@ +package com.log4ic.dao.impl; + +import com.log4ic.dao.IDocumentRelationDao; +import com.log4ic.entity.DocumentRelation; +import com.log4ic.utils.dao.DocViewerJdbcSupport; +import javolution.util.FastList; +import javolution.util.FastMap; + +import javax.naming.NamingException; +import java.sql.*; +import java.util.List; +import java.util.Map; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-23 + * @time: 上午2:37 + */ +public class DocumentRelationDao extends DocViewerJdbcSupport implements IDocumentRelationDao { + public void save(DocumentRelation relation) throws NamingException, SQLException { + + Map params = new FastMap(); + params.put(1, relation.getFileName()); + params.put(2, relation.getLocation()); + params.put(3, relation.getCreateDate()); + + this.executeUpdate("insert into documentrelation(filename,location,createdate) values (?,?,?)", params); + + } + + public List getAllRelation() throws NamingException, SQLException { + Connection conn = this.getDocviewerConnection(); + PreparedStatement stmt = null; + List relationList = new FastList(); + try { + stmt = conn.prepareStatement("select * from documentrelation order by createdate desc"); + ResultSet resultSet = stmt.executeQuery(); + while (resultSet.next()) { + com.log4ic.entity.DocumentRelation relation = new DocumentRelation(); + relation.setFileName(resultSet.getString("filename")); + relation.setLocation(resultSet.getString("location")); + relation.setId(resultSet.getInt("id")); + relation.setCreateDate(resultSet.getTimestamp("createDate")); + relationList.add(relation); + } + + } finally { + if (stmt != null) { + stmt.close(); + } + } + return relationList; + } + + public DocumentRelation getRelation(int id) throws NamingException, SQLException { + Connection conn = this.getDocviewerConnection(); + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement("select * from documentrelation where id = ?"); + stmt.setInt(1, id); + ResultSet resultSet = stmt.executeQuery(); + if (resultSet.next()) { + com.log4ic.entity.DocumentRelation relation = new DocumentRelation(); + relation.setFileName(resultSet.getString("filename")); + relation.setLocation(resultSet.getString("location")); + relation.setId(resultSet.getInt("id")); + relation.setCreateDate(resultSet.getTimestamp("createDate")); + return relation; + } + + } finally { + if (stmt != null) { + stmt.close(); + } + conn.close(); + } + + return null; + } + + public DocumentRelation getRelationByLocation(String location) throws NamingException, SQLException { + Connection conn = this.getDocviewerConnection(); + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement("select * from documentrelation where location = ?"); + stmt.setString(1, location); + ResultSet resultSet = stmt.executeQuery(); + if (resultSet.next()) { + com.log4ic.entity.DocumentRelation relation = new com.log4ic.entity.DocumentRelation(); + relation.setFileName(resultSet.getString("filename")); + relation.setLocation(resultSet.getString("location")); + relation.setId(resultSet.getInt("id")); + relation.setCreateDate(resultSet.getTimestamp("createDate")); + return relation; + } + + } finally { + if (stmt != null) { + stmt.close(); + } + conn.close(); + } + return null; + } +} diff --git a/docviewer/src/com/log4ic/entity/DocAttachment.java b/docviewer/src/com/log4ic/entity/DocAttachment.java index c72d97e..a0e6a03 100644 --- a/docviewer/src/com/log4ic/entity/DocAttachment.java +++ b/docviewer/src/com/log4ic/entity/DocAttachment.java @@ -1,6 +1,7 @@ package com.log4ic.entity; -import com.log4ic.utils.FileUtils; +import com.log4ic.enums.Permissions; +import com.log4ic.utils.io.FileUtils; import java.io.File; import java.io.FileInputStream; @@ -14,12 +15,12 @@ */ public class DocAttachment implements IDocAttachment { - String name; - Long contentSize; - Integer pageCount; - String digest; - String fileType; - InputStream contentStream; + private String name; + private Long contentSize; + private Integer pageCount; + private String fileType; + private InputStream contentStream; + private Permissions permissions; public DocAttachment(File file) { this.name = FileUtils.getFilePrefix(file); @@ -45,10 +46,6 @@ public Integer getPageCount() { return pageCount; } - public String getDigest() { - return digest; - } - public String getFileType() { return fileType; } @@ -56,4 +53,32 @@ public String getFileType() { public InputStream getContentStream() { return contentStream; } + + public Permissions getPermissions() { + return permissions; + } + + public void setName(String name) { + this.name = name; + } + + public void setContentSize(Long contentSize) { + this.contentSize = contentSize; + } + + public void setPageCount(Integer pageCount) { + this.pageCount = pageCount; + } + + public void setFileType(String fileType) { + this.fileType = fileType; + } + + public void setContentStream(InputStream contentStream) { + this.contentStream = contentStream; + } + + public void setPermissions(Permissions permissions) { + this.permissions = permissions; + } } diff --git a/docviewer/src/com/log4ic/entity/DocumentRelation.java b/docviewer/src/com/log4ic/entity/DocumentRelation.java new file mode 100644 index 0000000..6d283d3 --- /dev/null +++ b/docviewer/src/com/log4ic/entity/DocumentRelation.java @@ -0,0 +1,59 @@ +package com.log4ic.entity; + +import com.log4ic.utils.dao.AbstractEntitySupport; + +import javax.annotation.Generated; +import javax.persistence.*; +import java.sql.Timestamp; +import java.util.Date; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-23 + * @time: 上午2:55 + */ +@Entity +public class DocumentRelation extends AbstractEntitySupport { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column + private int id; + @Column(nullable = false) + private String fileName; + @Column(length = 2000, nullable = false) + private String location; + @Column(nullable = false) + private Timestamp createDate; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public Timestamp getCreateDate() { + return createDate; + } + + public void setCreateDate(Timestamp createDate) { + this.createDate = createDate; + } +} diff --git a/docviewer/src/com/log4ic/service/DocAttachmentService.java b/docviewer/src/com/log4ic/service/DocAttachmentService.java index 1df9c0d..335e6f0 100644 --- a/docviewer/src/com/log4ic/service/DocAttachmentService.java +++ b/docviewer/src/com/log4ic/service/DocAttachmentService.java @@ -1,12 +1,16 @@ package com.log4ic.service; +import com.log4ic.dao.impl.DocumentRelationDao; import com.log4ic.entity.DocAttachment; +import com.log4ic.entity.DocumentRelation; import com.log4ic.entity.IDocAttachment; import com.log4ic.enums.Permissions; import com.log4ic.services.IAttachmentService; +import javax.naming.NamingException; import javax.servlet.http.HttpServletRequest; import java.io.File; +import java.sql.SQLException; /** * @author: 张立鑫 @@ -14,10 +18,23 @@ * @date: 11-10-12 下午7:08 */ public class DocAttachmentService implements IAttachmentService { + + private DocumentRelationDao relationDao = new DocumentRelationDao(); + public IDocAttachment getDocAttachmentById(int id) { //TODO 获取文档 - File f = new File(this.getClass().getClassLoader().getResource("test.pdf").getPath()); - return new DocAttachment(f); + try { + DocumentRelation relation = relationDao.getRelation(id); + DocAttachment docAttachment = new DocAttachment(new File(relation.getLocation())); + docAttachment.setName(relation.getFileName()); + return docAttachment; + } catch (NamingException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } + + return null; } public Permissions getDocPermissionsById(int id, HttpServletRequest request) { diff --git a/docviewer/src/com/log4ic/servlet/DocViewerServlet.java b/docviewer/src/com/log4ic/servlet/DocViewerServlet.java index 1357281..91065d7 100644 --- a/docviewer/src/com/log4ic/servlet/DocViewerServlet.java +++ b/docviewer/src/com/log4ic/servlet/DocViewerServlet.java @@ -1,7 +1,13 @@ package com.log4ic.servlet; import com.log4ic.DocViewer; +import com.log4ic.dao.impl.DocumentRelationDao; +import com.log4ic.entity.DocumentRelation; import com.log4ic.enums.Permissions; +import com.log4ic.utils.io.Uploader; +import com.log4ic.utils.io.UploaderFile; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -11,6 +17,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; +import java.sql.*; +import java.util.*; /** * @author: 张立鑫 @@ -22,6 +30,8 @@ public class DocViewerServlet extends HttpServlet { public void getDocInfo(HttpServletRequest request, HttpServletResponse response) { + PrintWriter writer = null; + try { String id = request.getParameter("docId"); LOGGER.info("请求文档信息 ID:" + id); @@ -44,8 +54,9 @@ public void getDocInfo(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json"); response.setStatus(202); + response.setHeader("Keep-Alive", "600"); response.flushBuffer(); - PrintWriter writer = response.getWriter(); + writer = response.getWriter(); writer.flush(); @@ -72,11 +83,14 @@ public void getDocInfo(HttpServletRequest request, HttpServletResponse response) } else { writer.write("{\"uri\":\"" + docUri + "\",\"permissions\":" + permissions.ordinal() + "}"); } - writer.flush(); - writer.close(); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error(e); response.setStatus(404); + } finally { + if (writer != null) { + writer.flush(); + writer.close(); + } } } @@ -119,7 +133,7 @@ public void getDoc(HttpServletRequest request, HttpServletResponse response) { outp = response.getOutputStream(); if (DocViewer.isSplitPage()) { if (DocViewer.isEncryption()) { - LOGGER.info("解密文档..."); + LOGGER.info("加密文档..."); if (DocViewer.isDynamicKey()) { byte[] page = DocViewer.encryptToBytes(docId, docPage, secretKey); in = new ByteArrayInputStream(page); @@ -132,7 +146,7 @@ public void getDoc(HttpServletRequest request, HttpServletResponse response) { } } else { if (DocViewer.isEncryption()) { - LOGGER.info("解密文档..."); + LOGGER.info("加密文档..."); if (DocViewer.isDynamicKey()) { byte[] page = DocViewer.encryptToBytes(docId, secretKey); in = new ByteArrayInputStream(page); @@ -156,13 +170,13 @@ public void getDoc(HttpServletRequest request, HttpServletResponse response) { } } catch (Exception ex) { response.setStatus(404); - ex.printStackTrace(); + LOGGER.error(ex); } finally { if (in != null) { try { in.close(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error(e); } in = null; } @@ -171,22 +185,62 @@ public void getDoc(HttpServletRequest request, HttpServletResponse response) { outp.flush(); outp.close(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error(e); } outp = null; } } } + private DocumentRelationDao relationDao = new DocumentRelationDao(); + + private void uploadFile(HttpServletRequest request, HttpServletResponse response) { + try { + List uploaderFileList = Uploader.getFileList(); + if (uploaderFileList.size() > 0) { + String path = this.getClass().getResource("/").getPath(); + for (UploaderFile file : uploaderFileList) { + File newFile = new File(path + File.separator + "documents" + File.separator + file.getName()); + FileUtils.copyFile(file, newFile); + DocumentRelation relation = new DocumentRelation(); + relation.setFileName(file.getUploadName()); + relation.setLocation(newFile.getPath()); + relation.setCreateDate(new Timestamp(System.currentTimeMillis())); + relationDao.save(relation); + if(DocViewer.isSupport(FilenameUtils.getExtension(file.getUploadName()))){ + relation = relationDao.getRelationByLocation(relation.getLocation()); + DocViewer.addConvertWorker(relation.getId()); + } + } + + response.sendRedirect("/continue.jsp"); + } + } catch (Exception e) { + LOGGER.error(e); + } finally { + } + } + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - LOGGER.info("DocViewer doGet:" + req.getContextPath() + "/docviewer/info"); if (req.getRequestURI().equals(req.getContextPath() + "/docviewer/info")) { + LOGGER.info("DocViewer doGet:" + req.getContextPath() + "/docviewer/info"); LOGGER.info("请求文档信..."); getDocInfo(req, resp); } else if (req.getRequestURI().equals(req.getContextPath() + "/docviewer")) { + LOGGER.info("DocViewer doGet:" + req.getContextPath() + "/docviewer"); LOGGER.info("加载文档..."); getDoc(req, resp); } } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getRequestURI().equals(req.getContextPath() + "/docviewer/upload")) { + LOGGER.info("DocViewer doPost:" + req.getContextPath() + "/docviewer/upload"); + LOGGER.info("上传文件..."); + uploadFile(req, resp); + } + } + } diff --git a/docviewer/src/com/log4ic/servlet/UploaderServlet.java b/docviewer/src/com/log4ic/servlet/UploaderServlet.java new file mode 100644 index 0000000..5f82b92 --- /dev/null +++ b/docviewer/src/com/log4ic/servlet/UploaderServlet.java @@ -0,0 +1,128 @@ +package com.log4ic.servlet; + +import com.log4ic.utils.io.Uploader; +import javolution.util.FastMap; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileUpload; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.util.List; +import java.util.Map; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-21 + * @time: 下午11:11 + */ +public class UploaderServlet extends HttpServlet { + private static final Log LOGGER = LogFactory.getLog(UploaderServlet.class); + + + private void uploadFile(HttpServletRequest request, HttpServletResponse response) { + + PrintWriter writer = null; + + //本次块大小 + int chunk = 0; + //总共块数 + int chunks = 0; + + // 代上传文件的File对象 + InputStream upload = null; + + //本次上传器的ID 作为临时目录的目录名称 + String uploaderId = null; + // 上传文件名 + String uploadFileName = null; + //文件唯一标识名称 + String name = null; + + try { + + if (request.getContentType() != null && request.getContentType().indexOf("multipart/form-data;") != -1) { + // Create a factory for disk-based file items + FileItemFactory factory = new DiskFileItemFactory(); + + // Create a new file upload handler + ServletFileUpload servletUpload = new ServletFileUpload(factory); + + // Parse the request + List items = servletUpload.parseRequest(request); + + Map map = new FastMap(); + for (FileItem item : items) { + if (item.isFormField()) { + map.put(item.getFieldName(), item.getString()); + } else { + if ("upload".equals(item.getFieldName())) { + upload = item.getInputStream(); + // 上传文件名 + uploadFileName = item.getName(); + } + } + } + try { + //本次块大小 + chunk = Integer.parseInt(map.get("chunk")); + //总共块数 + chunks = Integer.parseInt(map.get("chunks")); + } catch (Exception e) { + } + //本次上传器的ID 作为临时目录的目录名称 + uploaderId = map.get("uploaderId"); + + //文件唯一标识名称 + name = map.get("name"); + + } + + if (upload == null || + StringUtils.isBlank(uploaderId) || + StringUtils.isBlank(name) || + StringUtils.isBlank(uploadFileName)) { + response.setStatus(404); + return; + } + //分块上传 + String chunkSize = request.getHeader("chunkSize"); + int cSize = 0; + try { + cSize = StringUtils.isNotBlank(chunkSize) ? Integer.parseInt(chunkSize) : 0; + } catch (Exception e) { + } + if (!Uploader.saveFile(upload, uploaderId, name, chunks, chunk, cSize)) { + response.setStatus(404); + return; + } + + writer = response.getWriter(); + writer.print("{\"success\":true}"); + } catch (Exception e) { + LOGGER.error(e); + } finally { + if (writer != null) { + writer.flush(); + writer.close(); + } + } + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (req.getRequestURI().equals(req.getContextPath() + "/upload")) { + LOGGER.info("DocViewer doPost:" + req.getContextPath() + "/upload"); + LOGGER.info("上传文件..."); + uploadFile(req, resp); + } + } +} diff --git a/docviewer/src/com/log4ic/utils/dao/AbstractEntitySupport.java b/docviewer/src/com/log4ic/utils/dao/AbstractEntitySupport.java new file mode 100644 index 0000000..2799826 --- /dev/null +++ b/docviewer/src/com/log4ic/utils/dao/AbstractEntitySupport.java @@ -0,0 +1,9 @@ +package com.log4ic.utils.dao; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 上午5:18 + */ +public class AbstractEntitySupport extends DocViewerJdbcSupport { +} diff --git a/docviewer/src/com/log4ic/utils/dao/AbstractJdbcSupport.java b/docviewer/src/com/log4ic/utils/dao/AbstractJdbcSupport.java new file mode 100644 index 0000000..4fac8ed --- /dev/null +++ b/docviewer/src/com/log4ic/utils/dao/AbstractJdbcSupport.java @@ -0,0 +1,212 @@ +package com.log4ic.utils.dao; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.Logger; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.*; +import javax.sql.DataSource; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.sql.*; +import java.sql.Date; +import java.util.*; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-23 + * @time: 上午2:39 + */ +public abstract class AbstractJdbcSupport { + private Log logger = LogFactory.getLog(this.getClass()); + + protected DataSource getDataSource(String dataSourceName) throws NamingException { + Context initContext = new InitialContext(); + if (initContext == null) { + throw new NamingException(); + } + return (DataSource) initContext.lookup("java:comp/env/jdbc/" + dataSourceName); + } + + protected Connection getConnection(String dataSourceName) throws SQLException, NamingException { + DataSource dataSource = this.getDataSource(dataSourceName); + if (dataSource == null) { + return null; + } + return dataSource.getConnection(); + } + + protected int executeUpdate(String dataSourceName, String sql, Map params) throws SQLException, NamingException { + Connection conn = this.getConnection(dataSourceName); + if (conn == null) { + throw new SQLException(); + } + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement(sql); + if (params != null) { + for (Integer index : params.keySet()) { + stmt.setObject(index, params.get(index)); + } + } + int result = stmt.executeUpdate(); + conn.commit(); + return result; + } catch (Exception e) { + conn.rollback(); + logger.error(e); + } finally { + if (stmt != null) { + stmt.close(); + } + conn.close(); + } + return 0; + } + + + protected boolean execute(String dataSourceName, String sql, Map params) throws SQLException, NamingException { + Connection conn = this.getConnection(dataSourceName); + if (conn == null) { + throw new SQLException(); + } + PreparedStatement stmt = null; + try { + stmt = conn.prepareStatement(sql); + if (params != null) { + for (Integer index : params.keySet()) { + stmt.setObject(index, params.get(index)); + } + } + return stmt.execute(); + } finally { + if (stmt != null) { + stmt.close(); + } + conn.commit(); + conn.close(); + } + } + + protected boolean execute(String dataSourceName, String sql) throws SQLException, NamingException { + return this.execute(dataSourceName, sql, null); + } + + protected boolean hasTable(String dataSourceName, String schema, String name) { + //判断某一个表是否存在 + boolean result = false; + try { + DatabaseMetaData meta = this.getConnection(dataSourceName).getMetaData(); + ResultSet set = meta.getTables(null, schema, name.toUpperCase(), new String[]{"TABLE"}); + while (set.next()) { + result = true; + } + } catch (Exception eHasTable) { + System.err.println(eHasTable); + eHasTable.printStackTrace(); + } + return result; + } + + protected boolean hasTable(String dataSourceName, String name) { + return this.hasTable(dataSourceName, null, name); + } + + public String getTableName() { + String name = null; + + Class selfClass = this.getClass(); + Annotation tableAnnotation = selfClass.getAnnotation(Table.class); + if (tableAnnotation != null) { + try { + Table table = (Table) tableAnnotation.getClass().newInstance(); + name = table.name(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + if (StringUtils.isBlank(name)) { + name = selfClass.getSimpleName(); + } + return name; + } + + public boolean hasTable(String dataSourceName) { + + String name = this.getTableName(); + + return this.hasTable(dataSourceName, name); + } + + + public boolean createTable(String dataSourceName) throws NamingException, SQLException { + StringBuffer buffer = new StringBuffer("create table "); + buffer.append(this.getTableName()); + buffer.append("("); + Class selfClass = this.getClass(); + Field[] fields = selfClass.getDeclaredFields(); + if (fields.length == 0) { + return false; + } + boolean hasColumn = false; + for (Field field : fields) { + Column columnAnnotation = field.getAnnotation(Column.class); + Id idAnnotation = field.getAnnotation(Id.class); + GeneratedValue generatedValueAnnotation = field.getAnnotation(GeneratedValue.class); + if (columnAnnotation != null) { + hasColumn = true; + buffer.append(field.getName()); + buffer.append(" "); + String columnDefinition = columnAnnotation.columnDefinition(); + boolean isInt = false; + if (StringUtils.isNotBlank(columnDefinition)) { + buffer.append(columnDefinition); + } else { + Class fieldType = field.getType(); + if (fieldType.isInstance(0)) { + buffer.append("int "); + } else if (fieldType.getCanonicalName().equals("int")) { + buffer.append("int not null "); + isInt = true; + } else if (fieldType.isInstance("")) { + buffer.append("varchar"); + buffer.append("("); + buffer.append(columnAnnotation.length()); + buffer.append(") "); + } else if (fieldType.equals(Date.class)) { + buffer.append("date "); + } else if (fieldType.isInstance(new java.util.Date()) || fieldType.equals(Timestamp.class)) { + buffer.append("timestamp "); + } + } + + if (generatedValueAnnotation != null && generatedValueAnnotation.strategy() == GenerationType.AUTO) { + buffer.append("generated always as identity (start with 1, increment by 1) "); + } + + if (idAnnotation != null) { + buffer.append("primary key "); + } + + if (!columnAnnotation.nullable() && !isInt) { + buffer.append("not null"); + } + buffer.append(","); + } + } + if (!hasColumn) { + return hasColumn; + } + buffer.deleteCharAt(buffer.length() - 1); + + buffer.append(")"); + logger.info(buffer.toString().replace(" ", " ")); + return this.execute(dataSourceName, buffer.toString().replace(" ", " ")); + } +} diff --git a/docviewer/src/com/log4ic/utils/dao/DocViewerJdbcSupport.java b/docviewer/src/com/log4ic/utils/dao/DocViewerJdbcSupport.java new file mode 100644 index 0000000..6e3716e --- /dev/null +++ b/docviewer/src/com/log4ic/utils/dao/DocViewerJdbcSupport.java @@ -0,0 +1,50 @@ +package com.log4ic.utils.dao; + +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-23 + * @time: 上午2:48 + */ +public abstract class DocViewerJdbcSupport extends AbstractJdbcSupport { + private static final String DEFAULT_DATA_SOURCE = "docviewerDB"; + + protected DataSource getDocviewerDataSource() throws NamingException { + return super.getDataSource(DEFAULT_DATA_SOURCE); + } + + protected Connection getDocviewerConnection() throws NamingException, SQLException { + return super.getConnection(DEFAULT_DATA_SOURCE); + } + + protected int executeUpdate(String sql, Map params) throws SQLException, NamingException { + return super.executeUpdate(DEFAULT_DATA_SOURCE, sql, params); + } + + protected int executeUpdate(String sql) throws SQLException, NamingException { + return super.executeUpdate(DEFAULT_DATA_SOURCE, sql, null); + } + + protected boolean execute(String sql) throws SQLException, NamingException { + return super.execute(DEFAULT_DATA_SOURCE, sql, null); + } + + protected boolean execute(String sql, Map params) throws SQLException, NamingException { + return super.execute(DEFAULT_DATA_SOURCE, sql, params); + } + + public boolean hasTable() { + return super.hasTable(DEFAULT_DATA_SOURCE); + } + + + public boolean createTable() throws NamingException, SQLException { + return super.createTable(DEFAULT_DATA_SOURCE); + } +} diff --git a/docviewer/src/com/log4ic/utils/io/FileUploaderFilter.java b/docviewer/src/com/log4ic/utils/io/FileUploaderFilter.java new file mode 100644 index 0000000..effc77e --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/FileUploaderFilter.java @@ -0,0 +1,53 @@ +package com.log4ic.utils.io; + +import org.apache.commons.lang.StringUtils; + +import javax.servlet.*; +import java.io.File; +import java.io.IOException; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-21 + * @time: 下午9:11 + */ +public class FileUploaderFilter implements Filter { + + public void init(FilterConfig filterConfig) throws ServletException { + String tempDir = filterConfig.getInitParameter("tempDir"); + if (StringUtils.isBlank(tempDir)) { + tempDir = this.getClass().getResource("/").getFile(); + tempDir += "uploader" + File.separator + "tempDir"; + } else { + + } + Uploader.setTempDir(tempDir); + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { + + String uploaderId = request.getParameter("uploader"); + + if (StringUtils.isBlank(uploaderId)) { + filterChain.doFilter(request, response); + return; + } + + String[] ids = request.getParameterValues(uploaderId); + + if (ids == null) { + filterChain.doFilter(request, response); + return; + } + + Uploader.addAll(Uploader.parseRequest(request)); + + filterChain.doFilter(request, response); + Uploader.removeAll(); + } + + public void destroy() { + Uploader.removeAll(); + } +} + diff --git a/docviewer/src/com/log4ic/utils/io/Uploader.java b/docviewer/src/com/log4ic/utils/io/Uploader.java new file mode 100644 index 0000000..4bbbd1c --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/Uploader.java @@ -0,0 +1,348 @@ +package com.log4ic.utils.io; + +import javolution.util.FastList; +import org.apache.commons.io.*; +import org.apache.commons.lang.StringUtils; + +import javax.servlet.ServletRequest; +import java.io.*; +import java.util.List; +import java.util.Map; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-21 + * @time: 下午8:59 + */ +public class Uploader { + private final static ThreadLocal> threadLocal = new ThreadLocal>(); + + private static String tempDir; + + public static String getTempDir() { + return tempDir; + } + + public static void setTempDir(String tempDir) { + Uploader.tempDir = tempDir.endsWith(File.separator) ? tempDir : tempDir + File.separator; + } + + /** + * 获取当前的文件列表 + * + * @return list + */ + public static List getFileList() { + return threadLocal.get() == null ? new FastList() : threadLocal.get(); + } + + /** + * 获取一个文件 + * + * @param id + * @return + */ + public static UploaderFile getFile(String id) { + for (UploaderFile file : getFileList()) { + if (file.getId() != null && file.getId().equals(id)) { + return file; + } + } + return null; + } + + /** + * 添加一个文件到文件列表 + * + * @param file 文件 + */ + public static void addFile(UploaderFile file) { + List list = threadLocal.get(); + if (list == null) { + list = new FastList(); + threadLocal.set(list); + } + list.add(file); + } + + /** + * 添加一个文件到文件列表 + * + * @param fileList 文件 + */ + public static void addAll(List fileList) { + List list = threadLocal.get(); + if (list == null) { + threadLocal.set(fileList); + } else { + list.addAll(fileList); + } + } + + /** + * 移除一个文件 + * + * @param file + */ + public static void removeFile(UploaderFile file) { + List list = threadLocal.get(); + if (list == null) { + return; + } + file.delete(); + list.remove(file); + } + + /** + * 清空文件列表 + */ + public static void removeAll() { + List list = threadLocal.get(); + if (list == null) { + return; + } + if (!list.isEmpty()) { + File dir = list.get(0).getParentFile(); + + for (File file : dir.listFiles()) { + file.delete(); + } + + dir.delete(); + } + threadLocal.remove(); + } + + /** + * 格式化请求为文件列表 + * + * @param request + * @return + */ + public static List parseRequest(ServletRequest request) { + return parseRequest(new RequestParameterHelper(request)); + } + + /** + * 格式化请求为文件列表 + * + * @param request + * @param uploaderId + * @return + */ + public static List parseRequest(ServletRequest request, String uploaderId) { + return parseRequest(new RequestParameterHelper(request), uploaderId); + } + + /** + * 格式化请求为文件列表 + * + * @param helper + * @return + */ + public static List parseRequest(IParameterHelper helper) { + String uploaderId = helper.getParameter("uploader"); + return parseRequest(helper, uploaderId); + } + + /** + * 格式化请求为文件列表 + * + * @param helper + * @param uploaderId + * @return + */ + public static List parseRequest(IParameterHelper helper, String uploaderId) { + + List list = new FastList(); + + if (StringUtils.isBlank(uploaderId)) { + return list; + } + + String[] ids = helper.getParameterValues(uploaderId); + + if (ids == null) { + return list; + } + + + for (String id : ids) { + String fileName = helper.getParameter(id); + if (StringUtils.isNotBlank(fileName)) { + String filePath = tempDir + uploaderId + File.separator + id + "." + FileUtils.getFileSuffix(fileName); + UploaderFile tempFile = new UploaderFile(filePath, fileName, id); + if (tempFile.exists()) { + list.add(tempFile); + } + } + } + return list; + } + + + /** + * 格式化请求为文件列表 + * + * @param map + * @return + */ + public static List parseRequest(Map map) { + return parseRequest(new MapParameterHelper(map)); + } + + /** + * 格式化请求为文件列表 + * + * @param map + * @param uploaderId + * @return + */ + public static List parseRequest(Map map, String uploaderId) { + return parseRequest(new MapParameterHelper(map), uploaderId); + } + + + /** + * 存储文件 + * + * @param inputStream 上传文件 + * @param uploaderId 上传器ID + * @param fileName 上传文件名 + * @param chunks 总文件块数 + * @param chunk 当前块大小 + * @param chunkSize 接受的块大小 + * @return 是否存存成功 + */ + public static boolean saveFile(InputStream inputStream, String uploaderId, String fileName, int chunks, int chunk, int chunkSize) { + String dstPath = tempDir + uploaderId + File.separator + fileName; + File dstFile = new File(dstPath); + //分块上传 + if (chunks > 1) { + if (chunkSize > 0) { + File file = null; + // 文件已存在删除旧文件(上传了同名的文件) + if (chunk == 0 && dstFile.exists()) { + dstFile.delete(); + } else if (!(file = dstFile.getParentFile()).exists()) { + file.mkdirs(); + } + Uploader.appendChunk(inputStream, dstFile, chunkSize); + } else { + return false; + } + } else {//一次上传 + FileUtils.writeFile(inputStream, dstPath); + } + return true; + } + + + /** + * 向文件内追加文件块 + * + * @param src 欲追加文件块 + * @param dst 追加到的目标文件 + * @param bufferSize 块大小 + */ + public static void appendChunk(File src, File dst, int bufferSize) { + InputStream in = null; + try { + in = new BufferedInputStream(new FileInputStream(src), bufferSize); + appendChunk(in, dst, bufferSize); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * 向文件内追加文件块 + * + * @param in 欲追加文件 + * @param dst 追加到的目标文件 + * @param bufferSize 块大小 + */ + public static void appendChunk(InputStream in, File dst, int bufferSize) { + OutputStream out = null; + try { + if (dst.exists()) { + out = new BufferedOutputStream(new FileOutputStream(dst, true), + bufferSize); //plupload 配置了chunk的时候新上传的文件appand到文件末尾 + } else { + out = new BufferedOutputStream(new FileOutputStream(dst), + bufferSize); + } + + byte[] buffer = new byte[bufferSize]; + int len = 0; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (null != in) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != out) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + + public static interface IParameterHelper { + public String getParameter(String name); + + public String[] getParameterValues(String name); + } + + public static class RequestParameterHelper implements IParameterHelper { + private ServletRequest request; + + public RequestParameterHelper(ServletRequest request) { + this.request = request; + } + + public String getParameter(String name) { + return this.request.getParameter(name); + } + + public String[] getParameterValues(String name) { + return this.request.getParameterValues(name); + } + } + + public static class MapParameterHelper implements IParameterHelper { + private Map map; + + public MapParameterHelper(Map map) { + this.map = map; + } + + public String getParameter(String name) { + return this.map.get(name); + } + + public String[] getParameterValues(String name) { + return map.get(name).split(","); + } + } + +} diff --git a/docviewer/src/com/log4ic/utils/io/UploaderFile.java b/docviewer/src/com/log4ic/utils/io/UploaderFile.java new file mode 100644 index 0000000..66a1b6c --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/UploaderFile.java @@ -0,0 +1,47 @@ +package com.log4ic.utils.io; + +import java.io.File; +import java.net.URI; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-21 + * @time: 下午9:00 + */ +public class UploaderFile extends File { + protected String uploadName; + protected String id; + + public UploaderFile(String pathname, String uploadName, String id) { + super(pathname); + this.uploadName = uploadName; + this.id = id; + } + + public UploaderFile(String parent, String child, String uploadName, String id) { + super(parent, child); + this.uploadName = uploadName; + this.id = id; + } + + public UploaderFile(File parent, String child, String uploadName, String id) { + super(parent, child); + this.uploadName = uploadName; + this.id = id; + } + + public UploaderFile(URI uri, String uploadName, String id) { + super(uri); + this.uploadName = uploadName; + this.id = id; + } + + public String getUploadName() { + return this.uploadName; + } + + public String getId() { + return this.id; + } + +} diff --git a/docviewer/src/com/log4ic/utils/io/scanner/FileScanner.java b/docviewer/src/com/log4ic/utils/io/scanner/FileScanner.java new file mode 100644 index 0000000..8a38839 --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/scanner/FileScanner.java @@ -0,0 +1,252 @@ +package com.log4ic.utils.io.scanner; + +import com.log4ic.utils.io.scanner.filter.ClassNameScannerFilter; +import com.log4ic.utils.io.scanner.filter.IScannerFilter; +import com.log4ic.utils.support.scanner.filter.AnnotationFilter; +import javolution.util.FastList; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.Logger; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.net.JarURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Enumeration; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-27 + * @time: 下午4:46 + */ +public class FileScanner { + + /** + * LOGGER + */ + private static final Log LOGGER = LogFactory.getLog(FileScanner.class); + + /** + * 过滤规则适用情况 true—>搜索符合规则的 false->排除符合规则的 + */ + private boolean checkInOrEx = true; + + private IScannerFilter scannerFilter = null; + + private List fileList = new FastList(); + + /** + * 无参构造器,默认是排除内部类、并搜索符合规则 + */ + public FileScanner() { + this.scannerFilter = new ClassNameScannerFilter(null); + } + + /** + * checkInOrEx:过滤规则适用情况 true—>搜索符合规则的 false->排除符合规则的
+ * classFilters:自定义过滤规则,如果是null或者空,即全部符合不过滤 + * + * @param checkInOrEx + * @param classFilters + */ + public FileScanner(Boolean checkInOrEx, + List classFilters) { + this.checkInOrEx = checkInOrEx; + this.scannerFilter = new ClassNameScannerFilter(classFilters); + + } + + public FileScanner(Boolean checkInOrEx, + IScannerFilter filter) { + this.checkInOrEx = checkInOrEx; + this.scannerFilter = filter; + } + + public FileScanner(AnnotationFilter filter) { + this.scannerFilter = filter; + } + + /** + * 扫描包 + * + * @param basePackage 基础包 + * @param recursive 是否递归搜索子包 + * @return Set + */ + public List find(ClassLoader classLoader, String basePackage, boolean recursive) { + + if (basePackage.endsWith(".")) { + basePackage = basePackage + .substring(0, basePackage.lastIndexOf('.')); + } + String package2Path = basePackage.replace('.', '/'); + + Enumeration dirs; + try { + dirs = classLoader.getResources(package2Path); + if (!dirs.hasMoreElements()) { + return this.fileList; + } + this.fileList.clear(); + while (dirs.hasMoreElements()) { + URL url = dirs.nextElement(); + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + LOGGER .info("扫描file类型的文件:[" + url + "]"); + String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); + doScanFileByDir(basePackage, filePath, recursive, classLoader); + } else if ("jar".equals(protocol)) { + LOGGER .info("扫描jar文件中的类:[" + url + "]"); + doScanFileByJar(basePackage, url, recursive, classLoader); + } + } + } catch (IOException e) { + LOGGER .error("IOException error:", e); + } + + return fileList; + } + + public List find(String basePackage, boolean recursive) { + return this.find(Thread.currentThread().getContextClassLoader(), basePackage, recursive); + } + + public List find(ClassLoader classLoader, boolean recursive) { + return this.find(classLoader, "", recursive); + } + + public List find(ClassLoader classLoader, String basePackage) { + return this.find(classLoader, basePackage, true); + } + + public List find(ClassLoader classLoader) { + return this.find(classLoader, true); + } + + public List find(boolean recursive) { + return this.find("", recursive); + } + + public List find(String basePackage) { + return this.find(basePackage, true); + } + + public List find() { + return this.find(true); + } + + /** + * 以jar的方式扫描包下的所有文件 + * + * @param basePackage + * @param url + * @param recursive + */ + private void doScanFileByJar(String basePackage, URL url, final boolean recursive, ClassLoader classLoader) { + String packageName = basePackage; + String package2Path = packageName.replace('.', '/'); + JarFile jar; + try { + jar = ((JarURLConnection) url.openConnection()).getJarFile(); + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String name = entry.getName(); + if (!name.startsWith(package2Path) || entry.isDirectory()) { + continue; + } + + // 判断是否递归搜索子包 + if (!recursive && name.lastIndexOf('/') != package2Path.length()) { + continue; + } + + URL fileUrl = new URL(url + name.substring(name.lastIndexOf("/"))); + + // 判定是否符合过滤条件 + boolean filter = scannerFilter.filter(name, fileUrl, classLoader); + if (checkInOrEx ? filter : !filter) { + this.fileList.add(fileUrl); + } + } + } catch (IOException e) { + LOGGER .error("IOException error:", e); + } + } + + /** + * 以文件目录的方式扫描包下的所有Class文件 + * + * @param packageName + * @param packagePath + * @param recursive + */ + private void doScanFileByDir(final String packageName, String packagePath, boolean recursive, final ClassLoader classLoader) { + File dir = new File(packagePath); + if (!dir.exists() || !dir.isDirectory()) { + return; + } + final boolean fileRecursive = recursive; + File[] dirfiles = dir.listFiles(new FileFilter() { + // 自定义文件过滤规则 + public boolean accept(File file) { + if (file.isDirectory()) { + return fileRecursive; + } + boolean filter = false; + try { + filter = scannerFilter.filter(packageName + "." + file.getName(), file.toURI().toURL(), classLoader); + } catch (MalformedURLException e) { + LOGGER .error(e); + } + return checkInOrEx ? filter : !filter; + } + }); + for (File file : dirfiles) { + if (file.isDirectory()) { + doScanFileByDir(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classLoader); + } else { + try { + this.fileList.add(file.toURI().toURL()); + } catch (MalformedURLException e) { + LOGGER .error(e); + } + + } + } + } + + + public boolean isCheckInOrEx() { + return checkInOrEx; + } + + + public void setCheckInOrEx(boolean pCheckInOrEx) { + checkInOrEx = pCheckInOrEx; + } + + public IScannerFilter getScannerFilter() { + return scannerFilter; + } + + public void setScannerFilter(IScannerFilter scannerFilter) { + this.scannerFilter = scannerFilter; + } + + public static void main(String[] args) { + FileScanner fileScanner = new FileScanner(); + List list = fileScanner.find("com.log4ic.entity"); + for (URL url : list) { + System.out.println(url.getPath()); + } + } +} diff --git a/docviewer/src/com/log4ic/utils/io/scanner/filter/ClassNameScannerFilter.java b/docviewer/src/com/log4ic/utils/io/scanner/filter/ClassNameScannerFilter.java new file mode 100644 index 0000000..012b719 --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/scanner/filter/ClassNameScannerFilter.java @@ -0,0 +1,49 @@ +package com.log4ic.utils.io.scanner.filter; + +import com.log4ic.utils.io.scanner.FileScanner; +import javolution.util.FastList; + +import java.net.URL; +import java.util.List; +import java.util.regex.Pattern; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 上午12:59 + */ +public class ClassNameScannerFilter implements IScannerFilter { + + List classFilters = new FastList(); + + public ClassNameScannerFilter(List classFilters) { + this.classFilters = classFilters; + } + + /** + * 根据过滤规则判断类名 + * + * @param url + * @return + */ + public boolean filter(String urlStr, URL url, ClassLoader classLoader) { + String fileName = url.getFile(); + if (!fileName.endsWith(".class")) { + return false; + } + if (null == this.classFilters || this.classFilters.isEmpty()) { + return true; + } + String tmpName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length() - 6); + boolean flag = false; + for (String str : classFilters) { + String tmpreg = "^" + str.replace("*", ".*") + "$"; + Pattern p = Pattern.compile(tmpreg); + if (p.matcher(tmpName).find()) { + flag = true; + break; + } + } + return flag; + } +} diff --git a/docviewer/src/com/log4ic/utils/io/scanner/filter/IScannerFilter.java b/docviewer/src/com/log4ic/utils/io/scanner/filter/IScannerFilter.java new file mode 100644 index 0000000..f9ebb70 --- /dev/null +++ b/docviewer/src/com/log4ic/utils/io/scanner/filter/IScannerFilter.java @@ -0,0 +1,14 @@ +package com.log4ic.utils.io.scanner.filter; + +import com.log4ic.utils.io.scanner.FileScanner; + +import java.net.URL; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 上午12:54 + */ +public interface IScannerFilter { + boolean filter(String urlStr, URL url, ClassLoader classLoader); +} diff --git a/docviewer/src/com/log4ic/utils/support/DataBaseSupport.java b/docviewer/src/com/log4ic/utils/support/DataBaseSupport.java new file mode 100644 index 0000000..c93e5c3 --- /dev/null +++ b/docviewer/src/com/log4ic/utils/support/DataBaseSupport.java @@ -0,0 +1,72 @@ +package com.log4ic.utils.support; + +import com.log4ic.utils.dao.DocViewerJdbcSupport; +import com.log4ic.utils.io.scanner.FileScanner; +import com.log4ic.utils.support.scanner.filter.AnnotationFilter; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.naming.NamingException; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Enumeration; +import java.util.List; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 上午2:51 + */ +public class DataBaseSupport implements ServletContextListener { + private static final Log LOGGER = LogFactory.getLog(DataBaseSupport.class); + + public void contextInitialized(ServletContextEvent servletContextEvent) { + LOGGER.info("初始化实体表...."); + AnnotationFilter annotationFilter = new AnnotationFilter(); + FileScanner fileScanner = new FileScanner(annotationFilter); + LOGGER.info("查找相关实体...."); + fileScanner.find("com.log4ic.entity"); + + List entityClassList = annotationFilter.getClassList(); + + try { + LOGGER.info("查看是否建表...."); + for (Class clazz : entityClassList) { + DocViewerJdbcSupport support = (DocViewerJdbcSupport) clazz.newInstance(); + boolean exist = support.hasTable(); + String tableName = support.getTableName(); + LOGGER.info("表[" + tableName + "]" + (exist ? "" : "不") + "存在"); + if (!exist) { + LOGGER.info("创建表[" + tableName + "]"); + support.createTable(); + } + } + } catch (NamingException e) { + LOGGER.error(e); + } catch (SQLException e) { + LOGGER.error(e); + } catch (InstantiationException e) { + LOGGER.error(e); + } catch (IllegalAccessException e) { + LOGGER.error(e); + } + + } + + public void contextDestroyed(ServletContextEvent servletContextEvent) { + Enumeration drivers = DriverManager.getDrivers(); + while (drivers.hasMoreElements()) { + Driver driver = drivers.nextElement(); + try { + DriverManager.deregisterDriver(driver); + LOGGER.debug("deregistering jdbc driver:" + driver); + } catch (SQLException e) { + LOGGER.error(e); + } + } + + } +} diff --git a/docviewer/src/com/log4ic/utils/support/scanner/filter/AnnotationFilter.java b/docviewer/src/com/log4ic/utils/support/scanner/filter/AnnotationFilter.java new file mode 100644 index 0000000..ae28d6a --- /dev/null +++ b/docviewer/src/com/log4ic/utils/support/scanner/filter/AnnotationFilter.java @@ -0,0 +1,54 @@ +package com.log4ic.utils.support.scanner.filter; + +import com.log4ic.utils.io.scanner.FileScanner; +import com.log4ic.utils.io.scanner.filter.IScannerFilter; +import javolution.util.FastList; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.Logger; + +import javax.persistence.Entity; +import java.lang.annotation.Annotation; +import java.net.URL; +import java.util.List; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 上午3:26 + */ +public class AnnotationFilter implements IScannerFilter { + + private static final Log LOGGER = LogFactory.getLog(AnnotationFilter.class); + + private List classList = new FastList(); + + public boolean filter(String urlStr, URL url, ClassLoader classLoader) { + String classPathStr = urlStr.replace("/", "."); + classPathStr = classPathStr.substring(0, classPathStr.length() - 6); + try { + Class clazz = classLoader.loadClass(classPathStr); + if (clazz.isAnnotationPresent(Entity.class)) { + classList.add(clazz); + return true; + } else { + return false; + } + } catch (ClassNotFoundException e) { + LOGGER.error(e); + } + return false; + } + + public List getClassList() { + return classList; + } + + public static void main(String[] args) { + FileScanner fileScanner = new FileScanner(new AnnotationFilter()); + List list = fileScanner.find("com.log4ic.entity"); + for (URL url : list) { + System.out.println(url.getPath()); + } + } +} diff --git a/docviewer/src/com/log4ic/utils/web/filter/CharacterEncodingFilter.java b/docviewer/src/com/log4ic/utils/web/filter/CharacterEncodingFilter.java new file mode 100644 index 0000000..e3d2fff --- /dev/null +++ b/docviewer/src/com/log4ic/utils/web/filter/CharacterEncodingFilter.java @@ -0,0 +1,50 @@ +package com.log4ic.utils.web.filter; + +import org.apache.commons.lang.ClassUtils; +import org.apache.commons.lang.StringUtils; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-28 + * @time: 下午10:31 + */ +public class CharacterEncodingFilter implements Filter { + private static boolean responseSetCharacterEncodingAvailable = false; + + static { + try { + responseSetCharacterEncodingAvailable = ClassUtils.getPublicMethod( + HttpServletResponse.class, "setCharacterEncoding", new Class[]{String.class}) != null; + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + } + + private boolean forceEncoding; + private String encoding; + + public void init(FilterConfig filterConfig) throws ServletException { + this.encoding = filterConfig.getInitParameter("encoding"); + String fe = filterConfig.getInitParameter("forceEncoding"); + if (StringUtils.isNotBlank(fe)) { + this.forceEncoding = Boolean.parseBoolean(fe); + } + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { + if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) { + request.setCharacterEncoding(this.encoding); + if (this.forceEncoding && responseSetCharacterEncodingAvailable) { + response.setCharacterEncoding(this.encoding); + } + } + filterChain.doFilter(request, response); + } + + public void destroy() { + } +} diff --git a/docviewer/web/META-INF/MANIFEST.MF b/docviewer/web/META-INF/MANIFEST.MF index 59499bc..4a8033f 100644 --- a/docviewer/web/META-INF/MANIFEST.MF +++ b/docviewer/web/META-INF/MANIFEST.MF @@ -1,2 +1,2 @@ -Manifest-Version: 1.0 +Manifest-Version: 0.0.9.0 diff --git a/docviewer/web/META-INF/context.xml b/docviewer/web/META-INF/context.xml new file mode 100644 index 0000000..87b0945 --- /dev/null +++ b/docviewer/web/META-INF/context.xml @@ -0,0 +1,12 @@ + + + + diff --git a/docviewer/web/WEB-INF/web.xml b/docviewer/web/WEB-INF/web.xml index 66991cb..6046ca6 100644 --- a/docviewer/web/WEB-INF/web.xml +++ b/docviewer/web/WEB-INF/web.xml @@ -1,29 +1,81 @@ - - - - - - - docViewerServlet - com.log4ic.servlet.DocViewerServlet - - - docViewerServlet - /docviewer - - - docViewerServlet - /docviewer/* - - - - com.log4ic.support.DocViewerServiceListener - - - - docviewer.jsp - - + + + + CharsetFilter + + com.log4ic.utils.web.filter.CharacterEncodingFilter + + + encoding + UTF-8 + + + forceEncoding + true + + + + CharsetFilter + /* + + + uploaderFilter + com.log4ic.utils.io.FileUploaderFilter + + tempDir + /home/icode/uploader/tempDir + + + + + uploaderFilter + * + + + + + uploaderServlet + com.log4ic.servlet.UploaderServlet + + + + uploaderServlet + /upload + + + + + docViewerServlet + com.log4ic.servlet.DocViewerServlet + + + docViewerServlet + /docviewer + + + docViewerServlet + /docviewer/* + + + + com.log4ic.utils.support.DocViewerServiceListener + + + + + com.log4ic.utils.support.DataBaseSupport + + + + + org.apache.commons.fileupload.servlet.FileCleanerCleanup + + + + + documents.jsp + + \ No newline at end of file diff --git a/docviewer/web/continue.jsp b/docviewer/web/continue.jsp new file mode 100644 index 0000000..e2ffb3e --- /dev/null +++ b/docviewer/web/continue.jsp @@ -0,0 +1,31 @@ +<%-- + Created by IntelliJ IDEA. + User: icode + Date: 12-1-28 + Time: 上午8:32 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + 跳转提示 + + +
+ 文档已经上传完毕,并进入转换列队,系统将在10秒钟后为您跳转至文档列表.... +
+ + + \ No newline at end of file diff --git a/docviewer/web/documents.jsp b/docviewer/web/documents.jsp new file mode 100644 index 0000000..42f3da8 --- /dev/null +++ b/docviewer/web/documents.jsp @@ -0,0 +1,49 @@ +<%@ page import="com.log4ic.dao.impl.DocumentRelationDao" %> +<%@ page import="java.util.List" %> +<%@ page import="java.util.Map" %> +<%@ page import="java.sql.ResultSet" %> +<%@ page import="com.log4ic.entity.DocumentRelation" %> +<%@ page import="java.text.SimpleDateFormat" %> +<%-- + Created by IntelliJ IDEA. + User: icode + Date: 12-1-23 + Time: 上午12:44 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + 所有文档 + + + +
    + <% + DocumentRelationDao relationDao = new DocumentRelationDao(); + List documentRelationList = relationDao.getAllRelation(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for (DocumentRelation relation : documentRelationList) { + %> +
  1. <%=relation.getFileName()%> + 创建时间:<%=sdf.format(relation.getCreateDate())%>
  2. + <%}%> +
+ + + \ No newline at end of file diff --git a/docviewer/web/resources/images/icon.png b/docviewer/web/resources/images/icon.png new file mode 100644 index 0000000..7308ca5 Binary files /dev/null and b/docviewer/web/resources/images/icon.png differ diff --git a/docviewer/web/scripts/docviewer.js b/docviewer/web/scripts/docviewer.js index f421f2c..efe2bf8 100644 --- a/docviewer/web/scripts/docviewer.js +++ b/docviewer/web/scripts/docviewer.js @@ -39,14 +39,6 @@ return error; } - function getRootPath() { - var curWwwPath = window.document.location.href, - pathName = window.document.location.pathname, - pos = curWwwPath.indexOf(pathName), - localhostPath = curWwwPath.substring(0, pos), - projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); - return(localhostPath + projectName); - } w.DocViewer = function(args) { args = args || {}; @@ -564,7 +556,7 @@ this.el.trigger('postsnapshot', url); } }; - var rootPath = getRootPath(); + var rootPath = ""; $.extend(w.DocViewer, { NONE_PERMS:0, READ_ONLY_PERMS:1, diff --git a/docviewer/web/scripts/i18n/zh_cn/uploader.js b/docviewer/web/scripts/i18n/zh_cn/uploader.js new file mode 100644 index 0000000..bfae539 --- /dev/null +++ b/docviewer/web/scripts/i18n/zh_cn/uploader.js @@ -0,0 +1,9 @@ +(function(w){ + if(w.plupload){ + w.plupload.addI18n({ + 'File size error.':'文件大小超过', + 'File extension error.':'不支持的文件格式!', + 'Init error.':'初始化错误!' + }) + } +})(window); \ No newline at end of file diff --git a/docviewer/web/scripts/lib/plupload/js/plupload.browserplus.js b/docviewer/web/scripts/lib/plupload/js/plupload.browserplus.js index 470f63d..52a9960 100644 --- a/docviewer/web/scripts/lib/plupload/js/plupload.browserplus.js +++ b/docviewer/web/scripts/lib/plupload/js/plupload.browserplus.js @@ -1,189 +1 @@ -(function(a) { - a.runtimes.BrowserPlus = a.addRuntime("browserplus", {getFeatures:function() { - return{dragdrop:true,jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true} - },init:function(g, i) { - var e = window.BrowserPlus,h = {},d = g.settings,c = d.resize; - - function f(n) { - var m,l,j = [],k,o; - for (l = 0; l < n.length; l++) { - k = n[l]; - o = a.guid(); - h[o] = k; - j.push(new a.File(o, k.name, k.size)) - } - if (l) { - g.trigger("FilesAdded", j) - } - } - - function b() { - g.bind("PostInit", function() { - var m,k = d.drop_element,o = g.id + "_droptarget",j = document.getElementById(k),l; - - function p(r, q) { - e.DragAndDrop.AddDropTarget({id:r}, function(s) { - e.DragAndDrop.AttachCallbacks({id:r,hover:function(t) { - if (!t && q) { - q() - } - },drop:function(t) { - if (q) { - q() - } - f(t) - }}, function() { - }) - }) - } - - function n() { - document.getElementById(o).style.top = "-1000px" - } - - if (j) { - if (document.attachEvent && (/MSIE/gi).test(navigator.userAgent)) { - m = document.createElement("div"); - m.setAttribute("id", o); - a.extend(m.style, {position:"absolute",top:"-1000px",background:"red",filter:"alpha(opacity=0)",opacity:0}); - document.body.appendChild(m); - a.addEvent(j, "dragenter", function(r) { - var q,s; - q = document.getElementById(k); - s = a.getPos(q); - a.extend(document.getElementById(o).style, {top:s.y + "px",left:s.x + "px",width:q.offsetWidth + "px",height:q.offsetHeight + "px"}) - }); - p(o, n) - } else { - p(k) - } - } - a.addEvent(document.getElementById(d.browse_button), "click", function(v) { - var t = [],r,q,u = d.filters,s; - v.preventDefault(); - no_type_restriction:for (r = 0; r < u.length; r++) { - s = u[r].extensions.split(","); - for (q = 0; q < s.length; q++) { - if (s[q] === "*") { - t = []; - break no_type_restriction - } - t.push(a.mimeTypes[s[q]]) - } - } - e.FileBrowse.OpenBrowseDialog({mimeTypes:t}, function(w) { - if (w.success) { - f(w.value) - } - }) - }); - j = m = null - }); - g.bind("UploadFile", function(m, j) { - var l = h[j.id],r = {},k = m.settings.chunk_size,n,o = []; - - function q(s, u) { - var t; - if (j.status == a.FAILED) { - return - } - r.name = j.target_name || j.name; - if (k) { - r.chunk = "" + s; - r.chunks = "" + u - } - t = o.shift(); - e.Uploader.upload({url:m.settings.url,files:{file:t},cookies:document.cookies,postvars:a.extend(r, m.settings.multipart_params),progressCallback:function(x) { - var w,v = 0; - n[s] = parseInt(x.filePercent * t.size / 100, 10); - for (w = 0; w < n.length; w++) { - v += n[w] - } - j.loaded = v; - m.trigger("UploadProgress", j) - }}, function(w) { - var v,x; - if (w.success) { - v = w.value.statusCode; - if (k) { - m.trigger("ChunkUploaded", j, {chunk:s,chunks:u,response:w.value.body,status:v}) - } - if (o.length > 0) { - q(++s, u) - } else { - j.status = a.DONE; - m.trigger("FileUploaded", j, {response:w.value.body,status:v}); - if (v >= 400) { - m.trigger("Error", {code:a.HTTP_ERROR,message:a.translate("HTTP Error."),file:j,status:v}) - } - } - } else { - m.trigger("Error", {code:a.GENERIC_ERROR,message:a.translate("Generic Error."),file:j,details:w.error}) - } - }) - } - - function p(s) { - j.size = s.size; - if (k) { - e.FileAccess.chunk({file:s,chunkSize:k}, function(v) { - if (v.success) { - var w = v.value,t = w.length; - n = Array(t); - for (var u = 0; u < t; u++) { - n[u] = 0; - o.push(w[u]) - } - q(0, t) - } - }) - } else { - n = Array(1); - o.push(s); - q(0, 1) - } - } - - if (c && /\.(png|jpg|jpeg)$/i.test(j.name)) { - BrowserPlus.ImageAlter.transform({file:l,quality:c.quality || 90,actions:[ - {scale:{maxwidth:c.width,maxheight:c.height}} - ]}, function(s) { - if (s.success) { - p(s.value.file) - } - }) - } else { - p(l) - } - }); - i({success:true}) - } - - if (e) { - e.init(function(k) { - var j = [ - {service:"Uploader",version:"3"}, - {service:"DragAndDrop",version:"1"}, - {service:"FileBrowse",version:"1"}, - {service:"FileAccess",version:"2"} - ]; - if (c) { - j.push({service:"ImageAlter",version:"4"}) - } - if (k.success) { - e.require({services:j}, function(l) { - if (l.success) { - b() - } else { - i() - } - }) - } else { - i() - } - }) - } else { - i() - } - }}) -})(plupload); \ No newline at end of file +(function(a){a.runtimes.BrowserPlus=a.addRuntime("browserplus",{getFeatures:function(){return{dragdrop:true,jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true}},init:function(g,i){var e=window.BrowserPlus,h={},d=g.settings,c=d.resize;function f(n){var m,l,j=[],k,o;for(l=0;l0){q(++s,u)}else{j.status=a.DONE;m.trigger("FileUploaded",j,{response:w.value.body,status:v});if(v>=400){m.trigger("Error",{code:a.HTTP_ERROR,message:a.translate("HTTP Error."),file:j,status:v})}}}else{m.trigger("Error",{code:a.GENERIC_ERROR,message:a.translate("Generic Error."),file:j,details:w.error})}})}function p(s){j.size=s.size;if(k){e.FileAccess.chunk({file:s,chunkSize:k},function(v){if(v.success){var w=v.value,t=w.length;n=Array(t);for(var u=0;u'; - if (d.ua.ie) { - q = b.createElement("div"); - l.appendChild(q); - q.outerHTML = p; - q = null - } else { - l.innerHTML = p - } - }()); - function n() { - return b.getElementById(m.id + "_flash") - } - - function j() { - if (h++ > 5000) { - o({success:false}); - return - } - if (!g[m.id]) { - setTimeout(j, 1) - } - } - - j(); - k = l = null; - m.bind("Flash:Init", function() { - var q = {},p; - n().setFileFilters(m.settings.filters, m.settings.multi_selection); - if (g[m.id]) { - return - } - g[m.id] = true; - m.bind("UploadFile", function(r, t) { - var u = r.settings,s = m.settings.resize || {}; - n().uploadFile(q[t.id], u.url, {name:t.target_name || t.name,mime:d.mimeTypes[t.name.replace(/^.+\.([^.]+)/, "$1").toLowerCase()] || "application/octet-stream",chunk_size:u.chunk_size,width:s.width,height:s.height,quality:s.quality,multipart:u.multipart,multipart_params:u.multipart_params || {},file_data_name:u.file_data_name,format:/\.(jpg|jpeg)$/i.test(t.name) ? "jpg" : "png",headers:u.headers,urlstream_upload:u.urlstream_upload}) - }); - m.bind("Flash:UploadProcess", function(s, r) { - var t = s.getFile(q[r.id]); - if (t.status != d.FAILED) { - t.loaded = r.loaded; - t.size = r.size; - s.trigger("UploadProgress", t) - } - }); - m.bind("Flash:UploadChunkComplete", function(r, t) { - var u,s = r.getFile(q[t.id]); - u = {chunk:t.chunk,chunks:t.chunks,response:t.text}; - r.trigger("ChunkUploaded", s, u); - if (s.status != d.FAILED) { - n().uploadNextChunk() - } - if (t.chunk == t.chunks - 1) { - s.status = d.DONE; - r.trigger("FileUploaded", s, {response:t.text}) - } - }); - m.bind("Flash:SelectFiles", function(r, u) { - var t,s,v = [],w; - for (s = 0; s < u.length; s++) { - t = u[s]; - w = d.guid(); - q[w] = t.id; - q[t.id] = w; - v.push(new d.File(w, t.name, t.size)) - } - if (v.length) { - m.trigger("FilesAdded", v) - } - }); - m.bind("Flash:SecurityError", function(r, s) { - m.trigger("Error", {code:d.SECURITY_ERROR,message:d.translate("Security error."),details:s.message,file:m.getFile(q[s.id])}) - }); - m.bind("Flash:GenericError", function(r, s) { - m.trigger("Error", {code:d.GENERIC_ERROR,message:d.translate("Generic error."),details:s.message,file:m.getFile(q[s.id])}) - }); - m.bind("Flash:IOError", function(r, s) { - m.trigger("Error", {code:d.IO_ERROR,message:d.translate("IO error."),details:s.message,file:m.getFile(q[s.id])}) - }); - m.bind("Flash:ImageError", function(r, s) { - m.trigger("Error", {code:parseInt(s.code, 10),message:d.translate("Image error."),file:m.getFile(q[s.id])}) - }); - m.bind("Flash:StageEvent:rollOver", function(r) { - var s,t; - s = b.getElementById(m.settings.browse_button); - t = r.settings.browse_button_hover; - if (s && t) { - d.addClass(s, t) - } - }); - m.bind("Flash:StageEvent:rollOut", function(r) { - var s,t; - s = b.getElementById(m.settings.browse_button); - t = r.settings.browse_button_hover; - if (s && t) { - d.removeClass(s, t) - } - }); - m.bind("Flash:StageEvent:mouseDown", function(r) { - var s,t; - s = b.getElementById(m.settings.browse_button); - t = r.settings.browse_button_active; - if (s && t) { - d.addClass(s, t); - d.addEvent(b.body, "mouseup", function() { - d.removeClass(s, t) - }, r.id) - } - }); - m.bind("Flash:StageEvent:mouseUp", function(r) { - var s,t; - s = b.getElementById(m.settings.browse_button); - t = r.settings.browse_button_active; - if (s && t) { - d.removeClass(s, t) - } - }); - m.bind("Flash:ExifData", function(r, s) { - m.trigger("ExifData", m.getFile(q[s.id]), s.data) - }); - m.bind("Flash:GpsData", function(r, s) { - m.trigger("GpsData", m.getFile(q[s.id]), s.data) - }); - m.bind("QueueChanged", function(r) { - m.refresh() - }); - m.bind("FilesRemoved", function(r, t) { - var s; - for (s = 0; s < t.length; s++) { - n().removeFile(q[t[s].id]) - } - }); - m.bind("StateChanged", function(r) { - m.refresh() - }); - m.bind("Refresh", function(r) { - var s,t,u; - n().setFileFilters(m.settings.filters, m.settings.multi_selection); - s = b.getElementById(r.settings.browse_button); - if (s) { - t = d.getPos(s, b.getElementById(r.settings.container)); - u = d.getSize(s); - d.extend(b.getElementById(r.id + "_flash_container").style, {top:t.y + "px",left:t.x + "px",width:u.w + "px",height:u.h + "px"}) - } - }); - m.bind("Destroy", function(r) { - var s; - d.removeAllEvents(b.body, r.id); - delete g[r.id]; - delete a[r.id]; - s = b.getElementById(r.id + "_flash_container"); - if (s) { - i.removeChild(s) - } - }); - o({success:true}) - }) - }}) -})(window, document, plupload); \ No newline at end of file +(function(f,b,d,e){var a={},g={};function c(){var h;try{h=navigator.plugins["Shockwave Flash"];h=h.description}catch(j){try{h=new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version")}catch(i){h="0.0"}}h=h.match(/\d+/g);return parseFloat(h[0]+"."+h[1])}d.flash={trigger:function(j,h,i){setTimeout(function(){var m=a[j],l,k;if(m){m.trigger("Flash:"+h,i)}},0)}};d.runtimes.Flash=d.addRuntime("flash",{getFeatures:function(){return{jpgresize:true,pngresize:true,maxWidth:8091,maxHeight:8091,chunks:true,progress:true,multipart:true,multi_selection:true}},init:function(m,o){var k,l,h=0,i=b.body;if(c()<10){o({success:false});return}g[m.id]=false;a[m.id]=m;k=b.getElementById(m.settings.browse_button);l=b.createElement("div");l.id=m.id+"_flash_container";d.extend(l.style,{position:"absolute",top:"0px",background:m.settings.shim_bgcolor||"transparent",zIndex:99999,width:"100%",height:"100%"});l.className="plupload flash";if(m.settings.container){i=b.getElementById(m.settings.container);if(d.getStyle(i,"position")==="static"){i.style.position="relative"}}i.appendChild(l);(function(){var p,q;p='';if(d.ua.ie){q=b.createElement("div");l.appendChild(q);q.outerHTML=p;q=null}else{l.innerHTML=p}}());function n(){return b.getElementById(m.id+"_flash")}function j(){if(h++>5000){o({success:false});return}if(!g[m.id]){setTimeout(j,1)}}j();k=l=null;m.bind("Flash:Init",function(){var q={},p;n().setFileFilters(m.settings.filters,m.settings.multi_selection);if(g[m.id]){return}g[m.id]=true;m.bind("UploadFile",function(r,t){var u=r.settings,s=m.settings.resize||{};n().uploadFile(q[t.id],u.url,{name:t.target_name||t.name,mime:d.mimeTypes[t.name.replace(/^.+\.([^.]+)/,"$1").toLowerCase()]||"application/octet-stream",chunk_size:u.chunk_size,width:s.width,height:s.height,quality:s.quality,multipart:u.multipart,multipart_params:u.multipart_params||{},file_data_name:u.file_data_name,format:/\.(jpg|jpeg)$/i.test(t.name)?"jpg":"png",headers:u.headers,urlstream_upload:u.urlstream_upload})});m.bind("Flash:UploadProcess",function(s,r){var t=s.getFile(q[r.id]);if(t.status!=d.FAILED){t.loaded=r.loaded;t.size=r.size;s.trigger("UploadProgress",t)}});m.bind("Flash:UploadChunkComplete",function(r,t){var u,s=r.getFile(q[t.id]);u={chunk:t.chunk,chunks:t.chunks,response:t.text};r.trigger("ChunkUploaded",s,u);if(s.status!=d.FAILED){n().uploadNextChunk()}if(t.chunk==t.chunks-1){s.status=d.DONE;r.trigger("FileUploaded",s,{response:t.text})}});m.bind("Flash:SelectFiles",function(r,u){var t,s,v=[],w;for(s=0;s":"gt","&":"amp",'"':"quot","'":"#39"},m = /[<>&\"\']/g,b,c = window.setTimeout,d = {},e; - - function h() { - this.returnValue = false - } - - function k() { - this.cancelBubble = true - } - - (function(o) { - var p = o.split(/,/),q,s,r; - for (q = 0; q < p.length; q += 2) { - r = p[q + 1].split(/ /); - for (s = 0; s < r.length; s++) { - j[r[s]] = p[q] - } - } - })("application/msword,doc dot,application/pdf,pdf,application/pgp-signature,pgp,application/postscript,ps ai eps,application/rtf,rtf,application/vnd.ms-excel,xls xlb,application/vnd.ms-powerpoint,ppt pps pot,application/zip,zip,application/x-shockwave-flash,swf swfl,application/vnd.openxmlformats,docx pptx xlsx,audio/mpeg,mpga mpega mp2 mp3,audio/x-wav,wav,audio/mp4,m4a,image/bmp,bmp,image/gif,gif,image/jpeg,jpeg jpg jpe,image/photoshop,psd,image/png,png,image/svg+xml,svg svgz,image/tiff,tiff tif,text/html,htm html xhtml,text/rtf,rtf,video/mpeg,mpeg mpg mpe,video/quicktime,qt mov,video/mp4,mp4,video/x-m4v,m4v,video/x-flv,flv,video/x-ms-wmv,wmv,video/avi,avi,video/webm,webm,video/vnd.rn-realvideo,rv,text/csv,csv,text/plain,asc txt text diff log,application/octet-stream,exe"); - var g = {VERSION:"1.5.1.1",STOPPED:1,STARTED:2,QUEUED:1,UPLOADING:2,FAILED:4,DONE:5,GENERIC_ERROR:-100,HTTP_ERROR:-200,IO_ERROR:-300,SECURITY_ERROR:-400,INIT_ERROR:-500,FILE_SIZE_ERROR:-600,FILE_EXTENSION_ERROR:-601,IMAGE_FORMAT_ERROR:-700,IMAGE_MEMORY_ERROR:-701,IMAGE_DIMENSIONS_ERROR:-702,mimeTypes:j,ua:(function() { - var s = navigator,r = s.userAgent,t = s.vendor,p,o,q; - p = /WebKit/.test(r); - q = p && t.indexOf("Apple") !== -1; - o = window.opera && window.opera.buildNumber; - return{windows:navigator.platform.indexOf("Win") !== -1,ie:!p && !o && (/MSIE/gi).test(r) && (/Explorer/gi).test(s.appName),webkit:p,gecko:!p && /Gecko/.test(r),safari:q,opera:!!o} - }()),extend:function(o) { - g.each(arguments, function(p, q) { - if (q > 0) { - g.each(p, function(s, r) { - o[r] = s - }) - } - }); - return o - },cleanName:function(o) { - var p,q; - q = [/[\300-\306]/g,"A",/[\340-\346]/g,"a",/\307/g,"C",/\347/g,"c",/[\310-\313]/g,"E",/[\350-\353]/g,"e",/[\314-\317]/g,"I",/[\354-\357]/g,"i",/\321/g,"N",/\361/g,"n",/[\322-\330]/g,"O",/[\362-\370]/g,"o",/[\331-\334]/g,"U",/[\371-\374]/g,"u"]; - for (p = 0; p < q.length; p += 2) { - o = o.replace(q[p], q[p + 1]) - } - o = o.replace(/\s+/g, "_"); - o = o.replace(/[^a-z0-9_\-\.]+/gi, ""); - return o - },addRuntime:function(o, p) { - p.name = o; - l[o] = p; - l.push(p); - return p - },guid:function() { - var o = new Date().getTime().toString(32),p; - for (p = 0; p < 5; p++) { - o += Math.floor(Math.random() * 65535).toString(32) - } - return(g.guidPrefix || "p") + o + (f++).toString(32) - },buildUrl:function(p, o) { - var q = ""; - g.each(o, function(s, r) { - q += (q ? "&" : "") + encodeURIComponent(r) + "=" + encodeURIComponent(s) - }); - if (q) { - p += (p.indexOf("?") > 0 ? "&" : "?") + q - } - return p - },each:function(r, s) { - var q,p,o; - if (r) { - q = r.length; - if (q === b) { - for (p in r) { - if (r.hasOwnProperty(p)) { - if (s(r[p], p) === false) { - return - } - } - } - } else { - for (o = 0; o < q; o++) { - if (s(r[o], o) === false) { - return - } - } - } - } - },formatSize:function(o) { - if (o === b || /\D/.test(o)) { - return g.translate("N/A") - } - if (o > 1073741824) { - return Math.round(o / 1073741824, 1) + " GB" - } - if (o > 1048576) { - return Math.round(o / 1048576, 1) + " MB" - } - if (o > 1024) { - return Math.round(o / 1024, 1) + " KB" - } - return o + " b" - },getPos:function(p, t) { - var u = 0,s = 0,w,v = document,q,r; - p = p; - t = t || v.body; - function o(C) { - var A,B,z = 0,D = 0; - if (C) { - B = C.getBoundingClientRect(); - A = v.compatMode === "CSS1Compat" ? v.documentElement : v.body; - z = B.left + A.scrollLeft; - D = B.top + A.scrollTop - } - return{x:z,y:D} - } - - if (p && p.getBoundingClientRect && (navigator.userAgent.indexOf("MSIE") > 0 && v.documentMode !== 8)) { - q = o(p); - r = o(t); - return{x:q.x - r.x,y:q.y - r.y} - } - w = p; - while (w && w != t && w.nodeType) { - u += w.offsetLeft || 0; - s += w.offsetTop || 0; - w = w.offsetParent - } - w = p.parentNode; - while (w && w != t && w.nodeType) { - u -= w.scrollLeft || 0; - s -= w.scrollTop || 0; - w = w.parentNode - } - return{x:u,y:s} - },getSize:function(o) { - return{w:o.offsetWidth || o.clientWidth,h:o.offsetHeight || o.clientHeight} - },parseSize:function(o) { - var p; - if (typeof(o) == "string") { - o = /^([0-9]+)([mgk]?)$/.exec(o.toLowerCase().replace(/[^0-9mkg]/g, "")); - p = o[2]; - o = +o[1]; - if (p == "g") { - o *= 1073741824 - } - if (p == "m") { - o *= 1048576 - } - if (p == "k") { - o *= 1024 - } - } - return o - },xmlEncode:function(o) { - return o ? ("" + o).replace(m, function(p) { - return a[p] ? "&" + a[p] + ";" : p - }) : o - },toArray:function(q) { - var p,o = []; - for (p = 0; p < q.length; p++) { - o[p] = q[p] - } - return o - },addI18n:function(o) { - return g.extend(n, o) - },translate:function(o) { - return n[o] || o - },isEmptyObj:function(o) { - if (o === b) { - return true - } - for (var p in o) { - return false - } - return true - },hasClass:function(q, p) { - var o; - if (q.className == "") { - return false - } - o = new RegExp("(^|\\s+)" + p + "(\\s+|$)"); - return o.test(q.className) - },addClass:function(p, o) { - if (!g.hasClass(p, o)) { - p.className = p.className == "" ? o : p.className.replace(/\s+$/, "") + " " + o - } - },removeClass:function(q, p) { - var o = new RegExp("(^|\\s+)" + p + "(\\s+|$)"); - q.className = q.className.replace(o, function(s, r, t) { - return r === " " && t === " " ? " " : "" - }) - },getStyle:function(p, o) { - if (p.currentStyle) { - return p.currentStyle[o] - } else { - if (window.getComputedStyle) { - return window.getComputedStyle(p, null)[o] - } - } - },addEvent:function(t, o, u) { - var s,r,q,p; - p = arguments[3]; - o = o.toLowerCase(); - if (e === b) { - e = "Plupload_" + g.guid() - } - if (t.addEventListener) { - s = u; - t.addEventListener(o, s, false) - } else { - if (t.attachEvent) { - s = function() { - var v = window.event; - if (!v.target) { - v.target = v.srcElement - } - v.preventDefault = h; - v.stopPropagation = k; - u(v) - }; - t.attachEvent("on" + o, s) - } - } - if (t[e] === b) { - t[e] = g.guid() - } - if (!d.hasOwnProperty(t[e])) { - d[t[e]] = {} - } - r = d[t[e]]; - if (!r.hasOwnProperty(o)) { - r[o] = [] - } - r[o].push({func:s,orig:u,key:p}) - },removeEvent:function(t, o) { - var r,u,q; - if (typeof(arguments[2]) == "function") { - u = arguments[2] - } else { - q = arguments[2] - } - o = o.toLowerCase(); - if (t[e] && d[t[e]] && d[t[e]][o]) { - r = d[t[e]][o] - } else { - return - } - for (var p = r.length - 1; p >= 0; p--) { - if (r[p].key === q || r[p].orig === u) { - if (t.detachEvent) { - t.detachEvent("on" + o, r[p].func) - } else { - if (t.removeEventListener) { - t.removeEventListener(o, r[p].func, false) - } - } - r[p].orig = null; - r[p].func = null; - r.splice(p, 1); - if (u !== b) { - break - } - } - } - if (!r.length) { - delete d[t[e]][o] - } - if (g.isEmptyObj(d[t[e]])) { - delete d[t[e]]; - try { - delete t[e] - } catch(s) { - t[e] = b - } - } - },removeAllEvents:function(p) { - var o = arguments[1]; - if (p[e] === b || !p[e]) { - return - } - g.each(d[p[e]], function(r, q) { - g.removeEvent(p, q, o) - }) - }}; - g.Uploader = function(r) { - var p = {},u,t = [],q; - u = new g.QueueProgress(); - r = g.extend({chunk_size:0,multipart:true,multi_selection:true,file_data_name:"file",filters:[]}, r); - function s() { - var w,x = 0,v; - if (this.state == g.STARTED) { - for (v = 0; v < t.length; v++) { - if (!w && t[v].status == g.QUEUED) { - w = t[v]; - w.status = g.UPLOADING; - if (this.trigger("BeforeUpload", w)) { - this.trigger("UploadFile", w) - } - } else { - x++ - } - } - if (x == t.length) { - this.stop(); - this.trigger("UploadComplete", t) - } - } - } - - function o() { - var w,v; - u.reset(); - for (w = 0; w < t.length; w++) { - v = t[w]; - if (v.size !== b) { - u.size += v.size; - u.loaded += v.loaded - } else { - u.size = b - } - if (v.status == g.DONE) { - u.uploaded++ - } else { - if (v.status == g.FAILED) { - u.failed++ - } else { - u.queued++ - } - } - } - if (u.size === b) { - u.percent = t.length > 0 ? Math.ceil(u.uploaded / t.length * 100) : 0 - } else { - u.bytesPerSec = Math.ceil(u.loaded / ((+new Date() - q || 1) / 1000)); - u.percent = u.size > 0 ? Math.ceil(u.loaded / u.size * 100) : 0 - } - } - - g.extend(this, {state:g.STOPPED,runtime:"",features:{},files:t,settings:r,total:u,id:g.guid(),init:function() { - var A = this,B,x,w,z = 0,y; - if (typeof(r.preinit) == "function") { - r.preinit(A) - } else { - g.each(r.preinit, function(D, C) { - A.bind(C, D) - }) - } - r.page_url = r.page_url || document.location.pathname.replace(/\/[^\/]+$/g, "/"); - if (!/^(\w+:\/\/|\/)/.test(r.url)) { - r.url = r.page_url + r.url - } - r.chunk_size = g.parseSize(r.chunk_size); - r.max_file_size = g.parseSize(r.max_file_size); - A.bind("FilesAdded", function(C, F) { - var E,D,H = 0,I,G = r.filters; - if (G && G.length) { - I = []; - g.each(G, function(J) { - g.each(J.extensions.split(/,/), function(K) { - if (/^\s*\*\s*$/.test(K)) { - I.push("\\.*") - } else { - I.push("\\." + K.replace(new RegExp("[" + ("/^$.*+?|()[]{}\\".replace(/./g, "\\$&")) + "]", "g"), "\\$&")) - } - }) - }); - I = new RegExp(I.join("|") + "$", "i") - } - for (E = 0; E < F.length; E++) { - D = F[E]; - D.loaded = 0; - D.percent = 0; - D.status = g.QUEUED; - if (I && !I.test(D.name)) { - C.trigger("Error", {code:g.FILE_EXTENSION_ERROR,message:g.translate("File extension error."),file:D}); - continue - } - if (D.size !== b && D.size > r.max_file_size) { - C.trigger("Error", {code:g.FILE_SIZE_ERROR,message:g.translate("File size error."),file:D}); - continue - } - t.push(D); - H++ - } - if (H) { - c(function() { - A.trigger("QueueChanged"); - A.refresh() - }, 1) - } else { - return false - } - }); - if (r.unique_names) { - A.bind("UploadFile", function(C, D) { - var F = D.name.match(/\.([^.]+)$/),E = "tmp"; - if (F) { - E = F[1] - } - D.target_name = D.id + "." + E - }) - } - A.bind("UploadProgress", function(C, D) { - D.percent = D.size > 0 ? Math.ceil(D.loaded / D.size * 100) : 100; - o() - }); - A.bind("StateChanged", function(C) { - if (C.state == g.STARTED) { - q = (+new Date()) - } else { - if (C.state == g.STOPPED) { - for (B = C.files.length - 1; B >= 0; B--) { - if (C.files[B].status == g.UPLOADING) { - C.files[B].status = g.QUEUED; - o() - } - } - } - } - }); - A.bind("QueueChanged", o); - A.bind("Error", function(C, D) { - if (D.file) { - D.file.status = g.FAILED; - o(); - if (C.state == g.STARTED) { - c(function() { - s.call(A) - }, 1) - } - } - }); - A.bind("FileUploaded", function(C, D) { - D.status = g.DONE; - D.loaded = D.size; - C.trigger("UploadProgress", D); - c(function() { - s.call(A) - }, 1) - }); - if (r.runtimes) { - x = []; - y = r.runtimes.split(/\s?,\s?/); - for (B = 0; B < y.length; B++) { - if (l[y[B]]) { - x.push(l[y[B]]) - } - } - } else { - x = l - } - function v() { - var F = x[z++],E,C,D; - if (F) { - E = F.getFeatures(); - C = A.settings.required_features; - if (C) { - C = C.split(","); - for (D = 0; D < C.length; D++) { - if (!E[C[D]]) { - v(); - return - } - } - } - F.init(A, function(G) { - if (G && G.success) { - A.features = E; - A.runtime = F.name; - A.trigger("Init", {runtime:F.name}); - A.trigger("PostInit"); - A.refresh() - } else { - v() - } - }) - } else { - A.trigger("Error", {code:g.INIT_ERROR,message:g.translate("Init error.")}) - } - } - - v(); - if (typeof(r.init) == "function") { - r.init(A) - } else { - g.each(r.init, function(D, C) { - A.bind(C, D) - }) - } - },refresh:function() { - this.trigger("Refresh") - },start:function() { - if (this.state != g.STARTED) { - this.state = g.STARTED; - this.trigger("StateChanged"); - s.call(this) - } - },stop:function() { - if (this.state != g.STOPPED) { - this.state = g.STOPPED; - this.trigger("StateChanged") - } - },getFile:function(w) { - var v; - for (v = t.length - 1; v >= 0; v--) { - if (t[v].id === w) { - return t[v] - } - } - },removeFile:function(w) { - var v; - for (v = t.length - 1; v >= 0; v--) { - if (t[v].id === w.id) { - return this.splice(v, 1)[0] - } - } - },splice:function(x, v) { - var w; - w = t.splice(x === b ? 0 : x, v === b ? t.length : v); - this.trigger("FilesRemoved", w); - this.trigger("QueueChanged"); - return w - },trigger:function(w) { - var y = p[w.toLowerCase()],x,v; - if (y) { - v = Array.prototype.slice.call(arguments); - v[0] = this; - for (x = 0; x < y.length; x++) { - if (y[x].func.apply(y[x].scope, v) === false) { - return false - } - } - } - return true - },hasEventListener:function(v) { - return !!p[v.toLowerCase()] - },bind:function(v, x, w) { - var y; - v = v.toLowerCase(); - y = p[v] || []; - y.push({func:x,scope:w || this}); - p[v] = y - },unbind:function(v) { - v = v.toLowerCase(); - var y = p[v],w,x = arguments[1]; - if (y) { - if (x !== b) { - for (w = y.length - 1; w >= 0; w--) { - if (y[w].func === x) { - y.splice(w, 1); - break - } - } - } else { - y = [] - } - if (!y.length) { - delete p[v] - } - } - },unbindAll:function() { - var v = this; - g.each(p, function(x, w) { - v.unbind(w) - }) - },destroy:function() { - this.trigger("Destroy"); - this.unbindAll() - }}) - }; - g.File = function(r, p, q) { - var o = this; - o.id = r; - o.name = p; - o.size = q; - o.loaded = 0; - o.percent = 0; - o.status = 0 - }; - g.Runtime = function() { - this.getFeatures = function() { - }; - this.init = function(o, p) { - } - }; - g.QueueProgress = function() { - var o = this; - o.size = 0; - o.loaded = 0; - o.uploaded = 0; - o.failed = 0; - o.queued = 0; - o.percent = 0; - o.bytesPerSec = 0; - o.reset = function() { - o.size = o.loaded = o.uploaded = o.failed = o.queued = o.percent = o.bytesPerSec = 0 - } - }; - g.runtimes = {}; - window.plupload = g -})(); -(function() { - if (window.google && google.gears) { - return - } - var a = null; - if (typeof GearsFactory != "undefined") { - a = new GearsFactory() - } else { - try { - a = new ActiveXObject("Gears.Factory"); - if (a.getBuildInfo().indexOf("ie_mobile") != -1) { - a.privateSetGlobalObject(this) - } - } catch(b) { - if ((typeof navigator.mimeTypes != "undefined") && navigator.mimeTypes["application/x-googlegears"]) { - a = document.createElement("object"); - a.style.display = "none"; - a.width = 0; - a.height = 0; - a.type = "application/x-googlegears"; - document.documentElement.appendChild(a) - } - } - } - if (!a) { - return - } - if (!window.google) { - window.google = {} - } - if (!google.gears) { - google.gears = {factory:a} - } -})(); -(function(e, b, c, d) { - var f = {}; - - function a(h, k, m) { - var g,j,l,o; - j = google.gears.factory.create("beta.canvas"); - try { - j.decode(h); - if (!k.width) { - k.width = j.width - } - if (!k.height) { - k.height = j.height - } - o = Math.min(width / j.width, height / j.height); - if (o < 1 || (o === 1 && m === "image/jpeg")) { - j.resize(Math.round(j.width * o), Math.round(j.height * o)); - if (k.quality) { - return j.encode(m, {quality:k.quality / 100}) - } - return j.encode(m) - } - } catch(n) { - } - return h - } - - c.runtimes.Gears = c.addRuntime("gears", {getFeatures:function() { - return{dragdrop:true,jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true} - },init:function(j, l) { - var k; - if (!e.google || !google.gears) { - return l({success:false}) - } - try { - k = google.gears.factory.create("beta.desktop") - } catch(h) { - return l({success:false}) - } - function g(o) { - var n,m,p = [],q; - for (m = 0; m < o.length; m++) { - n = o[m]; - q = c.guid(); - f[q] = n.blob; - p.push(new c.File(q, n.name, n.blob.length)) - } - j.trigger("FilesAdded", p) - } - - j.bind("PostInit", function() { - var n = j.settings,m = b.getElementById(n.drop_element); - if (m) { - c.addEvent(m, "dragover", function(o) { - k.setDropEffect(o, "copy"); - o.preventDefault() - }, j.id); - c.addEvent(m, "drop", function(p) { - var o = k.getDragData(p, "application/x-gears-files"); - if (o) { - g(o.files) - } - p.preventDefault() - }, j.id); - m = 0 - } - c.addEvent(b.getElementById(n.browse_button), "click", function(s) { - var r = [],p,o,q; - s.preventDefault(); - no_type_restriction:for (p = 0; p < n.filters.length; p++) { - q = n.filters[p].extensions.split(","); - for (o = 0; o < q.length; o++) { - if (q[o] === "*") { - r = []; - break no_type_restriction - } - r.push("." + q[o]) - } - } - k.openFiles(g, {singleFile:!n.multi_selection,filter:r}) - }, j.id) - }); - j.bind("UploadFile", function(s, p) { - var u = 0,t,q,r = 0,o = s.settings.resize,m; - if (o && /\.(png|jpg|jpeg)$/i.test(p.name)) { - f[p.id] = a(f[p.id], o, /\.png$/i.test(p.name) ? "image/png" : "image/jpeg") - } - p.size = f[p.id].length; - q = s.settings.chunk_size; - m = q > 0; - t = Math.ceil(p.size / q); - if (!m) { - q = p.size; - t = 1 - } - function n() { - var z,B,w = s.settings.multipart,v = 0,A = {name:p.target_name || p.name},x = s.settings.url; - - function y(D) { - var C,I = "----pluploadboundary" + c.guid(),F = "--",H = "\r\n",E,G; - if (w) { - z.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + I); - C = google.gears.factory.create("beta.blobbuilder"); - c.each(c.extend(A, s.settings.multipart_params), function(K, J) { - C.append(F + I + H + 'Content-Disposition: form-data; name="' + J + '"' + H + H); - C.append(K + H) - }); - G = c.mimeTypes[p.name.replace(/^.+\.([^.]+)/, "$1").toLowerCase()] || "application/octet-stream"; - C.append(F + I + H + 'Content-Disposition: form-data; name="' + s.settings.file_data_name + '"; filename="' + p.name + '"' + H + "Content-Type: " + G + H + H); - C.append(D); - C.append(H + F + I + F + H); - E = C.getAsBlob(); - v = E.length - D.length; - D = E - } - z.send(D) - } - - if (p.status == c.DONE || p.status == c.FAILED || s.state == c.STOPPED) { - return - } - if (m) { - A.chunk = u; - A.chunks = t - } - B = Math.min(q, p.size - (u * q)); - if (!w) { - x = c.buildUrl(s.settings.url, A) - } - z = google.gears.factory.create("beta.httprequest"); - z.open("POST", x); - if (!w) { - z.setRequestHeader("Content-Disposition", 'attachment; filename="' + p.name + '"'); - z.setRequestHeader("Content-Type", "application/octet-stream") - } - c.each(s.settings.headers, function(D, C) { - z.setRequestHeader(C, D) - }); - z.upload.onprogress = function(C) { - p.loaded = r + C.loaded - v; - s.trigger("UploadProgress", p) - }; - z.onreadystatechange = function() { - var C; - if (z.readyState == 4) { - if (z.status == 200) { - C = {chunk:u,chunks:t,response:z.responseText,status:z.status}; - s.trigger("ChunkUploaded", p, C); - if (C.cancelled) { - p.status = c.FAILED; - return - } - r += B; - if (++u >= t) { - p.status = c.DONE; - s.trigger("FileUploaded", p, {response:z.responseText,status:z.status}) - } else { - n() - } - } else { - s.trigger("Error", {code:c.HTTP_ERROR,message:c.translate("HTTP Error."),file:p,chunk:u,chunks:t,status:z.status}) - } - } - }; - if (u < t) { - y(f[p.id].slice(u * q, B)) - } - } - - n() - }); - j.bind("Destroy", function(m) { - var n,o,p = {browseButton:m.settings.browse_button,dropElm:m.settings.drop_element}; - for (n in p) { - o = b.getElementById(p[n]); - if (o) { - c.removeAllEvents(o, m.id) - } - } - }); - l({success:true}) - }}) -})(window, document, plupload); -(function(g, b, d, e) { - var a = {},h = {}; - - function c(o) { - var n,m = typeof o,j,l,k; - if (o === e || o === null) { - return"null" - } - if (m === "string") { - n = "\bb\tt\nn\ff\rr\"\"''\\\\"; - return'"' + o.replace(/([\u0080-\uFFFF\x00-\x1f\"])/g, function(r, q) { - var p = n.indexOf(q); - if (p + 1) { - return"\\" + n.charAt(p + 1) - } - r = q.charCodeAt().toString(16); - return"\\u" + "0000".substring(r.length) + r - }) + '"' - } - if (m == "object") { - j = o.length !== e; - n = ""; - if (j) { - for (l = 0; l < o.length; l++) { - if (n) { - n += "," - } - n += c(o[l]) - } - n = "[" + n + "]" - } else { - for (k in o) { - if (o.hasOwnProperty(k)) { - if (n) { - n += "," - } - n += c(k) + ":" + c(o[k]) - } - } - n = "{" + n + "}" - } - return n - } - return"" + o - } - - function f(s) { - var v = false,j = null,o = null,k,l,m,u,n,q = 0; - try { - try { - o = new ActiveXObject("AgControl.AgControl"); - if (o.IsVersionSupported(s)) { - v = true - } - o = null - } catch(r) { - var p = navigator.plugins["Silverlight Plug-In"]; - if (p) { - k = p.description; - if (k === "1.0.30226.2") { - k = "2.0.30226.2" - } - l = k.split("."); - while (l.length > 3) { - l.pop() - } - while (l.length < 4) { - l.push(0) - } - m = s.split("."); - while (m.length > 4) { - m.pop() - } - do{ - u = parseInt(m[q], 10); - n = parseInt(l[q], 10); - q++ - } while (q < m.length && u === n); - if (u <= n && !isNaN(u)) { - v = true - } - } - } - } catch(t) { - v = false - } - return v - } - - d.silverlight = {trigger:function(n, k) { - var m = a[n],l,j; - if (m) { - j = d.toArray(arguments).slice(1); - j[0] = "Silverlight:" + k; - setTimeout(function() { - m.trigger.apply(m, j) - }, 0) - } - }}; - d.runtimes.Silverlight = d.addRuntime("silverlight", {getFeatures:function() { - return{jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true} - },init:function(p, q) { - var o,m = "",n = p.settings.filters,l,k = b.body; - if (!f("2.0.31005.0") || (g.opera && g.opera.buildNumber)) { - q({success:false}); - return - } - h[p.id] = false; - a[p.id] = p; - o = b.createElement("div"); - o.id = p.id + "_silverlight_container"; - d.extend(o.style, {position:"absolute",top:"0px",background:p.settings.shim_bgcolor || "transparent",zIndex:99999,width:"100px",height:"100px",overflow:"hidden",opacity:p.settings.shim_bgcolor || b.documentMode > 8 ? "" : 0.01}); - o.className = "plupload silverlight"; - if (p.settings.container) { - k = b.getElementById(p.settings.container); - if (d.getStyle(k, "position") === "static") { - k.style.position = "relative" - } - } - k.appendChild(o); - for (l = 0; l < n.length; l++) { - m += (m != "" ? "|" : "") + n[l].title + " | *." + n[l].extensions.replace(/,/g, ";*.") - } - o.innerHTML = ''; - function j() { - return b.getElementById(p.id + "_silverlight").content.Upload - } - - p.bind("Silverlight:Init", function() { - var r,s = {}; - if (h[p.id]) { - return - } - h[p.id] = true; - p.bind("Silverlight:StartSelectFiles", function(t) { - r = [] - }); - p.bind("Silverlight:SelectFile", function(t, w, u, v) { - var x; - x = d.guid(); - s[x] = w; - s[w] = x; - r.push(new d.File(x, u, v)) - }); - p.bind("Silverlight:SelectSuccessful", function() { - if (r.length) { - p.trigger("FilesAdded", r) - } - }); - p.bind("Silverlight:UploadChunkError", function(t, w, u, x, v) { - p.trigger("Error", {code:d.IO_ERROR,message:"IO Error.",details:v,file:t.getFile(s[w])}) - }); - p.bind("Silverlight:UploadFileProgress", function(t, x, u, w) { - var v = t.getFile(s[x]); - if (v.status != d.FAILED) { - v.size = w; - v.loaded = u; - t.trigger("UploadProgress", v) - } - }); - p.bind("Refresh", function(t) { - var u,v,w; - u = b.getElementById(t.settings.browse_button); - if (u) { - v = d.getPos(u, b.getElementById(t.settings.container)); - w = d.getSize(u); - d.extend(b.getElementById(t.id + "_silverlight_container").style, {top:v.y + "px",left:v.x + "px",width:w.w + "px",height:w.h + "px"}) - } - }); - p.bind("Silverlight:UploadChunkSuccessful", function(t, w, u, z, y) { - var x,v = t.getFile(s[w]); - x = {chunk:u,chunks:z,response:y}; - t.trigger("ChunkUploaded", v, x); - if (v.status != d.FAILED) { - j().UploadNextChunk() - } - if (u == z - 1) { - v.status = d.DONE; - t.trigger("FileUploaded", v, {response:y}) - } - }); - p.bind("Silverlight:UploadSuccessful", function(t, w, u) { - var v = t.getFile(s[w]); - v.status = d.DONE; - t.trigger("FileUploaded", v, {response:u}) - }); - p.bind("FilesRemoved", function(t, v) { - var u; - for (u = 0; u < v.length; u++) { - j().RemoveFile(s[v[u].id]) - } - }); - p.bind("UploadFile", function(t, v) { - var w = t.settings,u = w.resize || {}; - j().UploadFile(s[v.id], t.settings.url, c({name:v.target_name || v.name,mime:d.mimeTypes[v.name.replace(/^.+\.([^.]+)/, "$1").toLowerCase()] || "application/octet-stream",chunk_size:w.chunk_size,image_width:u.width,image_height:u.height,image_quality:u.quality || 90,multipart:!!w.multipart,multipart_params:w.multipart_params || {},file_data_name:w.file_data_name,headers:w.headers})) - }); - p.bind("Silverlight:MouseEnter", function(t) { - var u,v; - u = b.getElementById(p.settings.browse_button); - v = t.settings.browse_button_hover; - if (u && v) { - d.addClass(u, v) - } - }); - p.bind("Silverlight:MouseLeave", function(t) { - var u,v; - u = b.getElementById(p.settings.browse_button); - v = t.settings.browse_button_hover; - if (u && v) { - d.removeClass(u, v) - } - }); - p.bind("Silverlight:MouseLeftButtonDown", function(t) { - var u,v; - u = b.getElementById(p.settings.browse_button); - v = t.settings.browse_button_active; - if (u && v) { - d.addClass(u, v); - d.addEvent(b.body, "mouseup", function() { - d.removeClass(u, v) - }) - } - }); - p.bind("Sliverlight:StartSelectFiles", function(t) { - var u,v; - u = b.getElementById(p.settings.browse_button); - v = t.settings.browse_button_active; - if (u && v) { - d.removeClass(u, v) - } - }); - p.bind("Destroy", function(t) { - var u; - d.removeAllEvents(b.body, t.id); - delete h[t.id]; - delete a[t.id]; - u = b.getElementById(t.id + "_silverlight_container"); - if (u) { - k.removeChild(u) - } - }); - q({success:true}) - }) - }}) -})(window, document, plupload); -(function(f, b, d, e) { - var a = {},g = {}; - - function c() { - var h; - try { - h = navigator.plugins["Shockwave Flash"]; - h = h.description - } catch(k) { - try { - h = new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version") - } catch(j) { - h = "0.0" - } - } - h = h.match(/\d+/g); - return parseFloat(h[0] + "." + h[1]) - } - - d.flash = {trigger:function(k, h, j) { - setTimeout(function() { - var n = a[k],m,l; - if (n) { - n.trigger("Flash:" + h, j) - } - }, 0) - }}; - d.runtimes.Flash = d.addRuntime("flash", {getFeatures:function() { - return{jpgresize:true,pngresize:true,maxWidth:8091,maxHeight:8091,chunks:true,progress:true,multipart:true,multi_selection:true} - },init:function(n, p) { - var l,m,h = 0,j = b.body; - if (c() < 10) { - p({success:false}); - return - } - g[n.id] = false; - a[n.id] = n; - l = b.getElementById(n.settings.browse_button); - m = b.createElement("div"); - m.id = n.id + "_flash_container"; - d.extend(m.style, {position:"absolute",top:"0px",background:n.settings.shim_bgcolor || "transparent",zIndex:99999,width:"100%",height:"100%"}); - m.className = "plupload flash"; - if (n.settings.container) { - j = b.getElementById(n.settings.container); - if (d.getStyle(j, "position") === "static") { - j.style.position = "relative" - } - } - j.appendChild(m); - (function() { - var q,r; - q = ''; - if (d.ua.ie) { - r = b.createElement("div"); - m.appendChild(r); - r.outerHTML = q; - r = null - } else { - m.innerHTML = q - } - }()); - function o() { - return b.getElementById(n.id + "_flash") - } - - function k() { - if (h++ > 5000) { - p({success:false}); - return - } - if (!g[n.id]) { - setTimeout(k, 1) - } - } - - k(); - l = m = null; - n.bind("Flash:Init", function() { - var r = {},q; - o().setFileFilters(n.settings.filters, n.settings.multi_selection); - if (g[n.id]) { - return - } - g[n.id] = true; - n.bind("UploadFile", function(s, u) { - var v = s.settings,t = n.settings.resize || {}; - o().uploadFile(r[u.id], v.url, {name:u.target_name || u.name,mime:d.mimeTypes[u.name.replace(/^.+\.([^.]+)/, "$1").toLowerCase()] || "application/octet-stream",chunk_size:v.chunk_size,width:t.width,height:t.height,quality:t.quality,multipart:v.multipart,multipart_params:v.multipart_params || {},file_data_name:v.file_data_name,format:/\.(jpg|jpeg)$/i.test(u.name) ? "jpg" : "png",headers:v.headers,urlstream_upload:v.urlstream_upload}) - }); - n.bind("Flash:UploadProcess", function(t, s) { - var u = t.getFile(r[s.id]); - if (u.status != d.FAILED) { - u.loaded = s.loaded; - u.size = s.size; - t.trigger("UploadProgress", u) - } - }); - n.bind("Flash:UploadChunkComplete", function(s, u) { - var v,t = s.getFile(r[u.id]); - v = {chunk:u.chunk,chunks:u.chunks,response:u.text}; - s.trigger("ChunkUploaded", t, v); - if (t.status != d.FAILED) { - o().uploadNextChunk() - } - if (u.chunk == u.chunks - 1) { - t.status = d.DONE; - s.trigger("FileUploaded", t, {response:u.text}) - } - }); - n.bind("Flash:SelectFiles", function(s, v) { - var u,t,w = [],x; - for (t = 0; t < v.length; t++) { - u = v[t]; - x = d.guid(); - r[x] = u.id; - r[u.id] = x; - w.push(new d.File(x, u.name, u.size)) - } - if (w.length) { - n.trigger("FilesAdded", w) - } - }); - n.bind("Flash:SecurityError", function(s, t) { - n.trigger("Error", {code:d.SECURITY_ERROR,message:d.translate("Security error."),details:t.message,file:n.getFile(r[t.id])}) - }); - n.bind("Flash:GenericError", function(s, t) { - n.trigger("Error", {code:d.GENERIC_ERROR,message:d.translate("Generic error."),details:t.message,file:n.getFile(r[t.id])}) - }); - n.bind("Flash:IOError", function(s, t) { - n.trigger("Error", {code:d.IO_ERROR,message:d.translate("IO error."),details:t.message,file:n.getFile(r[t.id])}) - }); - n.bind("Flash:ImageError", function(s, t) { - n.trigger("Error", {code:parseInt(t.code, 10),message:d.translate("Image error."),file:n.getFile(r[t.id])}) - }); - n.bind("Flash:StageEvent:rollOver", function(s) { - var t,u; - t = b.getElementById(n.settings.browse_button); - u = s.settings.browse_button_hover; - if (t && u) { - d.addClass(t, u) - } - }); - n.bind("Flash:StageEvent:rollOut", function(s) { - var t,u; - t = b.getElementById(n.settings.browse_button); - u = s.settings.browse_button_hover; - if (t && u) { - d.removeClass(t, u) - } - }); - n.bind("Flash:StageEvent:mouseDown", function(s) { - var t,u; - t = b.getElementById(n.settings.browse_button); - u = s.settings.browse_button_active; - if (t && u) { - d.addClass(t, u); - d.addEvent(b.body, "mouseup", function() { - d.removeClass(t, u) - }, s.id) - } - }); - n.bind("Flash:StageEvent:mouseUp", function(s) { - var t,u; - t = b.getElementById(n.settings.browse_button); - u = s.settings.browse_button_active; - if (t && u) { - d.removeClass(t, u) - } - }); - n.bind("Flash:ExifData", function(s, t) { - n.trigger("ExifData", n.getFile(r[t.id]), t.data) - }); - n.bind("Flash:GpsData", function(s, t) { - n.trigger("GpsData", n.getFile(r[t.id]), t.data) - }); - n.bind("QueueChanged", function(s) { - n.refresh() - }); - n.bind("FilesRemoved", function(s, u) { - var t; - for (t = 0; t < u.length; t++) { - o().removeFile(r[u[t].id]) - } - }); - n.bind("StateChanged", function(s) { - n.refresh() - }); - n.bind("Refresh", function(s) { - var t,u,v; - o().setFileFilters(n.settings.filters, n.settings.multi_selection); - t = b.getElementById(s.settings.browse_button); - if (t) { - u = d.getPos(t, b.getElementById(s.settings.container)); - v = d.getSize(t); - d.extend(b.getElementById(s.id + "_flash_container").style, {top:u.y + "px",left:u.x + "px",width:v.w + "px",height:v.h + "px"}) - } - }); - n.bind("Destroy", function(s) { - var t; - d.removeAllEvents(b.body, s.id); - delete g[s.id]; - delete a[s.id]; - t = b.getElementById(s.id + "_flash_container"); - if (t) { - j.removeChild(t) - } - }); - p({success:true}) - }) - }}) -})(window, document, plupload); -(function(a) { - a.runtimes.BrowserPlus = a.addRuntime("browserplus", {getFeatures:function() { - return{dragdrop:true,jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true} - },init:function(g, j) { - var e = window.BrowserPlus,h = {},d = g.settings,c = d.resize; - - function f(o) { - var n,m,k = [],l,p; - for (m = 0; m < o.length; m++) { - l = o[m]; - p = a.guid(); - h[p] = l; - k.push(new a.File(p, l.name, l.size)) - } - if (m) { - g.trigger("FilesAdded", k) - } - } - - function b() { - g.bind("PostInit", function() { - var n,l = d.drop_element,p = g.id + "_droptarget",k = document.getElementById(l),m; - - function q(s, r) { - e.DragAndDrop.AddDropTarget({id:s}, function(t) { - e.DragAndDrop.AttachCallbacks({id:s,hover:function(u) { - if (!u && r) { - r() - } - },drop:function(u) { - if (r) { - r() - } - f(u) - }}, function() { - }) - }) - } - - function o() { - document.getElementById(p).style.top = "-1000px" - } - - if (k) { - if (document.attachEvent && (/MSIE/gi).test(navigator.userAgent)) { - n = document.createElement("div"); - n.setAttribute("id", p); - a.extend(n.style, {position:"absolute",top:"-1000px",background:"red",filter:"alpha(opacity=0)",opacity:0}); - document.body.appendChild(n); - a.addEvent(k, "dragenter", function(s) { - var r,t; - r = document.getElementById(l); - t = a.getPos(r); - a.extend(document.getElementById(p).style, {top:t.y + "px",left:t.x + "px",width:r.offsetWidth + "px",height:r.offsetHeight + "px"}) - }); - q(p, o) - } else { - q(l) - } - } - a.addEvent(document.getElementById(d.browse_button), "click", function(w) { - var u = [],s,r,v = d.filters,t; - w.preventDefault(); - no_type_restriction:for (s = 0; s < v.length; s++) { - t = v[s].extensions.split(","); - for (r = 0; r < t.length; r++) { - if (t[r] === "*") { - u = []; - break no_type_restriction - } - u.push(a.mimeTypes[t[r]]) - } - } - e.FileBrowse.OpenBrowseDialog({mimeTypes:u}, function(x) { - if (x.success) { - f(x.value) - } - }) - }); - k = n = null - }); - g.bind("UploadFile", function(n, k) { - var m = h[k.id],s = {},l = n.settings.chunk_size,o,p = []; - - function r(t, v) { - var u; - if (k.status == a.FAILED) { - return - } - s.name = k.target_name || k.name; - if (l) { - s.chunk = "" + t; - s.chunks = "" + v - } - u = p.shift(); - e.Uploader.upload({url:n.settings.url,files:{file:u},cookies:document.cookies,postvars:a.extend(s, n.settings.multipart_params),progressCallback:function(y) { - var x,w = 0; - o[t] = parseInt(y.filePercent * u.size / 100, 10); - for (x = 0; x < o.length; x++) { - w += o[x] - } - k.loaded = w; - n.trigger("UploadProgress", k) - }}, function(x) { - var w,y; - if (x.success) { - w = x.value.statusCode; - if (l) { - n.trigger("ChunkUploaded", k, {chunk:t,chunks:v,response:x.value.body,status:w}) - } - if (p.length > 0) { - r(++t, v) - } else { - k.status = a.DONE; - n.trigger("FileUploaded", k, {response:x.value.body,status:w}); - if (w >= 400) { - n.trigger("Error", {code:a.HTTP_ERROR,message:a.translate("HTTP Error."),file:k,status:w}) - } - } - } else { - n.trigger("Error", {code:a.GENERIC_ERROR,message:a.translate("Generic Error."),file:k,details:x.error}) - } - }) - } - - function q(t) { - k.size = t.size; - if (l) { - e.FileAccess.chunk({file:t,chunkSize:l}, function(w) { - if (w.success) { - var x = w.value,u = x.length; - o = Array(u); - for (var v = 0; v < u; v++) { - o[v] = 0; - p.push(x[v]) - } - r(0, u) - } - }) - } else { - o = Array(1); - p.push(t); - r(0, 1) - } - } - - if (c && /\.(png|jpg|jpeg)$/i.test(k.name)) { - BrowserPlus.ImageAlter.transform({file:m,quality:c.quality || 90,actions:[ - {scale:{maxwidth:c.width,maxheight:c.height}} - ]}, function(t) { - if (t.success) { - q(t.value.file) - } - }) - } else { - q(m) - } - }); - j({success:true}) - } - - if (e) { - e.init(function(l) { - var k = [ - {service:"Uploader",version:"3"}, - {service:"DragAndDrop",version:"1"}, - {service:"FileBrowse",version:"1"}, - {service:"FileAccess",version:"2"} - ]; - if (c) { - k.push({service:"ImageAlter",version:"4"}) - } - if (l.success) { - e.require({services:k}, function(m) { - if (m.success) { - b() - } else { - j() - } - }) - } else { - j() - } - }) - } else { - j() - } - }}) -})(plupload); -(function(h, k, j, e) { - var c = {},g; - - function m(o, p) { - var n; - if ("FileReader" in h) { - n = new FileReader(); - n.readAsDataURL(o); - n.onload = function() { - p(n.result) - } - } else { - return p(o.getAsDataURL()) - } - } - - function l(o, p) { - var n; - if ("FileReader" in h) { - n = new FileReader(); - n.readAsBinaryString(o); - n.onload = function() { - p(n.result) - } - } else { - return p(o.getAsBinary()) - } - } - - function d(r, p, n, v) { - var q,o,u,s,t = this; - m(c[r.id], function(w) { - q = k.createElement("canvas"); - q.style.display = "none"; - k.body.appendChild(q); - o = q.getContext("2d"); - u = new Image(); - u.onerror = u.onabort = function() { - v({success:false}) - }; - u.onload = function() { - var B,x,z,y,A; - if (!p.width) { - p.width = u.width - } - if (!p.height) { - p.height = u.height - } - s = Math.min(p.width / u.width, p.height / u.height); - if (s < 1 || (s === 1 && n === "image/jpeg")) { - B = Math.round(u.width * s); - x = Math.round(u.height * s); - q.width = B; - q.height = x; - o.drawImage(u, 0, 0, B, x); - if (n === "image/jpeg") { - y = new f(atob(w.substring(w.indexOf("base64,") + 7))); - if (y.headers && y.headers.length) { - A = new a(); - if (A.init(y.get("exif")[0])) { - A.setExif("PixelXDimension", B); - A.setExif("PixelYDimension", x); - y.set("exif", A.getBinary()); - if (t.hasEventListener("ExifData")) { - t.trigger("ExifData", r, A.EXIF()) - } - if (t.hasEventListener("GpsData")) { - t.trigger("GpsData", r, A.GPS()) - } - } - } - if (p.quality) { - try { - w = q.toDataURL(n, p.quality / 100) - } catch(C) { - w = q.toDataURL(n) - } - } - } else { - w = q.toDataURL(n) - } - w = w.substring(w.indexOf("base64,") + 7); - w = atob(w); - if (y && y.headers && y.headers.length) { - w = y.restore(w); - y.purge() - } - q.parentNode.removeChild(q); - v({success:true,data:w}) - } else { - v({success:false}) - } - }; - u.src = w - }) - } - - j.runtimes.Html5 = j.addRuntime("html5", {getFeatures:function() { - var s,o,r,q,p,n; - o = r = p = n = false; - if (h.XMLHttpRequest) { - s = new XMLHttpRequest(); - r = !!s.upload; - o = !!(s.sendAsBinary || s.upload) - } - if (o) { - q = !!(s.sendAsBinary || (h.Uint8Array && h.ArrayBuffer)); - p = !!(File && (File.prototype.getAsDataURL || h.FileReader) && q); - n = !!(File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)) - } - g = j.ua.safari && j.ua.windows; - return{html5:o,dragdrop:(function() { - var t = k.createElement("div"); - return("draggable" in t) || ("ondragstart" in t && "ondrop" in t) - }()),jpgresize:p,pngresize:p,multipart:p || !!h.FileReader || !!h.FormData,canSendBinary:q,cantSendBlobInFormData:!!(j.ua.gecko && h.FormData && h.FileReader && !FileReader.prototype.readAsArrayBuffer),progress:r,chunks:n,multi_selection:!(j.ua.safari && j.ua.windows),triggerDialog:(j.ua.gecko && h.FormData || j.ua.webkit)} - },init:function(p, q) { - var n; - - function o(v) { - var t,s,u = [],w,r = {}; - for (s = 0; s < v.length; s++) { - t = v[s]; - if (r[t.name]) { - continue - } - r[t.name] = true; - w = j.guid(); - c[w] = t; - u.push(new j.File(w, t.fileName || t.name, t.fileSize || t.size)) - } - if (u.length) { - p.trigger("FilesAdded", u) - } - } - - n = this.getFeatures(); - if (!n.html5) { - q({success:false}); - return - } - p.bind("Init", function(v) { - var F,E,B = [],u,C,s = v.settings.filters,t,A,r = k.body,D; - F = k.createElement("div"); - F.id = v.id + "_html5_container"; - j.extend(F.style, {position:"absolute",background:p.settings.shim_bgcolor || "transparent",width:"100px",height:"100px",overflow:"hidden",zIndex:99999,opacity:p.settings.shim_bgcolor ? "" : 0}); - F.className = "plupload html5"; - if (p.settings.container) { - r = k.getElementById(p.settings.container); - if (j.getStyle(r, "position") === "static") { - r.style.position = "relative" - } - } - r.appendChild(F); - no_type_restriction:for (u = 0; u < s.length; u++) { - t = s[u].extensions.split(/,/); - for (C = 0; C < t.length; C++) { - if (t[C] === "*") { - B = []; - break no_type_restriction - } - A = j.mimeTypes[t[C]]; - if (A) { - B.push(A) - } - } - } - F.innerHTML = '"; - F.scrollTop = 100; - D = k.getElementById(p.id + "_html5"); - if (v.features.triggerDialog) { - j.extend(D.style, {position:"absolute",width:"100%",height:"100%"}) - } else { - j.extend(D.style, {cssFloat:"right",styleFloat:"right"}) - } - D.onchange = function() { - o(this.files); - this.value = "" - }; - E = k.getElementById(v.settings.browse_button); - if (E) { - var x = v.settings.browse_button_hover,z = v.settings.browse_button_active,w = v.features.triggerDialog ? E : F; - if (x) { - j.addEvent(w, "mouseover", function() { - j.addClass(E, x) - }, v.id); - j.addEvent(w, "mouseout", function() { - j.removeClass(E, x) - }, v.id) - } - if (z) { - j.addEvent(w, "mousedown", function() { - j.addClass(E, z) - }, v.id); - j.addEvent(k.body, "mouseup", function() { - j.removeClass(E, z) - }, v.id) - } - if (v.features.triggerDialog) { - j.addEvent(E, "click", function(y) { - k.getElementById(v.id + "_html5").click(); - y.preventDefault() - }, v.id) - } - } - }); - p.bind("PostInit", function() { - var r = k.getElementById(p.settings.drop_element); - if (r) { - if (g) { - j.addEvent(r, "dragenter", function(v) { - var u,s,t; - u = k.getElementById(p.id + "_drop"); - if (!u) { - u = k.createElement("input"); - u.setAttribute("type", "file"); - u.setAttribute("id", p.id + "_drop"); - u.setAttribute("multiple", "multiple"); - j.addEvent(u, "change", function() { - o(this.files); - j.removeEvent(u, "change", p.id); - u.parentNode.removeChild(u) - }, p.id); - r.appendChild(u) - } - s = j.getPos(r, k.getElementById(p.settings.container)); - t = j.getSize(r); - if (j.getStyle(r, "position") === "static") { - j.extend(r.style, {position:"relative"}) - } - j.extend(u.style, {position:"absolute",display:"block",top:0,left:0,width:t.w + "px",height:t.h + "px",opacity:0}) - }, p.id); - return - } - j.addEvent(r, "dragover", function(s) { - s.preventDefault() - }, p.id); - j.addEvent(r, "drop", function(t) { - var s = t.dataTransfer; - if (s && s.files) { - o(s.files) - } - t.preventDefault() - }, p.id) - } - }); - p.bind("Refresh", function(r) { - var s,t,u,w,v; - s = k.getElementById(p.settings.browse_button); - if (s) { - t = j.getPos(s, k.getElementById(r.settings.container)); - u = j.getSize(s); - w = k.getElementById(p.id + "_html5_container"); - j.extend(w.style, {top:t.y + "px",left:t.x + "px",width:u.w + "px",height:u.h + "px"}); - if (p.features.triggerDialog) { - if (j.getStyle(s, "position") === "static") { - j.extend(s.style, {position:"relative"}) - } - v = parseInt(j.getStyle(s, "z-index"), 10); - if (isNaN(v)) { - v = 0 - } - j.extend(s.style, {zIndex:v}); - j.extend(w.style, {zIndex:v - 1}) - } - } - }); - p.bind("UploadFile", function(r, t) { - var u = r.settings,x,s; - - function w(z, C, y) { - var A; - if (File.prototype.slice) { - try { - z.slice(); - return z.slice(C, y) - } catch(B) { - return z.slice(C, y - C) - } - } else { - if (A = File.prototype.webkitSlice || File.prototype.mozSlice) { - return A.call(z, C, y) - } else { - return null - } - } - } - - function v(z) { - var C = 0,B = 0,y = ("FileReader" in h) ? new FileReader : null; - - function A() { - var H,L,J,K,G,I,E,D = r.settings.url; - - function F(V) { - var S = 0,T = new XMLHttpRequest,W = T.upload,M = "----pluploadboundary" + j.guid(),N,O = "--",U = "\r\n",Q = ""; - if (W) { - W.onprogress = function(X) { - t.loaded = Math.min(t.size, B + X.loaded - S); - r.trigger("UploadProgress", t) - } - } - T.onreadystatechange = function() { - var X,Z; - if (T.readyState == 4) { - try { - X = T.status - } catch(Y) { - X = 0 - } - if (X >= 400) { - r.trigger("Error", {code:j.HTTP_ERROR,message:j.translate("HTTP Error."),file:t,status:X}) - } else { - if (J) { - Z = {chunk:C,chunks:J,response:T.responseText,status:X}; - r.trigger("ChunkUploaded", t, Z); - B += I; - if (Z.cancelled) { - t.status = j.FAILED; - return - } - t.loaded = Math.min(t.size, (C + 1) * G) - } else { - t.loaded = t.size - } - r.trigger("UploadProgress", t); - V = H = N = Q = null; - if (!J || ++C >= J) { - t.status = j.DONE; - r.trigger("FileUploaded", t, {response:T.responseText,status:X}) - } else { - A() - } - } - T = null - } - }; - if (r.settings.multipart && n.multipart) { - K.name = t.target_name || t.name; - T.open("post", D, true); - j.each(r.settings.headers, function(Y, X) { - T.setRequestHeader(X, Y) - }); - if (typeof(V) !== "string" && !!h.FormData) { - N = new FormData(); - j.each(j.extend(K, r.settings.multipart_params), function(Y, X) { - N.append(X, Y) - }); - N.append(r.settings.file_data_name, V); - T.send(N); - return - } - if (typeof(V) === "string") { - T.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + M); - j.each(j.extend(K, r.settings.multipart_params), function(Y, X) { - Q += O + M + U + 'Content-Disposition: form-data; name="' + X + '"' + U + U; - Q += unescape(encodeURIComponent(Y)) + U - }); - E = j.mimeTypes[t.name.replace(/^.+\.([^.]+)/, "$1").toLowerCase()] || "application/octet-stream"; - Q += O + M + U + 'Content-Disposition: form-data; name="' + r.settings.file_data_name + '"; filename="' + unescape(encodeURIComponent(t.name)) + '"' + U + "Content-Type: " + E + U + U + V + U + O + M + O + U; - S = Q.length - V.length; - V = Q; - if (T.sendAsBinary) { - T.sendAsBinary(V) - } else { - if (n.canSendBinary) { - var R = new Uint8Array(V.length); - for (var P = 0; P < V.length; P++) { - R[P] = (V.charCodeAt(P) & 255) - } - T.send(R.buffer) - } - } - return - } - } - D = j.buildUrl(r.settings.url, j.extend(K, r.settings.multipart_params)); - T.open("post", D, true); - T.setRequestHeader("Content-Type", "application/octet-stream"); - j.each(r.settings.headers, function(Y, X) { - T.setRequestHeader(X, Y) - }); - T.send(V) - } - - if (t.status == j.DONE || t.status == j.FAILED || r.state == j.STOPPED) { - return - } - K = {name:t.target_name || t.name}; - if (u.chunk_size && t.size > u.chunk_size && (n.chunks || typeof(z) == "string")) { - G = u.chunk_size; - J = Math.ceil(t.size / G); - I = Math.min(G, t.size - (C * G)); - if (typeof(z) == "string") { - H = z.substring(C * G, C * G + I) - } else { - H = w(z, C * G, C * G + I) - } - K.chunk = C; - K.chunks = J - } else { - I = t.size; - H = z - } - if (typeof(H) !== "string" && y && n.cantSendBlobInFormData && n.chunks && r.settings.chunk_size) { - y.onload = function() { - F(y.result) - }; - y.readAsBinaryString(H) - } else { - F(H) - } - } - - A() - } - - x = c[t.id]; - if (n.jpgresize && r.settings.resize && /\.(png|jpg|jpeg)$/i.test(t.name)) { - d.call(r, t, r.settings.resize, /\.png$/i.test(t.name) ? "image/png" : "image/jpeg", function(y) { - if (y.success) { - t.size = y.data.length; - v(y.data) - } else { - v(x) - } - }) - } else { - if (!n.chunks && n.jpgresize) { - l(x, v) - } else { - v(x) - } - } - }); - p.bind("Destroy", function(r) { - var t,u,s = k.body,v = {inputContainer:r.id + "_html5_container",inputFile:r.id + "_html5",browseButton:r.settings.browse_button,dropElm:r.settings.drop_element}; - for (t in v) { - u = k.getElementById(v[t]); - if (u) { - j.removeAllEvents(u, r.id) - } - } - j.removeAllEvents(k.body, r.id); - if (r.settings.container) { - s = k.getElementById(r.settings.container) - } - s.removeChild(k.getElementById(v.inputContainer)) - }); - q({success:true}) - }}); - function b() { - var q = false,o; - - function r(t, v) { - var s = q ? 0 : -8 * (v - 1),w = 0,u; - for (u = 0; u < v; u++) { - w |= (o.charCodeAt(t + u) << Math.abs(s + u * 8)) - } - return w - } - - function n(u, s, t) { - var t = arguments.length === 3 ? t : o.length - s - 1; - o = o.substr(0, s) + u + o.substr(t + s) - } - - function p(t, u, w) { - var x = "",s = q ? 0 : -8 * (w - 1),v; - for (v = 0; v < w; v++) { - x += String.fromCharCode((u >> Math.abs(s + v * 8)) & 255) - } - n(x, t, w) - } - - return{II:function(s) { - if (s === e) { - return q - } else { - q = s - } - },init:function(s) { - q = false; - o = s - },SEGMENT:function(s, u, t) { - switch (arguments.length) { - case 1: - return o.substr(s, o.length - s - 1); - case 2: - return o.substr(s, u); - case 3: - n(t, s, u); - break; - default: - return o - } - },BYTE:function(s) { - return r(s, 1) - },SHORT:function(s) { - return r(s, 2) - },LONG:function(s, t) { - if (t === e) { - return r(s, 4) - } else { - p(s, t, 4) - } - },SLONG:function(s) { - var t = r(s, 4); - return(t > 2147483647 ? t - 4294967296 : t) - },STRING:function(s, t) { - var u = ""; - for (t += s; s < t; s++) { - u += String.fromCharCode(r(s, 1)) - } - return u - }} - } - - function f(s) { - var u = {65505:{app:"EXIF",name:"APP1",signature:"Exif\0"},65506:{app:"ICC",name:"APP2",signature:"ICC_PROFILE\0"},65517:{app:"IPTC",name:"APP13",signature:"Photoshop 3.0\0"}},t = [],r,n,p = e,q = 0,o; - r = new b(); - r.init(s); - if (r.SHORT(0) !== 65496) { - return - } - n = 2; - o = Math.min(1048576, s.length); - while (n <= o) { - p = r.SHORT(n); - if (p >= 65488 && p <= 65495) { - n += 2; - continue - } - if (p === 65498 || p === 65497) { - break - } - q = r.SHORT(n + 2) + 2; - if (u[p] && r.STRING(n + 4, u[p].signature.length) === u[p].signature) { - t.push({hex:p,app:u[p].app.toUpperCase(),name:u[p].name.toUpperCase(),start:n,length:q,segment:r.SEGMENT(n, q)}) - } - n += q - } - r.init(null); - return{headers:t,restore:function(y) { - r.init(y); - var w = new f(y); - if (!w.headers) { - return false - } - for (var x = w.headers.length; x > 0; x--) { - var z = w.headers[x - 1]; - r.SEGMENT(z.start, z.length, "") - } - w.purge(); - n = r.SHORT(2) == 65504 ? 4 + r.SHORT(4) : 2; - for (var x = 0,v = t.length; x < v; x++) { - r.SEGMENT(n, 0, t[x].segment); - n += t[x].length - } - return r.SEGMENT() - },get:function(x) { - var y = []; - for (var w = 0,v = t.length; w < v; w++) { - if (t[w].app === x.toUpperCase()) { - y.push(t[w].segment) - } - } - return y - },set:function(y, x) { - var z = []; - if (typeof(x) === "string") { - z.push(x) - } else { - z = x - } - for (var w = ii = 0,v = t.length; w < v; w++) { - if (t[w].app === y.toUpperCase()) { - t[w].segment = z[ii]; - t[w].length = z[ii].length; - ii++ - } - if (ii >= z.length) { - break - } - } - },purge:function() { - t = []; - r.init(null) - }} - } - - function a() { - var q,n,o = {},t; - q = new b(); - n = {tiff:{274:"Orientation",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer"},exif:{36864:"ExifVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",36867:"DateTimeOriginal",33434:"ExposureTime",33437:"FNumber",34855:"ISOSpeedRatings",37377:"ShutterSpeedValue",37378:"ApertureValue",37383:"MeteringMode",37384:"LightSource",37385:"Flash",41986:"ExposureMode",41987:"WhiteBalance",41990:"SceneCaptureType",41988:"DigitalZoomRatio",41992:"Contrast",41993:"Saturation",41994:"Sharpness"},gps:{0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude"}}; - t = {ColorSpace:{1:"sRGB",0:"Uncalibrated"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{1:"Daylight",2:"Fliorescent",3:"Tungsten",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 -5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire.",1:"Flash fired.",5:"Strobe return light not detected.",7:"Strobe return light detected.",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},ExposureMode:{0:"Auto exposure",1:"Manual exposure",2:"Auto bracket"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},GPSLatitudeRef:{N:"North latitude",S:"South latitude"},GPSLongitudeRef:{E:"East longitude",W:"West longitude"}}; - function p(u, C) { - var w = q.SHORT(u),z,F,G,B,A,v,x,D,E = [],y = {}; - for (z = 0; z < w; z++) { - x = v = u + 12 * z + 2; - G = C[q.SHORT(x)]; - if (G === e) { - continue - } - B = q.SHORT(x += 2); - A = q.LONG(x += 2); - x += 4; - E = []; - switch (B) { - case 1: - case 7: - if (A > 4) { - x = q.LONG(x) + o.tiffHeader - } - for (F = 0; F < A; F++) { - E[F] = q.BYTE(x + F) - } - break; - case 2: - if (A > 4) { - x = q.LONG(x) + o.tiffHeader - } - y[G] = q.STRING(x, A - 1); - continue; - case 3: - if (A > 2) { - x = q.LONG(x) + o.tiffHeader - } - for (F = 0; F < A; F++) { - E[F] = q.SHORT(x + F * 2) - } - break; - case 4: - if (A > 1) { - x = q.LONG(x) + o.tiffHeader - } - for (F = 0; F < A; F++) { - E[F] = q.LONG(x + F * 4) - } - break; - case 5: - x = q.LONG(x) + o.tiffHeader; - for (F = 0; F < A; F++) { - E[F] = q.LONG(x + F * 4) / q.LONG(x + F * 4 + 4) - } - break; - case 9: - x = q.LONG(x) + o.tiffHeader; - for (F = 0; F < A; F++) { - E[F] = q.SLONG(x + F * 4) - } - break; - case 10: - x = q.LONG(x) + o.tiffHeader; - for (F = 0; F < A; F++) { - E[F] = q.SLONG(x + F * 4) / q.SLONG(x + F * 4 + 4) - } - break; - default: - continue - } - D = (A == 1 ? E[0] : E); - if (t.hasOwnProperty(G) && typeof D != "object") { - y[G] = t[G][D] - } else { - y[G] = D - } - } - return y - } - - function s() { - var v = e,u = o.tiffHeader; - q.II(q.SHORT(u) == 18761); - if (q.SHORT(u += 2) !== 42) { - return false - } - o.IFD0 = o.tiffHeader + q.LONG(u += 2); - v = p(o.IFD0, n.tiff); - o.exifIFD = ("ExifIFDPointer" in v ? o.tiffHeader + v.ExifIFDPointer : e); - o.gpsIFD = ("GPSInfoIFDPointer" in v ? o.tiffHeader + v.GPSInfoIFDPointer : e); - return true - } - - function r(w, u, z) { - var B,y,x,A = 0; - if (typeof(u) === "string") { - var v = n[w.toLowerCase()]; - for (hex in v) { - if (v[hex] === u) { - u = hex; - break - } - } - } - B = o[w.toLowerCase() + "IFD"]; - y = q.SHORT(B); - for (i = 0; i < y; i++) { - x = B + 12 * i + 2; - if (q.SHORT(x) == u) { - A = x + 8; - break - } - } - if (!A) { - return false - } - q.LONG(A, z); - return true - } - - return{init:function(u) { - o = {tiffHeader:10}; - if (u === e || !u.length) { - return false - } - q.init(u); - if (q.SHORT(0) === 65505 && q.STRING(4, 5).toUpperCase() === "EXIF\0") { - return s() - } - return false - },EXIF:function() { - var u; - u = p(o.exifIFD, n.exif); - if (u.ExifVersion) { - u.ExifVersion = String.fromCharCode(u.ExifVersion[0], u.ExifVersion[1], u.ExifVersion[2], u.ExifVersion[3]) - } - return u - },GPS:function() { - var u; - u = p(o.gpsIFD, n.gps); - if (u.GPSVersionID) { - u.GPSVersionID = u.GPSVersionID.join(".") - } - return u - },setExif:function(u, v) { - if (u !== "PixelXDimension" && u !== "PixelYDimension") { - return false - } - return r("exif", u, v) - },getBinary:function() { - return q.SEGMENT() - }} - } -})(window, document, plupload); -(function(d, a, b, c) { - function e(f) { - return a.getElementById(f) - } - - b.runtimes.Html4 = b.addRuntime("html4", {getFeatures:function() { - return{multipart:true,triggerDialog:(b.ua.gecko && d.FormData || b.ua.webkit)} - },init:function(f, g) { - f.bind("Init", function(p) { - var j = a.body,n,h = "javascript",k,x,q,z = [],r = /MSIE/.test(navigator.userAgent),t = [],m = p.settings.filters,o,l,s,w; - no_type_restriction:for (o = 0; o < m.length; o++) { - l = m[o].extensions.split(/,/); - for (w = 0; w < l.length; w++) { - if (l[w] === "*") { - t = []; - break no_type_restriction - } - s = b.mimeTypes[l[w]]; - if (s) { - t.push(s) - } - } - } - t = t.join(","); - function v() { - var C,A,y,B; - q = b.guid(); - z.push(q); - C = a.createElement("form"); - C.setAttribute("id", "form_" + q); - C.setAttribute("method", "post"); - C.setAttribute("enctype", "multipart/form-data"); - C.setAttribute("encoding", "multipart/form-data"); - C.setAttribute("target", p.id + "_iframe"); - C.style.position = "absolute"; - A = a.createElement("input"); - A.setAttribute("id", "input_" + q); - A.setAttribute("type", "file"); - A.setAttribute("accept", t); - A.setAttribute("size", 1); - B = e(p.settings.browse_button); - if (p.features.triggerDialog && B) { - b.addEvent(e(p.settings.browse_button), "click", function(D) { - A.click(); - D.preventDefault() - }, p.id) - } - b.extend(A.style, {width:"100%",height:"100%",opacity:0,fontSize:"999px"}); - b.extend(C.style, {overflow:"hidden"}); - y = p.settings.shim_bgcolor; - if (y) { - C.style.background = y - } - if (r) { - b.extend(A.style, {filter:"alpha(opacity=0)"}) - } - b.addEvent(A, "change", function(G) { - var E = G.target,D,F = [],H; - if (E.value) { - e("form_" + q).style.top = -1048575 + "px"; - D = E.value.replace(/\\/g, "/"); - D = D.substring(D.length, D.lastIndexOf("/") + 1); - F.push(new b.File(q, D)); - if (!p.features.triggerDialog) { - b.removeAllEvents(C, p.id) - } else { - b.removeEvent(B, "click", p.id) - } - b.removeEvent(A, "change", p.id); - v(); - if (F.length) { - f.trigger("FilesAdded", F) - } - } - }, p.id); - C.appendChild(A); - j.appendChild(C); - p.refresh() - } - - function u() { - var y = a.createElement("div"); - y.innerHTML = ''; - n = y.firstChild; - j.appendChild(n); - b.addEvent(n, "load", function(D) { - var E = D.target,C,A; - if (!k) { - return - } - try { - C = E.contentWindow.document || E.contentDocument || d.frames[E.id].document - } catch(B) { - p.trigger("Error", {code:b.SECURITY_ERROR,message:b.translate("Security error."),file:k}); - return - } - A = C.body.innerHTML; - if (A) { - k.status = b.DONE; - k.loaded = 1025; - k.percent = 100; - p.trigger("UploadProgress", k); - p.trigger("FileUploaded", k, {response:A}) - } - }, p.id) - } - - if (p.settings.container) { - j = e(p.settings.container); - if (b.getStyle(j, "position") === "static") { - j.style.position = "relative" - } - } - p.bind("UploadFile", function(y, B) { - var C,A; - if (B.status == b.DONE || B.status == b.FAILED || y.state == b.STOPPED) { - return - } - C = e("form_" + B.id); - A = e("input_" + B.id); - A.setAttribute("name", y.settings.file_data_name); - C.setAttribute("action", y.settings.url); - b.each(b.extend({name:B.target_name || B.name}, y.settings.multipart_params), function(F, D) { - var E = a.createElement("input"); - b.extend(E, {type:"hidden",name:D,value:F}); - C.insertBefore(E, C.firstChild) - }); - k = B; - e("form_" + q).style.top = -1048575 + "px"; - C.submit(); - C.parentNode.removeChild(C) - }); - p.bind("FileUploaded", function(y) { - y.refresh() - }); - p.bind("StateChanged", function(y) { - if (y.state == b.STARTED) { - u() - } - if (y.state == b.STOPPED) { - d.setTimeout(function() { - b.removeEvent(n, "load", y.id); - if (n.parentNode) { - n.parentNode.removeChild(n) - } - }, 0) - } - }); - p.bind("Refresh", function(A) { - var G,B,C,D,y,H,I,F,E; - G = e(A.settings.browse_button); - if (G) { - y = b.getPos(G, e(A.settings.container)); - H = b.getSize(G); - I = e("form_" + q); - F = e("input_" + q); - b.extend(I.style, {top:y.y + "px",left:y.x + "px",width:H.w + "px",height:H.h + "px"}); - if (A.features.triggerDialog) { - if (b.getStyle(G, "position") === "static") { - b.extend(G.style, {position:"relative"}) - } - E = parseInt(G.style.zIndex, 10); - if (isNaN(E)) { - E = 0 - } - b.extend(G.style, {zIndex:E}); - b.extend(I.style, {zIndex:E - 1}) - } - C = A.settings.browse_button_hover; - D = A.settings.browse_button_active; - B = A.features.triggerDialog ? G : I; - if (C) { - b.addEvent(B, "mouseover", function() { - b.addClass(G, C) - }, A.id); - b.addEvent(B, "mouseout", function() { - b.removeClass(G, C) - }, A.id) - } - if (D) { - b.addEvent(B, "mousedown", function() { - b.addClass(G, D) - }, A.id); - b.addEvent(a.body, "mouseup", function() { - b.removeClass(G, D) - }, A.id) - } - } - }); - f.bind("FilesRemoved", function(y, B) { - var A,C; - for (A = 0; A < B.length; A++) { - C = e("form_" + B[A].id); - if (C) { - C.parentNode.removeChild(C) - } - } - }); - f.bind("Destroy", function(y) { - var A,B,C,D = {inputContainer:"form_" + q,inputFile:"input_" + q,browseButton:y.settings.browse_button}; - for (A in D) { - B = e(D[A]); - if (B) { - b.removeAllEvents(B, y.id) - } - } - b.removeAllEvents(a.body, y.id); - b.each(z, function(F, E) { - C = e("form_" + F); - if (C) { - j.removeChild(C) - } - }) - }); - v() - }); - g({success:true}) - }}) -})(window, document, plupload); \ No newline at end of file +(function(){var f=0,l=[],n={},j={},a={"<":"lt",">":"gt","&":"amp",'"':"quot","'":"#39"},m=/[<>&\"\']/g,b,c=window.setTimeout,d={},e;function h(){this.returnValue=false}function k(){this.cancelBubble=true}(function(o){var p=o.split(/,/),q,s,r;for(q=0;q0){g.each(p,function(s,r){o[r]=s})}});return o},cleanName:function(o){var p,q;q=[/[\300-\306]/g,"A",/[\340-\346]/g,"a",/\307/g,"C",/\347/g,"c",/[\310-\313]/g,"E",/[\350-\353]/g,"e",/[\314-\317]/g,"I",/[\354-\357]/g,"i",/\321/g,"N",/\361/g,"n",/[\322-\330]/g,"O",/[\362-\370]/g,"o",/[\331-\334]/g,"U",/[\371-\374]/g,"u"];for(p=0;p0?"&":"?")+q}return p},each:function(r,s){var q,p,o;if(r){q=r.length;if(q===b){for(p in r){if(r.hasOwnProperty(p)){if(s(r[p],p)===false){return}}}}else{for(o=0;o1073741824){return Math.round(o/1073741824,1)+" GB"}if(o>1048576){return Math.round(o/1048576,1)+" MB"}if(o>1024){return Math.round(o/1024,1)+" KB"}return o+" b"},getPos:function(p,t){var u=0,s=0,w,v=document,q,r;p=p;t=t||v.body;function o(C){var A,B,z=0,D=0;if(C){B=C.getBoundingClientRect();A=v.compatMode==="CSS1Compat"?v.documentElement:v.body;z=B.left+A.scrollLeft;D=B.top+A.scrollTop}return{x:z,y:D}}if(p&&p.getBoundingClientRect&&(navigator.userAgent.indexOf("MSIE")>0&&v.documentMode!==8)){q=o(p);r=o(t);return{x:q.x-r.x,y:q.y-r.y}}w=p;while(w&&w!=t&&w.nodeType){u+=w.offsetLeft||0;s+=w.offsetTop||0;w=w.offsetParent}w=p.parentNode;while(w&&w!=t&&w.nodeType){u-=w.scrollLeft||0;s-=w.scrollTop||0;w=w.parentNode}return{x:u,y:s}},getSize:function(o){return{w:o.offsetWidth||o.clientWidth,h:o.offsetHeight||o.clientHeight}},parseSize:function(o){var p;if(typeof(o)=="string"){o=/^([0-9]+)([mgk]?)$/.exec(o.toLowerCase().replace(/[^0-9mkg]/g,""));p=o[2];o=+o[1];if(p=="g"){o*=1073741824}if(p=="m"){o*=1048576}if(p=="k"){o*=1024}}return o},xmlEncode:function(o){return o?(""+o).replace(m,function(p){return a[p]?"&"+a[p]+";":p}):o},toArray:function(q){var p,o=[];for(p=0;p=0;p--){if(r[p].key===q||r[p].orig===u){if(t.detachEvent){t.detachEvent("on"+o,r[p].func)}else{if(t.removeEventListener){t.removeEventListener(o,r[p].func,false)}}r[p].orig=null;r[p].func=null;r.splice(p,1);if(u!==b){break}}}if(!r.length){delete d[t[e]][o]}if(g.isEmptyObj(d[t[e]])){delete d[t[e]];try{delete t[e]}catch(s){t[e]=b}}},removeAllEvents:function(p){var o=arguments[1];if(p[e]===b||!p[e]){return}g.each(d[p[e]],function(r,q){g.removeEvent(p,q,o)})}};g.Uploader=function(r){var p={},u,t=[],q;u=new g.QueueProgress();r=g.extend({chunk_size:0,multipart:true,multi_selection:true,file_data_name:"file",filters:[]},r);function s(){var w,x=0,v;if(this.state==g.STARTED){for(v=0;v0?Math.ceil(u.uploaded/t.length*100):0}else{u.bytesPerSec=Math.ceil(u.loaded/((+new Date()-q||1)/1000));u.percent=u.size>0?Math.ceil(u.loaded/u.size*100):0}}g.extend(this,{state:g.STOPPED,runtime:"",features:{},files:t,settings:r,total:u,id:g.guid(),init:function(){var A=this,B,x,w,z=0,y;if(typeof(r.preinit)=="function"){r.preinit(A)}else{g.each(r.preinit,function(D,C){A.bind(C,D)})}r.page_url=r.page_url||document.location.pathname.replace(/\/[^\/]+$/g,"/");if(!/^(\w+:\/\/|\/)/.test(r.url)){r.url=r.page_url+r.url}r.chunk_size=g.parseSize(r.chunk_size);r.max_file_size=g.parseSize(r.max_file_size);A.bind("FilesAdded",function(C,F){var E,D,H=0,I,G=r.filters;if(G&&G.length){I=[];g.each(G,function(J){g.each(J.extensions.split(/,/),function(K){if(/^\s*\*\s*$/.test(K)){I.push("\\.*")}else{I.push("\\."+K.replace(new RegExp("["+("/^$.*+?|()[]{}\\".replace(/./g,"\\$&"))+"]","g"),"\\$&"))}})});I=new RegExp(I.join("|")+"$","i")}for(E=0;Er.max_file_size){C.trigger("Error",{code:g.FILE_SIZE_ERROR,message:g.translate("File size error."),file:D});continue}t.push(D);H++}if(H){c(function(){A.trigger("QueueChanged");A.refresh()},1)}else{return false}});if(r.unique_names){A.bind("UploadFile",function(C,D){var F=D.name.match(/\.([^.]+)$/),E="tmp";if(F){E=F[1]}D.target_name=D.id+"."+E})}A.bind("UploadProgress",function(C,D){D.percent=D.size>0?Math.ceil(D.loaded/D.size*100):100;o()});A.bind("StateChanged",function(C){if(C.state==g.STARTED){q=(+new Date())}else{if(C.state==g.STOPPED){for(B=C.files.length-1;B>=0;B--){if(C.files[B].status==g.UPLOADING){C.files[B].status=g.QUEUED;o()}}}}});A.bind("QueueChanged",o);A.bind("Error",function(C,D){if(D.file){D.file.status=g.FAILED;o();if(C.state==g.STARTED){c(function(){s.call(A)},1)}}});A.bind("FileUploaded",function(C,D){D.status=g.DONE;D.loaded=D.size;C.trigger("UploadProgress",D);c(function(){s.call(A)},1)});if(r.runtimes){x=[];y=r.runtimes.split(/\s?,\s?/);for(B=0;B=0;v--){if(t[v].id===w){return t[v]}}},removeFile:function(w){var v;for(v=t.length-1;v>=0;v--){if(t[v].id===w.id){return this.splice(v,1)[0]}}},splice:function(x,v){var w;w=t.splice(x===b?0:x,v===b?t.length:v);this.trigger("FilesRemoved",w);this.trigger("QueueChanged");return w},trigger:function(w){var y=p[w.toLowerCase()],x,v;if(y){v=Array.prototype.slice.call(arguments);v[0]=this;for(x=0;x=0;w--){if(y[w].func===x){y.splice(w,1);break}}}else{y=[]}if(!y.length){delete p[v]}}},unbindAll:function(){var v=this;g.each(p,function(x,w){v.unbind(w)})},destroy:function(){this.trigger("Destroy");this.unbindAll()}})};g.File=function(r,p,q){var o=this;o.id=r;o.name=p;o.size=q;o.loaded=0;o.percent=0;o.status=0};g.Runtime=function(){this.getFeatures=function(){};this.init=function(o,p){}};g.QueueProgress=function(){var o=this;o.size=0;o.loaded=0;o.uploaded=0;o.failed=0;o.queued=0;o.percent=0;o.bytesPerSec=0;o.reset=function(){o.size=o.loaded=o.uploaded=o.failed=o.queued=o.percent=o.bytesPerSec=0}};g.runtimes={};window.plupload=g})();(function(){if(window.google&&google.gears){return}var a=null;if(typeof GearsFactory!="undefined"){a=new GearsFactory()}else{try{a=new ActiveXObject("Gears.Factory");if(a.getBuildInfo().indexOf("ie_mobile")!=-1){a.privateSetGlobalObject(this)}}catch(b){if((typeof navigator.mimeTypes!="undefined")&&navigator.mimeTypes["application/x-googlegears"]){a=document.createElement("object");a.style.display="none";a.width=0;a.height=0;a.type="application/x-googlegears";document.documentElement.appendChild(a)}}}if(!a){return}if(!window.google){window.google={}}if(!google.gears){google.gears={factory:a}}})();(function(e,b,c,d){var f={};function a(h,k,m){var g,j,l,o;j=google.gears.factory.create("beta.canvas");try{j.decode(h);if(!k.width){k.width=j.width}if(!k.height){k.height=j.height}o=Math.min(width/j.width,height/j.height);if(o<1||(o===1&&m==="image/jpeg")){j.resize(Math.round(j.width*o),Math.round(j.height*o));if(k.quality){return j.encode(m,{quality:k.quality/100})}return j.encode(m)}}catch(n){}return h}c.runtimes.Gears=c.addRuntime("gears",{getFeatures:function(){return{dragdrop:true,jpgresize:true,pngresize:true,chunks:true,progress:true,multipart:true,multi_selection:true}},init:function(j,l){var k;if(!e.google||!google.gears){return l({success:false})}try{k=google.gears.factory.create("beta.desktop")}catch(h){return l({success:false})}function g(o){var n,m,p=[],q;for(m=0;m0;t=Math.ceil(p.size/q);if(!m){q=p.size;t=1}function n(){var z,B,w=s.settings.multipart,v=0,A={name:p.target_name||p.name},x=s.settings.url;function y(D){var C,I="----pluploadboundary"+c.guid(),F="--",H="\r\n",E,G;if(w){z.setRequestHeader("Content-Type","multipart/form-data; boundary="+I);C=google.gears.factory.create("beta.blobbuilder");c.each(c.extend(A,s.settings.multipart_params),function(K,J){C.append(F+I+H+'Content-Disposition: form-data; name="'+J+'"'+H+H);C.append(K+H)});G=c.mimeTypes[p.name.replace(/^.+\.([^.]+)/,"$1").toLowerCase()]||"application/octet-stream";C.append(F+I+H+'Content-Disposition: form-data; name="'+s.settings.file_data_name+'"; filename="'+p.name+'"'+H+"Content-Type: "+G+H+H);C.append(D);C.append(H+F+I+F+H);E=C.getAsBlob();v=E.length-D.length;D=E}z.send(D)}if(p.status==c.DONE||p.status==c.FAILED||s.state==c.STOPPED){return}if(m){A.chunk=u;A.chunks=t}B=Math.min(q,p.size-(u*q));if(!w){x=c.buildUrl(s.settings.url,A)}z=google.gears.factory.create("beta.httprequest");z.open("POST",x);if(!w){z.setRequestHeader("Content-Disposition",'attachment; filename="'+p.name+'"');z.setRequestHeader("Content-Type","application/octet-stream")}c.each(s.settings.headers,function(D,C){z.setRequestHeader(C,D)});z.upload.onprogress=function(C){p.loaded=r+C.loaded-v;s.trigger("UploadProgress",p)};z.onreadystatechange=function(){var C;if(z.readyState==4){if(z.status==200){C={chunk:u,chunks:t,response:z.responseText,status:z.status};s.trigger("ChunkUploaded",p,C);if(C.cancelled){p.status=c.FAILED;return}r+=B;if(++u>=t){p.status=c.DONE;s.trigger("FileUploaded",p,{response:z.responseText,status:z.status})}else{n()}}else{s.trigger("Error",{code:c.HTTP_ERROR,message:c.translate("HTTP Error."),file:p,chunk:u,chunks:t,status:z.status})}}};if(u3){l.pop()}while(l.length<4){l.push(0)}m=s.split(".");while(m.length>4){m.pop()}do{u=parseInt(m[q],10);n=parseInt(l[q],10);q++}while(q8?"":0.01});o.className="plupload silverlight";if(p.settings.container){k=b.getElementById(p.settings.container);if(d.getStyle(k,"position")==="static"){k.style.position="relative"}}k.appendChild(o);for(l=0;l';function j(){return b.getElementById(p.id+"_silverlight").content.Upload}p.bind("Silverlight:Init",function(){var r,s={};if(h[p.id]){return}h[p.id]=true;p.bind("Silverlight:StartSelectFiles",function(t){r=[]});p.bind("Silverlight:SelectFile",function(t,w,u,v){var x;x=d.guid();s[x]=w;s[w]=x;r.push(new d.File(x,u,v))});p.bind("Silverlight:SelectSuccessful",function(){if(r.length){p.trigger("FilesAdded",r)}});p.bind("Silverlight:UploadChunkError",function(t,w,u,x,v){p.trigger("Error",{code:d.IO_ERROR,message:"IO Error.",details:v,file:t.getFile(s[w])})});p.bind("Silverlight:UploadFileProgress",function(t,x,u,w){var v=t.getFile(s[x]);if(v.status!=d.FAILED){v.size=w;v.loaded=u;t.trigger("UploadProgress",v)}});p.bind("Refresh",function(t){var u,v,w;u=b.getElementById(t.settings.browse_button);if(u){v=d.getPos(u,b.getElementById(t.settings.container));w=d.getSize(u);d.extend(b.getElementById(t.id+"_silverlight_container").style,{top:v.y+"px",left:v.x+"px",width:w.w+"px",height:w.h+"px"})}});p.bind("Silverlight:UploadChunkSuccessful",function(t,w,u,z,y){var x,v=t.getFile(s[w]);x={chunk:u,chunks:z,response:y};t.trigger("ChunkUploaded",v,x);if(v.status!=d.FAILED){j().UploadNextChunk()}if(u==z-1){v.status=d.DONE;t.trigger("FileUploaded",v,{response:y})}});p.bind("Silverlight:UploadSuccessful",function(t,w,u){var v=t.getFile(s[w]);v.status=d.DONE;t.trigger("FileUploaded",v,{response:u})});p.bind("FilesRemoved",function(t,v){var u;for(u=0;u';if(d.ua.ie){r=b.createElement("div");m.appendChild(r);r.outerHTML=q;r=null}else{m.innerHTML=q}}());function o(){return b.getElementById(n.id+"_flash")}function k(){if(h++>5000){p({success:false});return}if(!g[n.id]){setTimeout(k,1)}}k();l=m=null;n.bind("Flash:Init",function(){var r={},q;o().setFileFilters(n.settings.filters,n.settings.multi_selection);if(g[n.id]){return}g[n.id]=true;n.bind("UploadFile",function(s,u){var v=s.settings,t=n.settings.resize||{};o().uploadFile(r[u.id],v.url,{name:u.target_name||u.name,mime:d.mimeTypes[u.name.replace(/^.+\.([^.]+)/,"$1").toLowerCase()]||"application/octet-stream",chunk_size:v.chunk_size,width:t.width,height:t.height,quality:t.quality,multipart:v.multipart,multipart_params:v.multipart_params||{},file_data_name:v.file_data_name,format:/\.(jpg|jpeg)$/i.test(u.name)?"jpg":"png",headers:v.headers,urlstream_upload:v.urlstream_upload})});n.bind("Flash:UploadProcess",function(t,s){var u=t.getFile(r[s.id]);if(u.status!=d.FAILED){u.loaded=s.loaded;u.size=s.size;t.trigger("UploadProgress",u)}});n.bind("Flash:UploadChunkComplete",function(s,u){var v,t=s.getFile(r[u.id]);v={chunk:u.chunk,chunks:u.chunks,response:u.text};s.trigger("ChunkUploaded",t,v);if(t.status!=d.FAILED){o().uploadNextChunk()}if(u.chunk==u.chunks-1){t.status=d.DONE;s.trigger("FileUploaded",t,{response:u.text})}});n.bind("Flash:SelectFiles",function(s,v){var u,t,w=[],x;for(t=0;t0){r(++t,v)}else{k.status=a.DONE;n.trigger("FileUploaded",k,{response:x.value.body,status:w});if(w>=400){n.trigger("Error",{code:a.HTTP_ERROR,message:a.translate("HTTP Error."),file:k,status:w})}}}else{n.trigger("Error",{code:a.GENERIC_ERROR,message:a.translate("Generic Error."),file:k,details:x.error})}})}function q(t){k.size=t.size;if(l){e.FileAccess.chunk({file:t,chunkSize:l},function(w){if(w.success){var x=w.value,u=x.length;o=Array(u);for(var v=0;v";F.scrollTop=100;D=k.getElementById(p.id+"_html5");if(v.features.triggerDialog){j.extend(D.style,{position:"absolute",width:"100%",height:"100%"})}else{j.extend(D.style,{cssFloat:"right",styleFloat:"right"})}D.onchange=function(){o(this.files);this.value=""};E=k.getElementById(v.settings.browse_button);if(E){var x=v.settings.browse_button_hover,z=v.settings.browse_button_active,w=v.features.triggerDialog?E:F;if(x){j.addEvent(w,"mouseover",function(){j.addClass(E,x)},v.id);j.addEvent(w,"mouseout",function(){j.removeClass(E,x)},v.id)}if(z){j.addEvent(w,"mousedown",function(){j.addClass(E,z)},v.id);j.addEvent(k.body,"mouseup",function(){j.removeClass(E,z)},v.id)}if(v.features.triggerDialog){j.addEvent(E,"click",function(y){k.getElementById(v.id+"_html5").click();y.preventDefault()},v.id)}}});p.bind("PostInit",function(){var r=k.getElementById(p.settings.drop_element);if(r){if(g){j.addEvent(r,"dragenter",function(v){var u,s,t;u=k.getElementById(p.id+"_drop");if(!u){u=k.createElement("input");u.setAttribute("type","file");u.setAttribute("id",p.id+"_drop");u.setAttribute("multiple","multiple");j.addEvent(u,"change",function(){o(this.files);j.removeEvent(u,"change",p.id);u.parentNode.removeChild(u)},p.id);r.appendChild(u)}s=j.getPos(r,k.getElementById(p.settings.container));t=j.getSize(r);if(j.getStyle(r,"position")==="static"){j.extend(r.style,{position:"relative"})}j.extend(u.style,{position:"absolute",display:"block",top:0,left:0,width:t.w+"px",height:t.h+"px",opacity:0})},p.id);return}j.addEvent(r,"dragover",function(s){s.preventDefault()},p.id);j.addEvent(r,"drop",function(t){var s=t.dataTransfer;if(s&&s.files){o(s.files)}t.preventDefault()},p.id)}});p.bind("Refresh",function(r){var s,t,u,w,v;s=k.getElementById(p.settings.browse_button);if(s){t=j.getPos(s,k.getElementById(r.settings.container));u=j.getSize(s);w=k.getElementById(p.id+"_html5_container");j.extend(w.style,{top:t.y+"px",left:t.x+"px",width:u.w+"px",height:u.h+"px"});if(p.features.triggerDialog){if(j.getStyle(s,"position")==="static"){j.extend(s.style,{position:"relative"})}v=parseInt(j.getStyle(s,"z-index"),10);if(isNaN(v)){v=0}j.extend(s.style,{zIndex:v});j.extend(w.style,{zIndex:v-1})}}});p.bind("UploadFile",function(r,t){var u=r.settings,x,s;function w(z,C,y){var A;if(File.prototype.slice){try{z.slice();return z.slice(C,y)}catch(B){return z.slice(C,y-C)}}else{if(A=File.prototype.webkitSlice||File.prototype.mozSlice){return A.call(z,C,y)}else{return null}}}function v(z){var C=0,B=0,y=("FileReader" in h)?new FileReader:null;function A(){var H,L,J,K,G,I,E,D=r.settings.url;function F(V){var S=0,T=new XMLHttpRequest,W=T.upload,M="----pluploadboundary"+j.guid(),N,O="--",U="\r\n",Q="";if(W){W.onprogress=function(X){t.loaded=Math.min(t.size,B+X.loaded-S);r.trigger("UploadProgress",t)}}T.onreadystatechange=function(){var X,Z;if(T.readyState==4){try{X=T.status}catch(Y){X=0}if(X>=400){r.trigger("Error",{code:j.HTTP_ERROR,message:j.translate("HTTP Error."),file:t,status:X})}else{if(J){Z={chunk:C,chunks:J,response:T.responseText,status:X};r.trigger("ChunkUploaded",t,Z);B+=I;if(Z.cancelled){t.status=j.FAILED;return}t.loaded=Math.min(t.size,(C+1)*G)}else{t.loaded=t.size}r.trigger("UploadProgress",t);V=H=N=Q=null;if(!J||++C>=J){t.status=j.DONE;r.trigger("FileUploaded",t,{response:T.responseText,status:X})}else{A()}}T=null}};if(r.settings.multipart&&n.multipart){K.name=t.target_name||t.name;T.open("post",D,true);j.each(r.settings.headers,function(Y,X){T.setRequestHeader(X,Y)});if(typeof(V)!=="string"&&!!h.FormData){N=new FormData();j.each(j.extend(K,r.settings.multipart_params),function(Y,X){N.append(X,Y)});N.append(r.settings.file_data_name,V);T.send(N);return}if(typeof(V)==="string"){T.setRequestHeader("Content-Type","multipart/form-data; boundary="+M);j.each(j.extend(K,r.settings.multipart_params),function(Y,X){Q+=O+M+U+'Content-Disposition: form-data; name="'+X+'"'+U+U;Q+=unescape(encodeURIComponent(Y))+U});E=j.mimeTypes[t.name.replace(/^.+\.([^.]+)/,"$1").toLowerCase()]||"application/octet-stream";Q+=O+M+U+'Content-Disposition: form-data; name="'+r.settings.file_data_name+'"; filename="'+unescape(encodeURIComponent(t.name))+'"'+U+"Content-Type: "+E+U+U+V+U+O+M+O+U;S=Q.length-V.length;V=Q;if(T.sendAsBinary){T.sendAsBinary(V)}else{if(n.canSendBinary){var R=new Uint8Array(V.length);for(var P=0;Pu.chunk_size&&(n.chunks||typeof(z)=="string")){G=u.chunk_size;J=Math.ceil(t.size/G);I=Math.min(G,t.size-(C*G));if(typeof(z)=="string"){H=z.substring(C*G,C*G+I)}else{H=w(z,C*G,C*G+I)}K.chunk=C;K.chunks=J}else{I=t.size;H=z}if(typeof(H)!=="string"&&y&&n.cantSendBlobInFormData&&n.chunks&&r.settings.chunk_size){y.onload=function(){F(y.result)};y.readAsBinaryString(H)}else{F(H)}}A()}x=c[t.id];if(n.jpgresize&&r.settings.resize&&/\.(png|jpg|jpeg)$/i.test(t.name)){d.call(r,t,r.settings.resize,/\.png$/i.test(t.name)?"image/png":"image/jpeg",function(y){if(y.success){t.size=y.data.length;v(y.data)}else{v(x)}})}else{if(!n.chunks&&n.jpgresize){l(x,v)}else{v(x)}}});p.bind("Destroy",function(r){var t,u,s=k.body,v={inputContainer:r.id+"_html5_container",inputFile:r.id+"_html5",browseButton:r.settings.browse_button,dropElm:r.settings.drop_element};for(t in v){u=k.getElementById(v[t]);if(u){j.removeAllEvents(u,r.id)}}j.removeAllEvents(k.body,r.id);if(r.settings.container){s=k.getElementById(r.settings.container)}s.removeChild(k.getElementById(v.inputContainer))});q({success:true})}});function b(){var q=false,o;function r(t,v){var s=q?0:-8*(v-1),w=0,u;for(u=0;u>Math.abs(s+v*8))&255)}n(x,t,w)}return{II:function(s){if(s===e){return q}else{q=s}},init:function(s){q=false;o=s},SEGMENT:function(s,u,t){switch(arguments.length){case 1:return o.substr(s,o.length-s-1);case 2:return o.substr(s,u);case 3:n(t,s,u);break;default:return o}},BYTE:function(s){return r(s,1)},SHORT:function(s){return r(s,2)},LONG:function(s,t){if(t===e){return r(s,4)}else{p(s,t,4)}},SLONG:function(s){var t=r(s,4);return(t>2147483647?t-4294967296:t)},STRING:function(s,t){var u="";for(t+=s;s=65488&&p<=65495){n+=2;continue}if(p===65498||p===65497){break}q=r.SHORT(n+2)+2;if(u[p]&&r.STRING(n+4,u[p].signature.length)===u[p].signature){t.push({hex:p,app:u[p].app.toUpperCase(),name:u[p].name.toUpperCase(),start:n,length:q,segment:r.SEGMENT(n,q)})}n+=q}r.init(null);return{headers:t,restore:function(y){r.init(y);var w=new f(y);if(!w.headers){return false}for(var x=w.headers.length;x>0;x--){var z=w.headers[x-1];r.SEGMENT(z.start,z.length,"")}w.purge();n=r.SHORT(2)==65504?4+r.SHORT(4):2;for(var x=0,v=t.length;x=z.length){break}}},purge:function(){t=[];r.init(null)}}}function a(){var q,n,o={},t;q=new b();n={tiff:{274:"Orientation",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer"},exif:{36864:"ExifVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",36867:"DateTimeOriginal",33434:"ExposureTime",33437:"FNumber",34855:"ISOSpeedRatings",37377:"ShutterSpeedValue",37378:"ApertureValue",37383:"MeteringMode",37384:"LightSource",37385:"Flash",41986:"ExposureMode",41987:"WhiteBalance",41990:"SceneCaptureType",41988:"DigitalZoomRatio",41992:"Contrast",41993:"Saturation",41994:"Sharpness"},gps:{0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude"}};t={ColorSpace:{1:"sRGB",0:"Uncalibrated"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{1:"Daylight",2:"Fliorescent",3:"Tungsten",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 -5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire.",1:"Flash fired.",5:"Strobe return light not detected.",7:"Strobe return light detected.",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},ExposureMode:{0:"Auto exposure",1:"Manual exposure",2:"Auto bracket"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},GPSLatitudeRef:{N:"North latitude",S:"South latitude"},GPSLongitudeRef:{E:"East longitude",W:"West longitude"}};function p(u,C){var w=q.SHORT(u),z,F,G,B,A,v,x,D,E=[],y={};for(z=0;z4){x=q.LONG(x)+o.tiffHeader}for(F=0;F4){x=q.LONG(x)+o.tiffHeader}y[G]=q.STRING(x,A-1);continue;case 3:if(A>2){x=q.LONG(x)+o.tiffHeader}for(F=0;F1){x=q.LONG(x)+o.tiffHeader}for(F=0;F
diff --git a/docviewerapi/src/com/log4ic/DocViewer.java b/docviewerapi/src/com/log4ic/DocViewer.java index ae7c81a..42f9030 100644 --- a/docviewerapi/src/com/log4ic/DocViewer.java +++ b/docviewerapi/src/com/log4ic/DocViewer.java @@ -2,21 +2,21 @@ import com.log4ic.entity.IDocAttachment; import com.log4ic.services.IAttachmentService; -import com.log4ic.utils.FileUtils; import com.log4ic.utils.convert.*; import com.log4ic.utils.convert.office.OfficeConverter; import com.log4ic.utils.convert.pdf.PDFConverter; -import com.log4ic.utils.filter.SplitSwfFileFilter; +import com.log4ic.utils.io.FileUtils; import com.log4ic.utils.security.XXTEA; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.artofsolving.jodconverter.document.DocumentFormat; import org.artofsolving.jodconverter.office.OfficeConnectionProtocol; import java.io.*; -import java.util.LinkedList; -import java.util.Properties; -import java.util.Random; +import java.util.*; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * @author: 张立鑫 @@ -119,9 +119,9 @@ public static String getCurrentSecretKey() { public static IAttachmentService getAttachmentService() throws ClassNotFoundException, IllegalAccessException, InstantiationException { if (attachmentService == null) { - synchronized (ATTACHMENT_SERVICE){ + synchronized (ATTACHMENT_SERVICE) { if (attachmentService == null) { - Class serviceClass = Class.forName(ATTACHMENT_SERVICE); + Class serviceClass = DocViewer.class.getClassLoader().loadClass(ATTACHMENT_SERVICE); attachmentService = (IAttachmentService) serviceClass.newInstance(); } } @@ -139,8 +139,11 @@ public static boolean isSupport(String fileExtends) { return OfficeConverter.isSupport(fileExtends); } + public static List getAllSupport() { + return OfficeConverter.getAllSupport(); + } - DocViewer() { + protected DocViewer() { } public static void initialize() throws Exception { @@ -153,7 +156,17 @@ public static void initialize() throws Exception { LOGGER.debug("初始化office转换服务配置...."); OfficeConverter.setOfficeHome(new String(properties.getProperty(baseOfficeConfigSpace + "home", OfficeConverter.getOfficeHome()).getBytes("ISO-8859-1"), "UTF-8")); //OfficeConverter.setHost(new String(properties.getProperty(baseOfficeConfigSpace + "host", OfficeConverter.getHost()).getBytes("ISO-8859-1"), "UTF-8")); - OfficeConverter.setPort(Integer.parseInt(properties.getProperty(baseOfficeConfigSpace + "port", OfficeConverter.getPort() + ""))); + String portStr = properties.getProperty(baseOfficeConfigSpace + "port"); + if(StringUtils.isNotBlank(portStr)){ + String[] portStrs = portStr.split(","); + int[] ports = new int[portStrs.length]; + int i = 0; + for(String s : portStrs){ + ports[i] = Integer.parseInt(s); + i++; + } + OfficeConverter.setPort(ports); + } String protocol = properties.getProperty(baseOfficeConfigSpace + "protocol"); if (StringUtils.isNotBlank(protocol)) { protocol = protocol.toLowerCase(); @@ -240,24 +253,28 @@ public static void initialize() throws Exception { public static void destroy() throws Exception { OfficeConverter.stopService(); + officeQueue.safeShutdown(); + pdfQueue.safeShutdown(); } - private synchronized static void checkWorker(ConvertWorker worker) throws Exception { + private synchronized static boolean checkWorker(ConvertWorker worker) throws Exception { worker.setOutputPath(OUTPUT_PATH); - if (worker.getInFile() == null) { - throw new Exception("input file is null"); - } + return worker.getInFile() != null; } public synchronized static void addConvertWorker(PDFConvertWorker worker) throws Exception { - checkWorker(worker); + if (!checkWorker(worker)) { + return; + } synchronized (pdfQueue) { pdfQueue.addWorker(worker); } } public synchronized static void addConvertWorker(OfficeConvertWorker worker) throws Exception { - checkWorker(worker); + if (!checkWorker(worker)) { + return; + } synchronized (officeQueue) { officeQueue.addWorker(worker); } @@ -280,7 +297,8 @@ public synchronized static int getNextId() { private static final ConvertQueue officeQueue = new ConvertQueue(OFFICE_POOL_MAX_THREAD, "office_queue"); private static final ConvertQueue pdfQueue = new ConvertQueue(PDF_POOL_MAX_THREAD, "pdf_queue"); - + private static Map fileIds = new HashMap(); + private static final byte[] lock = new byte[0]; /** * 获取转换后的文档目录 如果没有转换则进行转换 @@ -290,84 +308,129 @@ public synchronized static int getNextId() { * @throws Exception */ public static File getDoc(int id) throws Exception { - if (DocViewer.isConverting(id) || hasDoc(id)) { - while (DocViewer.isConverting(id)) { - Thread.sleep(500); - } + if (hasDoc(id)) { + LOGGER.debug(id + " return doc"); return new File(OUTPUT_PATH + id); } - ConvertWorker worker = null; - if (pdfQueue.isWaiting(id)) { - worker = (ConvertWorker) pdfQueue.getWaitingWorker(id); - if (worker != null) { - pdfQueue.removeWaitingWorker(worker); - } - } else if (officeQueue.isWaiting(id)) { - worker = (ConvertWorker) officeQueue.getWaitingWorker(id); - if (worker != null) { - officeQueue.removeWaitingWorker(worker); + String docId = id + "_doc"; + + if (!fileIds.containsKey(docId)) { + synchronized (lock) { + if (!fileIds.containsKey(docId)) { + fileIds.put(docId, new ReentrantLock()); + } } } + Lock lk = fileIds.get(docId); - File in = null; + lk.lock(); + try { + if (hasDoc(id)) { + LOGGER.debug(id + " return doc"); + return new File(OUTPUT_PATH + id); + } + ConvertWorker worker = null; + if (pdfQueue.isWaiting(id)) { + worker = (ConvertWorker) pdfQueue.getWaitingWorker(id); + if (worker != null) { + pdfQueue.removeWaitingWorker(worker); + } - if (worker != null) { - in = worker.getInFile(); - } else { - in = getDocFileFromSource(id); - } + } else if (officeQueue.isWaiting(id)) { + worker = (ConvertWorker) officeQueue.getWaitingWorker(id); + if (worker != null) { + officeQueue.removeWaitingWorker(worker); + } + } - if (in == null) { - return null; - } + File in; + + if (worker != null) { + in = worker.getInFile(); + } else { + in = getDocFileFromSource(id); + } - return DocViewerConverter.toSwf(in, OUTPUT_PATH); + if (in == null) { + return null; + } + return DocViewerConverter.toSwf(in, OUTPUT_PATH); + } finally { + lk.unlock(); + fileIds.remove(docId); + } } public synchronized static boolean isConverting(int id) { - - LinkedList fileList = DocViewerConverter.getRunningQueue(); - - synchronized (fileList) { + DocViewerConverter.getRunningQueueLock().lock(); + try { + LinkedList fileList = DocViewerConverter.getRunningQueue(); for (File f : fileList) { - if (FileUtils.getFilePrefix(f).equals(id + "")) { + if (FileUtils.getFilePrefix(f).equals(id)) { return true; } } + } finally { + DocViewerConverter.getRunningQueueLock().unlock(); } - return officeQueue.isRunning(id) || pdfQueue.isRunning(id); } public static File getPDFDoc(int id) throws Exception { if (DocViewer.hasDocDir(id)) { - while (DocViewer.isConverting(id)) { - Thread.sleep(500); - } File file = new File(OUTPUT_PATH + id + File.separator + id + ".pdf"); if (file.exists()) { + LOGGER.debug(id + " return pdf"); return file; } } - ConvertWorker worker = null; - if (pdfQueue.isWaiting(id)) { - worker = (ConvertWorker) pdfQueue.getWaitingWorker(id); - if (worker != null) { - pdfQueue.removeWaitingWorker(worker); - } + String pdfId = id + "_pdf"; + if (!fileIds.containsKey(pdfId)) { + synchronized (lock) { + if (!fileIds.containsKey(pdfId)) { + fileIds.put(pdfId, new ReentrantLock()); + } + } } + Lock lk = fileIds.get(pdfId); + + lk.lock(); + try { + if (DocViewer.hasDocDir(id)) { + File file = new File(OUTPUT_PATH + id + File.separator + id + ".pdf"); + if (file.exists()) { + LOGGER.debug(id + " return pdf"); + return file; + } + } + ConvertWorker worker = null; + if (pdfQueue.isWaiting(id)) { + worker = (ConvertWorker) pdfQueue.getWaitingWorker(id); + if (worker != null) { + pdfQueue.removeWaitingWorker(worker); + } + + } - File in = null; + File in; - if (worker != null) { - in = worker.getInFile(); - } else { - in = getDocFileFromSource(id); - } + if (worker != null) { + in = worker.getInFile(); + } else { + in = getDocFileFromSource(id); + } - return DocViewerConverter.toPDF(in, OUTPUT_PATH); + + if (in == null) { + return null; + } + return DocViewerConverter.toPDF(in, OUTPUT_PATH); + } finally { + lk.unlock(); + fileIds.remove(pdfId); + } } /** @@ -461,15 +524,8 @@ public static boolean hasDocDir(int id) { File dir = new File(OUTPUT_PATH + id); - if (!dir.exists()) { - return false; - } - - if (dir.isDirectory()) { - return true; - } + return dir.exists() && dir.isDirectory(); - return false; } @@ -481,11 +537,8 @@ public static boolean hasPDF(int id) { File file = new File(OUTPUT_PATH + id + File.separator + id + ".pdf"); - if (!file.exists()) { - return false; - } + return file.exists(); - return true; } /** @@ -502,12 +555,12 @@ public static boolean hasDoc(int id) throws Exception { File dir = new File(OUTPUT_PATH + id + File.separator); if (isSplitPage()) { if (dir.exists()) { - if (dir.listFiles(new SplitSwfFileFilter()).length == getDocPageCount(id, false)) { + if (getDocPageCount(id, false) > 0) { return true; } } } else { - File swf = new File(dir.getPath() + "page.swf"); + File swf = new File(dir.getPath() + File.separator + "page.swf"); if (swf.exists() && swf.isFile() && swf.length() > 0) { return true; } @@ -579,24 +632,17 @@ public static String getRandomKey(int length) { } - public static void main(String[] args) { -// String path = "/home/icode/test/"; + public static void main(String[] args) throws Exception { + DocViewer.initialize(); + OfficeConverter converter = new OfficeConverter(); try { - - System.out.print( - isSupport("xxpdf") - ); -// byte[] keyValue = "abcs".getBytes("UTF-8"); -// DocViewer.addConvertWorker(new File(path + "3489682.pdf")); -// DocViewer.addConvertWorker(new File(path + "3692243.pdf")); -// DocViewer.addConvertWorker(new File(path + "7828624.pdf")); -// DocViewer.addConvertWorker(new File(path + "test.pdf")); -// DocViewer.addConvertWorker(new File(path + "test.txt")); -// DocViewer.addConvertWorker(new File(path + "test1.doc")); - } catch (Exception e) { + converter.convert("/home/icode/Desktop/b.txt", "/home/icode/Desktop/b.pdf"); + } catch (IOException e) { e.printStackTrace(); } + DocViewer.destroy(); + } diff --git a/docviewerapi/src/com/log4ic/entity/IDocAttachment.java b/docviewerapi/src/com/log4ic/entity/IDocAttachment.java index 19c2472..3784b54 100644 --- a/docviewerapi/src/com/log4ic/entity/IDocAttachment.java +++ b/docviewerapi/src/com/log4ic/entity/IDocAttachment.java @@ -1,6 +1,8 @@ package com.log4ic.entity; +import com.log4ic.enums.Permissions; + import java.io.InputStream; /** @@ -30,13 +32,6 @@ public interface IDocAttachment { */ public Integer getPageCount(); - /** - * 获得附件摘要属性值 - * - * @return 附件摘要属性值 - */ - public String getDigest(); - /** * 获得文件类型属性值 * @@ -50,4 +45,11 @@ public interface IDocAttachment { * @return 附件内容属性值 */ public InputStream getContentStream(); + + /** + * 获取该文档权限 + * + * @return + */ + public Permissions getPermissions(); } diff --git a/docviewerapi/src/com/log4ic/services/IAttachmentService.java b/docviewerapi/src/com/log4ic/services/IAttachmentService.java index 1408d70..4847014 100644 --- a/docviewerapi/src/com/log4ic/services/IAttachmentService.java +++ b/docviewerapi/src/com/log4ic/services/IAttachmentService.java @@ -11,6 +11,7 @@ * @date: 11-8-29 上午10:34 */ public interface IAttachmentService { + /** * 获取附件 * diff --git a/docviewerapi/src/com/log4ic/utils/FileUtils.java b/docviewerapi/src/com/log4ic/utils/FileUtils.java deleted file mode 100644 index 26d4c99..0000000 --- a/docviewerapi/src/com/log4ic/utils/FileUtils.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.log4ic.utils; - -import java.io.*; -import java.util.Properties; - -/** - * @author: 张立鑫 - * @version: 1 - * @date: 11-8-25 上午10:17 - */ -public class FileUtils { - - public static Properties getProperties(String config) throws Exception { - Properties properties = new Properties(); - //获取class文件夹 - ClassLoader loader = FileUtils.class.getClassLoader(); - //加载文件 - InputStream is = loader.getResourceAsStream(config); - if (is == null) { - throw new Exception("properties is not found"); - } - //读取 - properties.load(is); - return properties; - } - - public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator"); - - - public static String getFilePrefix(String fileFullName) { - int splitIndex = fileFullName.lastIndexOf("."); - return fileFullName.substring(0, splitIndex); - } - - public static String getFilePrefix(File file) { - String fileFullName = file.getName(); - return getFilePrefix(fileFullName); - } - - public static String getFileSuffix(String fileFullName) { - int splitIndex = fileFullName.lastIndexOf("."); - return fileFullName.substring(splitIndex + 1); - } - - public static String getFileSuffix(File file) { - String fileFullName = file.getName(); - return getFileSuffix(fileFullName); - } - - - public static String appendFileSeparator(String path) { - return path + (path.lastIndexOf(File.separator) == path.length() - 1 ? "" : File.separator); - } - - /** - * 文件转化为字节数组 - */ - public static byte[] getBytesFromFile(File f) { - if (f == null) { - return null; - } - try { - FileInputStream stream = new FileInputStream(f); - ByteArrayOutputStream out = new ByteArrayOutputStream(1000); - byte[] b = new byte[1000]; - int n; - while ((n = stream.read(b)) != -1) - out.write(b, 0, n); - stream.close(); - out.close(); - return out.toByteArray(); - } catch (IOException e) { - } - return null; - } - - /** - * 把字节数组保存为一个文件 - */ - public static File getFileFromBytes(byte[] b, String outputFile) { - BufferedOutputStream stream = null; - File file = null; - try { - file = new File(outputFile); - FileOutputStream fstream = new FileOutputStream(file); - stream = new BufferedOutputStream(fstream); - stream.write(b); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e1) { - e1.printStackTrace(); - } - } - } - return file; - } - - /** - * 从字节数组获取对象 - */ - public static Object getObjectFromBytes(byte[] objBytes) throws Exception { - if (objBytes == null || objBytes.length == 0) { - return null; - } - ByteArrayInputStream bi = new ByteArrayInputStream(objBytes); - ObjectInputStream oi = new ObjectInputStream(bi); - return oi.readObject(); - } - - /** - * 从对象获取一个字节数组 - */ - public static byte[] getBytesFromObject(Serializable obj) throws Exception { - if (obj == null) { - return null; - } - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - ObjectOutputStream oo = new ObjectOutputStream(bo); - oo.writeObject(obj); - return bo.toByteArray(); - } - -} diff --git a/docviewerapi/src/com/log4ic/utils/convert/DocViewerConverter.java b/docviewerapi/src/com/log4ic/utils/convert/DocViewerConverter.java index bc7837e..ee021c8 100644 --- a/docviewerapi/src/com/log4ic/utils/convert/DocViewerConverter.java +++ b/docviewerapi/src/com/log4ic/utils/convert/DocViewerConverter.java @@ -1,12 +1,16 @@ package com.log4ic.utils.convert; import com.log4ic.DocViewer; -import com.log4ic.utils.FileUtils; import com.log4ic.utils.convert.office.OfficeConverter; import com.log4ic.utils.convert.pdf.PDFConverter; +import com.log4ic.utils.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.io.File; import java.util.LinkedList; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * @author: 张立鑫 @@ -15,9 +19,11 @@ public class DocViewerConverter { private static OfficeConverter officeConverter; private static PDFConverter pdfConverter; - private static Object lock = new Object(); + private static final Object lock = new Object(); + private static final Log logger = LogFactory.getLog(DocViewerConverter.class); private static LinkedList runningQueue = new LinkedList(); + private static final Lock queueLock = new ReentrantLock(); public static File deploy(File file, String outPath) { @@ -34,61 +40,82 @@ public static File deploy(File file, String outPath) { return dir; } + public static Lock getRunningQueueLock() { + return queueLock; + } + public static LinkedList getRunningQueue() { return runningQueue; } - /*** + /** * 转换为swf + * * @param file * @param outPath * @return 返回转换后输出文件目录 * @throws Exception */ public static File toSwf(File file, String outPath) throws Exception { - synchronized (lock) { + File pdf = file; + if (pdfConverter == null) { + queueLock.lock(); if (pdfConverter == null) { //PDFConverter.loadConfig(); pdfConverter = new PDFConverter(); } + queueLock.unlock(); } + queueLock.lock(); + runningQueue.add(file); + queueLock.unlock(); try { - runningQueue.add(file); + logger.debug("toSwf after add size:" + runningQueue.size() + ".[" + file.getName() + "]"); String suffix = FileUtils.getFileSuffix(file); - File pdf; if (suffix == null) { throw new Exception("The file not has a suffix!"); } if (!suffix.toLowerCase().equals("pdf")) { pdf = toPDF(file, outPath); - } else { - pdf = file; } return pdfConverter.convert(pdf, outPath, DocViewer.isSplitPage(), false); } finally { - runningQueue.remove(file); + queueLock.lock(); + boolean isok = runningQueue.remove(file); + + logger.debug("toSwf after remove size:" + runningQueue.size() + ". isok:" + isok); + queueLock.unlock(); } } public static File toPDF(File file, String outPath) throws Exception { - synchronized (lock) { + if (officeConverter == null) { + queueLock.lock(); if (officeConverter == null) { officeConverter = new OfficeConverter(); } + queueLock.unlock(); } + queueLock.lock(); + runningQueue.add(file); + queueLock.unlock(); try { - runningQueue.add(file); + logger.debug("toPDF after add size:" + runningQueue.size() + ".[" + file.getName() + "]"); File pdf = null; File dir = deploy(file, outPath); - pdf = new File(FileUtils.appendFileSeparator(dir.getPath()) + FileUtils.getFilePrefix(file) + ".pdf"); + pdf = new File(dir.getPath() + File.separator + FileUtils.getFilePrefix(file) + ".pdf"); if (!pdf.exists()) { pdf = officeConverter.toPDF(file, dir.getPath()); } + return pdf; } finally { - runningQueue.remove(file); + queueLock.lock(); + boolean isok = runningQueue.remove(file); + logger.debug("toPDF after remove size:" + runningQueue.size() + ". isok:" + isok); + queueLock.unlock(); } } } diff --git a/docviewerapi/src/com/log4ic/utils/convert/OfficeConvertWorker.java b/docviewerapi/src/com/log4ic/utils/convert/OfficeConvertWorker.java index 92a3056..426d932 100644 --- a/docviewerapi/src/com/log4ic/utils/convert/OfficeConvertWorker.java +++ b/docviewerapi/src/com/log4ic/utils/convert/OfficeConvertWorker.java @@ -38,7 +38,7 @@ public void run() { OfficeConverter converter = new OfficeConverter(); try { in = converter.toPDF(in, dir.getPath()); - DocViewer.addConvertWorker(new PDFConvertWorker(0, in, out, splitePage)); + DocViewer.addConvertWorker(new PDFConvertWorker(this.getId(), in, out, splitePage)); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/OfficeConverter.java b/docviewerapi/src/com/log4ic/utils/convert/office/OfficeConverter.java index c1e1526..f8a77d3 100644 --- a/docviewerapi/src/com/log4ic/utils/convert/office/OfficeConverter.java +++ b/docviewerapi/src/com/log4ic/utils/convert/office/OfficeConverter.java @@ -1,11 +1,11 @@ package com.log4ic.utils.convert.office; -import com.log4ic.utils.FileUtils; -import com.sun.star.comp.helper.BootstrapException; +import com.log4ic.utils.convert.office.document.OfficeDocumentFormatRegistry; +import com.log4ic.utils.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.artofsolving.jodconverter.OfficeDocumentConverter; -import org.artofsolving.jodconverter.document.DefaultDocumentFormatRegistry; +import org.artofsolving.jodconverter.document.DocumentFormat; import org.artofsolving.jodconverter.document.DocumentFormatRegistry; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeConnectionProtocol; @@ -14,7 +14,8 @@ import java.io.File; import java.io.IOException; import java.net.ConnectException; -import java.util.Properties; +import java.nio.charset.Charset; +import java.util.List; /** * @author: 张立鑫 @@ -43,16 +44,26 @@ public class OfficeConverter { /** * 远程地址端口 */ - private static int PORT = 8100; + private static int[] PORT = {8100}; - private static DocumentFormatRegistry documentFormatRegistry = new DefaultDocumentFormatRegistry(); + private static DocumentFormatRegistry documentFormatRegistry = null; + + static { + try { + documentFormatRegistry = new OfficeDocumentFormatRegistry(OfficeConverter.class.getResourceAsStream("/conf/documentFormats.js")); + } catch (Exception e) { + LOGGER.error(e); + } + } - private static Properties properties; public static boolean isSupport(String fileExtends) { return documentFormatRegistry.getFormatByExtension(fileExtends) != null; } + public static List getAllSupport() { + return ((OfficeDocumentFormatRegistry) documentFormatRegistry).getDocumentFormats(); + } /** * 将office转换为PDF @@ -104,20 +115,41 @@ public File convert(String in, String out) throws IOException { return convert(inputFile, outputFile); } + private boolean isWindows() { + return System.getProperty("os.name").startsWith("Windows"); + } + /** * 根据传入文件后缀名转换文件 * * @param inputFile * @param outputFile + * @return File + * @throws java.io.IOException */ public File convert(File inputFile, File outputFile) throws IOException { try { - if (System.getProperty("os.name").startsWith("Windows") && inputFile.getName().endsWith(".txt")) { - File tmp = new File(inputFile.getName().replace(".txt", ".odt")); - if (!tmp.exists()) { - org.apache.commons.io.FileUtils.copyFile(inputFile, tmp); + if (inputFile.getName().endsWith(".txt")) { + Charset fileCharset = FileUtils.getFileEncoding(inputFile); + if (fileCharset != null) { + Charset systemCharset = Charset.defaultCharset(); + if (!fileCharset.equals(systemCharset) && !(systemCharset.equals(Charset.forName("GBK")) + && fileCharset.name().toLowerCase().equals("gb2312"))) { + String encodedFileName = FileUtils.getFilePrefix(inputFile.getPath()) + "_encoded." + (this.isWindows() ? "odt" : "txt"); + File encodedFile = new File(encodedFileName); + try { + FileUtils.convertFileEncodingToSys(inputFile, encodedFile); + } catch (Exception e) { + org.apache.commons.io.FileUtils.copyFile(inputFile, encodedFile); + } + inputFile = encodedFile; + } else if (isWindows()) { + String encodedFileName = FileUtils.getFilePrefix(inputFile.getPath()) + "_encoded.odt"; + File encodedFile = new File(encodedFileName); + org.apache.commons.io.FileUtils.copyFile(inputFile, encodedFile); + inputFile = encodedFile; + } } - inputFile = tmp; } LOGGER.debug("进行文档转换转换:" + inputFile.getPath() + " --> " + outputFile.getPath()); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); @@ -133,29 +165,29 @@ public File convert(File inputFile, File outputFile) throws IOException { return null; } - public static void startService() throws Exception { + public static void startService(){ DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration(); try { LOGGER.debug("准备启动服务...."); configuration.setOfficeHome(getOfficeHome()); - configuration.setPortNumber(getPort()); - officeManager = configuration.buildOfficeManager(); + configuration.setPortNumbers(getPort()); + configuration.setTaskExecutionTimeout(1000 * 60 * 5L); + configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L); if (CONNECTION_PROTOCOL != null) { configuration.setConnectionProtocol(CONNECTION_PROTOCOL); } if (OFFICE_PROFILE != null) { configuration.setTemplateProfileDir(OFFICE_PROFILE); } + officeManager = configuration.buildOfficeManager(); officeManager.start(); LOGGER.debug("office转换服务启动成功!"); } catch (Exception ce) { - } finally { - + LOGGER.error("office转换服务启动失败!详细信息:" + ce); } - } - public static void stopService() throws Exception, BootstrapException { + public static void stopService() { LOGGER.debug("关闭office转换服务...."); if (officeManager != null) { officeManager.stop(); @@ -172,7 +204,7 @@ public static String getHost() { return HOST; } - public static int getPort() { + public static int[] getPort() { return PORT; } @@ -181,7 +213,7 @@ public static void setOfficeHome(String officeHome) { LOGGER.debug("设置office目录为:" + OfficeConverter.OFFICE_HOME); } - public static void setPort(int port) { + public static void setPort(int[] port) { LOGGER.debug("设置office转换服务端口为:" + port); OfficeConverter.PORT = port; } diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapConnector.java b/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapConnector.java deleted file mode 100644 index 976f447..0000000 --- a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapConnector.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.log4ic.utils.convert.office.connector; - -import com.log4ic.utils.convert.office.connector.server.OOoServer; -import com.sun.star.bridge.UnoUrlResolver; -import com.sun.star.bridge.XUnoUrlResolver; -import com.sun.star.comp.helper.Bootstrap; -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.connection.ConnectionSetupException; -import com.sun.star.connection.NoConnectException; -import com.sun.star.frame.XDesktop; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; - -/** - * A bootstrap connector which establishes a connection to an OOo server. - *

- * Most of the source code in this class has been taken from the Java class - * "Bootstrap.java" (Revision: 1.15) from the UDK projekt (Uno Software Develop- - * ment Kit) from OpenOffice.org (http://udk.openoffice.org/). The source code - * is available for example through a browser based online version control - * access at http://udk.openoffice.org/source/browse/udk/. The Java class - * "Bootstrap.java" is there available at - * http://udk.openoffice.org/source/browse/udk/javaunohelper/com/sun/star/comp/helper/Bootstrap.java?view=markup - *

- * The idea to develop this BootstrapConnector comes from the blog "Getting - * started with the OpenOffice.org API part III : starting OpenOffice.org with - * jars not in the OOo install dir by Wouter van Reeven" - * (http://technology.amis.nl/blog/?p=1284) and from various posts in the - * "(Unofficial) OpenOffice.org Forum" at http://www.oooforum.org/ and the - * "OpenOffice.org Community Forum" at http://user.service.openoffice.org/ - * complaining about "no office executable found!". - */ -public class BootstrapConnector { - - /** - * The OOo server. - */ - private OOoServer oooServer; - - /** - * The connection string which has ben used to establish the connection. - */ - private String oooConnectionString; - - /** - * Constructs a bootstrap connector which uses the folder of the OOo - * installation containing the soffice executable. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - */ - public BootstrapConnector(String oooExecFolder) { - - this.oooServer = new OOoServer(oooExecFolder); - this.oooConnectionString = null; - } - - /** - * Constructs a bootstrap connector which connects to the specified - * OOo server. - * - * @param oooServer The OOo server - */ - public BootstrapConnector(OOoServer oooServer) { - - this.oooServer = oooServer; - this.oooConnectionString = null; - } - - /** - * Connects to an OOo server using the specified accept option and - * connection string and returns a component context for using the - * connection to the OOo server. - *

- * The accept option and the connection string should match to get a - * connection. OOo provides to different types of connections: - * 1) The socket connection - * 2) The named pipe connection - *

- * To create a socket connection a host and port must be provided. - * For example using the host "localhost" and the port "8100" the - * accept option and connection string looks like this: - * - accept option : -accept=socket,host=localhost,port=8100;urp; - * - connection string: uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext - *

- * To create a named pipe a pipe name must be provided. For example using - * the pipe name "oooPipe" the accept option and connection string looks - * like this: - * - accept option : -accept=pipe,name=oooPipe;urp; - * - connection string: uno:pipe,name=oooPipe;urp;StarOffice.ComponentContext - * - * @param oooAcceptOption The accept option - * @param oooConnectionString The connection string - * @return The component context - */ - public XComponentContext connect(String oooAcceptOption, String oooConnectionString) throws BootstrapException { - - this.oooConnectionString = oooConnectionString; - - XComponentContext xContext = null; - try { - // get local context - XComponentContext xLocalContext = getLocalContext(); - - oooServer.start(oooAcceptOption); - - // initial service manager - XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); - if (xLocalServiceManager == null) - throw new BootstrapException("no initial service manager!"); - - // create a URL resolver - XUnoUrlResolver xUrlResolver = UnoUrlResolver.create(xLocalContext); - - // wait until office is started - for (int i = 0; ; ++i) { - try { - xContext = getRemoteContext(xUrlResolver); - break; - } catch (com.sun.star.connection.NoConnectException ex) { - // Wait 500 ms, then try to connect again, but do not wait - // longer than 5 min (= 600 * 500 ms) total: - if (i == 600) { - throw new BootstrapException(ex.toString()); - } - Thread.sleep(500); - } - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.lang.Exception e) { - throw new BootstrapException(e); - } - return xContext; - } - - /** - * Disconnects from an OOo server using the connection string from the - * previous connect. - *

- * If there has been no previous connect, the disconnects does nothing. - *

- * If there has been a previous connect, disconnect tries to terminate - * the OOo server and kills the OOo server process the connect started. - */ - public void disconnect() { - - if (oooConnectionString == null) - return; - - // call office to terminate itself - try { - // get local context - XComponentContext xLocalContext = getLocalContext(); - - // create a URL resolver - XUnoUrlResolver xUrlResolver = UnoUrlResolver.create(xLocalContext); - - // get remote context - XComponentContext xRemoteContext = getRemoteContext(xUrlResolver); - - // get desktop to terminate office - Object desktop = xRemoteContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext); - XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop); - xDesktop.terminate(); - } catch (Exception e) { - // Bad luck, unable to terminate office - } - - oooServer.kill(); - oooConnectionString = null; - } - - /** - * Create default local component context. - * - * @return The default local component context - */ - private XComponentContext getLocalContext() throws BootstrapException, Exception { - - XComponentContext xLocalContext = Bootstrap.createInitialComponentContext(null); - if (xLocalContext == null) { - throw new BootstrapException("no local component context!"); - } - return xLocalContext; - } - - /** - * Try to connect to office. - * - * @return The remote component context - */ - private XComponentContext getRemoteContext(XUnoUrlResolver xUrlResolver) throws BootstrapException, ConnectionSetupException, IllegalArgumentException, NoConnectException { - - Object context = xUrlResolver.resolve(oooConnectionString); - XComponentContext xContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, context); - if (xContext == null) { - throw new BootstrapException("no component context!"); - } - return xContext; - } - - /** - * Bootstraps a connection to an OOo server in the specified soffice - * executable folder of the OOo installation using the specified accept - * option and connection string and returns a component context for using - * the connection to the OOo server. - *

- * The accept option and the connection string should match in connection - * type and pipe name or host and port to get a connection. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @param oooAcceptOption The accept option - * @param oooConnectionString The connection string - * @return The component context - */ - public static final XComponentContext bootstrap(String oooExecFolder, String oooAcceptOption, String oooConnectionString) throws BootstrapException { - - BootstrapConnector bootstrapConnector = new BootstrapConnector(oooExecFolder); - return bootstrapConnector.connect(oooAcceptOption, oooConnectionString); - } -} \ No newline at end of file diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapPipeConnector.java b/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapPipeConnector.java deleted file mode 100644 index 7e98135..0000000 --- a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapPipeConnector.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.log4ic.utils.convert.office.connector; - -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.uno.XComponentContext; -import java.util.Random; -import com.log4ic.utils.convert.office.connector.server.OOoServer; - -/** - * A bootstrap connector which uses a named pipe to connect to an OOo server. - * - * Very helpful in getting the named pipe connection working has been the posts - * of mnasato in the thread "Correct FilterName to open RTF from bytestream?" at - * http://www.oooforum.org/forum/viewtopic.phtml?t=40263&highlight=named+pipe. - */ -public class BootstrapPipeConnector extends BootstrapConnector { - - /** - * Constructs a bootstrap pipe connector which uses the specified folder of - * the OOo installation containing the soffice executable. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - */ - public BootstrapPipeConnector(String oooExecFolder) { - - super(oooExecFolder); - } - - /** - * Constructs a bootstrap pipe connector which connects to the specified - * OOo server. - * - * @param oooServer The OOo server - */ - public BootstrapPipeConnector(OOoServer oooServer) { - - super(oooServer); - } - - /** - * Connects to an OOo server using a random pipe name and returns a - * component context for using the connection to the OOo server. - * - * @return The component context - */ - public XComponentContext connect() throws BootstrapException { - - // create random pipe name - String sPipeName = "uno" + Long.toString((new Random()).nextLong() & 0x7fffffffffffffffL); - - return connect(sPipeName); - } - - /** - * Connects to an OOo server using the specified pipe name and returns a - * component context for using the connection to the OOo server. - * - * @param pipeName The pipe name - * @return The component context - */ - public XComponentContext connect(String pipeName) throws BootstrapException { - - // accept option - String oooAcceptOption = "-accept=pipe,name=" + pipeName + ";urp;"; - - // connection string - String unoConnectString = "uno:pipe,name=" + pipeName + ";urp;StarOffice.ComponentContext"; - - return connect(oooAcceptOption, unoConnectString); - } - - /** - * Bootstraps a connection to an OOo server in the specified soffice - * executable folder of the OOo installation using a random pipe name and - * returns a component context for using the connection to the OOo server. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @return The component context - */ - public static final XComponentContext bootstrap(String oooExecFolder) throws BootstrapException { - - BootstrapPipeConnector bootstrapPipeConnector = new BootstrapPipeConnector(oooExecFolder); - return bootstrapPipeConnector.connect(); - } - - /** - * Bootstraps a connection to an OOo server in the specified soffice - * executable folder of the OOo installation using the specified pipe name - * and returns a component context for using the connection to OOo server. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @param pipeName The pipe name - * @return The component context - */ - public static final XComponentContext bootstrap(String oooExecFolder, String pipeName) throws BootstrapException { - - BootstrapPipeConnector bootstrapPipeConnector = new BootstrapPipeConnector(oooExecFolder); - return bootstrapPipeConnector.connect(pipeName); - } -} \ No newline at end of file diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapSocketConnector.java b/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapSocketConnector.java deleted file mode 100644 index 36e9643..0000000 --- a/docviewerapi/src/com/log4ic/utils/convert/office/connector/BootstrapSocketConnector.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.log4ic.utils.convert.office.connector; - -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.uno.XComponentContext; -import com.log4ic.utils.convert.office.connector.server.OOoServer; - -/** - * A Bootstrap Connector which uses a socket to connect to an OOo server. - */ -public class BootstrapSocketConnector extends BootstrapConnector { - - /** - * Constructs a bootstrap socket connector which uses the folder of the OOo installation containing the soffice executable. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - */ - public BootstrapSocketConnector(String oooExecFolder) { - - super(oooExecFolder); - } - - /** - * Constructs a bootstrap socket connector which connects to the specified - * OOo server. - * - * @param oooServer The OOo server - */ - public BootstrapSocketConnector(OOoServer oooServer) { - - super(oooServer); - } - - /** - * Connects to an OOo server using a default socket and returns a - * component context for using the connection to the OOo server. - * - * @return The component context - */ - public XComponentContext connect() throws BootstrapException { - - // create random pipe name - String host = "localhost"; - int port = 8100; - - return connect(host,port); - } - - /** - * Connects to an OOo server using the specified host and port for the - * socket and returns a component context for using the connection to the - * OOo server. - * - * @param host The host - * @param port The port - * @return The component context - */ - public XComponentContext connect(String host, int port) throws BootstrapException { - - // host and port - String hostAndPort = "host="+host+",port="+port; - - // accept option - String oooAcceptOption = "-accept=socket,"+hostAndPort+";urp;"; - - // connection string - String unoConnectString = "uno:socket,"+hostAndPort+";urp;StarOffice.ComponentContext"; - - return connect(oooAcceptOption, unoConnectString); - } - - /** - * Bootstraps a connection to an OOo server in the specified soffice - * executable folder of the OOo installation using a default socket and - * returns a component context for using the connection to the OOo server. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @return The component context - */ - public static final XComponentContext bootstrap(String oooExecFolder) throws BootstrapException { - - BootstrapSocketConnector bootstrapSocketConnector = new BootstrapSocketConnector(oooExecFolder); - return bootstrapSocketConnector.connect(); - } - - /** - * Bootstraps a connection to an OOo server in the specified soffice - * executable folder of the OOo installation using the specified host and - * port for the socket and returns a component context for using the - * connection to the OOo server. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @param host The host - * @param port The port - * @return The component context - */ - public static final XComponentContext bootstrap(String oooExecFolder, String host, int port) throws BootstrapException { - - BootstrapSocketConnector bootstrapSocketConnector = new BootstrapSocketConnector(oooExecFolder); - return bootstrapSocketConnector.connect(host,port); - } -} \ No newline at end of file diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/connector/example/BootstrapSocketConnectorExample.java b/docviewerapi/src/com/log4ic/utils/convert/office/connector/example/BootstrapSocketConnectorExample.java deleted file mode 100644 index 52b1e67..0000000 --- a/docviewerapi/src/com/log4ic/utils/convert/office/connector/example/BootstrapSocketConnectorExample.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.log4ic.utils.convert.office.connector.example; - -import com.sun.star.beans.PropertyValue; -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.connection.NoConnectException; -import com.sun.star.frame.XComponentLoader; -import com.sun.star.frame.XStorable; -import com.sun.star.io.IOException; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.XMultiComponentFactory; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; -import java.util.List; -import com.log4ic.utils.convert.office.connector.BootstrapSocketConnector; -import com.log4ic.utils.convert.office.connector.server.OOoServer; - -public class BootstrapSocketConnectorExample { - - private static final String OOO_EXEC_FOLDER = "C:/Programme/OpenOffice.org 2.3/program/"; - - private static final String TEMPLATE_FOLDER = "C:/Temp/"; - private static final String TEXT_DOCUMENT_NAME = "Text"; - - private static final String FILE_URL_PREFIX = "file:///"; - private static final String TEXT_DOCUMENT_EXTENSION = ".odt"; - private static final String PDF_DOCUMENT_EXTENSION = ".pdf"; - - /** - * Converts an OOo text document (.odt) to a PDF file using a - * BootstrapConnector. - * - * @param args The command line arguments - */ - public static void main(String[] args) { - - String textDocumentName = (args.length > 0)? args[0]: TEXT_DOCUMENT_NAME; - - String loadUrl=FILE_URL_PREFIX+TEMPLATE_FOLDER+textDocumentName+TEXT_DOCUMENT_EXTENSION; - String storeUrl; - - try { - storeUrl=FILE_URL_PREFIX+TEMPLATE_FOLDER+textDocumentName+"SC"+PDF_DOCUMENT_EXTENSION; - convertWithStaticConnector(loadUrl, storeUrl); - - storeUrl=FILE_URL_PREFIX+TEMPLATE_FOLDER+textDocumentName+"C"+PDF_DOCUMENT_EXTENSION; - convertWithConnector(loadUrl, storeUrl); - } - catch (NoConnectException e) { - System.out.println("OOo is not responding"); - e.printStackTrace(); - } - catch (Exception e) { - e.printStackTrace(); - } - finally { - System.exit(0); - } - } - - private static void convertWithStaticConnector(String loadUrl, String storeUrl) throws Exception, IllegalArgumentException, IOException, BootstrapException { - - // Connect to OOo - XComponentContext remoteContext = BootstrapSocketConnector.bootstrap(OOO_EXEC_FOLDER); - - // Convert text document to PDF - convert(loadUrl, storeUrl, remoteContext); - } - - private static void convertWithConnector(String loadUrl, String storeUrl) throws Exception, IllegalArgumentException, IOException, BootstrapException { - - // Create OOo server with additional -nofirststartwizard option - List oooOptions = OOoServer.getDefaultOOoOptions(); - oooOptions.add("-nofirststartwizard"); - OOoServer oooServer = new OOoServer(OOO_EXEC_FOLDER, oooOptions); - - // Connect to OOo - BootstrapSocketConnector bootstrapSocketConnector = new BootstrapSocketConnector(oooServer); - XComponentContext remoteContext = bootstrapSocketConnector.connect(); - - // Convert text document to PDF - convert(loadUrl, storeUrl, remoteContext); - - // Disconnect and terminate OOo server - bootstrapSocketConnector.disconnect(); - } - - protected static void convert(String loadUrl, String storeUrl, XComponentContext remoteContext) throws IllegalArgumentException, IOException, Exception { - - XComponentLoader xcomponentloader = getComponentLoader(remoteContext); - - Object objectDocumentToStore = xcomponentloader.loadComponentFromURL(loadUrl, "_blank", 0, new PropertyValue[0]); - - PropertyValue[] conversionProperties = new PropertyValue[1]; - conversionProperties[0] = new PropertyValue(); - conversionProperties[0].Name = "FilterName"; - conversionProperties[0].Value = "writer_pdf_Export"; - - XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class,objectDocumentToStore); - xstorable.storeToURL(storeUrl, conversionProperties); - } - - private static XComponentLoader getComponentLoader(XComponentContext remoteContext) throws Exception { - - XMultiComponentFactory remoteServiceManager = remoteContext.getServiceManager(); - Object desktop = remoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext); - XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,desktop); - - return xcomponentloader; - } -} diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/connector/server/OOoServer.java b/docviewerapi/src/com/log4ic/utils/convert/office/connector/server/OOoServer.java deleted file mode 100644 index fda83bb..0000000 --- a/docviewerapi/src/com/log4ic/utils/convert/office/connector/server/OOoServer.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.log4ic.utils.convert.office.connector.server; - -import com.sun.star.comp.helper.BootstrapException; -import com.sun.star.lib.util.NativeLibraryLoader; -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.IOException; -import java.io.PrintStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; - -/** - * Starts and stops an OOo server. - * - * Most of the source code in this class has been taken from the Java class - * "Bootstrap.java" (Revision: 1.15) from the UDK projekt (Uno Software Develop- - * ment Kit) from OpenOffice.org (http://udk.openoffice.org/). The source code - * is available for example through a browser based online version control - * access at http://udk.openoffice.org/source/browse/udk/. The Java class - * "Bootstrap.java" is there available at - * http://udk.openoffice.org/source/browse/udk/javaunohelper/com/sun/star/comp/helper/Bootstrap.java?view=markup - */ -public class OOoServer { - - /** The OOo server process. */ - private Process oooProcess; - - /** The folder of the OOo installation containing the soffice executable. */ - private String oooExecFolder; - - /** The options for starting the OOo server. */ - private List oooOptions; - - /** - * Constructs an OOo server which uses the folder of the OOo installation - * containing the soffice executable and a list of default options to start - * OOo. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - */ - public OOoServer(String oooExecFolder) { - - this.oooProcess = null; - this.oooExecFolder = oooExecFolder; - this.oooOptions = getDefaultOOoOptions(); - } - - /** - * Constructs an OOo server which uses the folder of the OOo installation - * containing the soffice executable and a given list of options to start - * OOo. - * - * @param oooExecFolder The folder of the OOo installation containing the soffice executable - * @param oooOptions The list of options - */ - public OOoServer(String oooExecFolder, List oooOptions) { - - this.oooProcess = null; - this.oooExecFolder = oooExecFolder; - this.oooOptions = oooOptions; - } - - /** - * Starts an OOo server which uses the specified accept option. - * - * The accept option can be used for two different types of connections: - * 1) The socket connection - * 2) The named pipe connection - * - * To create a socket connection a host and port must be provided. - * For example using the host "localhost" and the port "8100" the - * accept option looks like this: - * - accept option : -accept=socket,host=localhost,port=8100;urp; - * - * To create a named pipe a pipe name must be provided. For example using - * the pipe name "oooPipe" the accept option looks like this: - * - accept option : -accept=pipe,name=oooPipe;urp; - * - * @param oooAcceptOption The accept option - */ - public void start(String oooAcceptOption) throws BootstrapException, IOException, MalformedURLException { - - // find office executable relative to this class's class loader - String sOffice = System.getProperty("os.name").startsWith("Windows")? "soffice.exe": "soffice"; - - URL[] oooExecFolderURL = new URL[] {new File(oooExecFolder).toURI().toURL()}; - URLClassLoader loader = new URLClassLoader(oooExecFolderURL); - File fOffice = NativeLibraryLoader.getResource(loader, sOffice); - if (fOffice == null) - throw new BootstrapException("no office executable found!"); - - // create call with arguments - int arguments = (oooOptions != null)? oooOptions.size()+1: 1; - if (oooAcceptOption != null) - arguments++; - - String[] oooCommand = new String[arguments]; - oooCommand[0] = fOffice.getPath(); - - for (int i = 0; i < oooOptions.size(); i++) { - oooCommand[i+1] = (String) oooOptions.get(i); - } - - if (oooAcceptOption != null) - oooCommand[arguments-1] = oooAcceptOption; - - // start office process - oooProcess = Runtime.getRuntime().exec(oooCommand); - - pipe(oooProcess.getInputStream(), System.out, "CO> "); - pipe(oooProcess.getErrorStream(), System.err, "CE> "); - } - - /** - * Kills the OOo server process from the previous start. - * - * If there has been no previous start of the OOo server, the kill does - * nothing. - * - * If there has been a previous start, kill destroys the process. - */ - public void kill() { - - if (oooProcess != null) - { - oooProcess.destroy(); - oooProcess = null; - } - } - - private static void pipe(final InputStream in, final PrintStream out, final String prefix ) { - new Thread( "Pipe: " + prefix) { - @Override - public void run() { - BufferedReader r = new BufferedReader(new InputStreamReader(in)); - try { - for ( ; ; ) { - String s = r.readLine(); - if (s == null) { - break; - } - out.println(prefix + s); - } - } catch (java.io.IOException e) { - e.printStackTrace(System.err); - } - } - }.start(); - } - - /** - * Returns the list of default options. - * - * @return The list of default options - */ - public static List getDefaultOOoOptions() { - - ArrayList options = new ArrayList(); - - options.add("-nologo"); - options.add("-nodefault"); - options.add("-norestore"); - options.add("-nocrashreport"); - options.add("-nolockcheck"); - options.add("-headless"); - options.add("-nofirststartwizard"); - - return options; - } -} \ No newline at end of file diff --git a/docviewerapi/src/com/log4ic/utils/convert/office/document/OfficeDocumentFormatRegistry.java b/docviewerapi/src/com/log4ic/utils/convert/office/document/OfficeDocumentFormatRegistry.java new file mode 100644 index 0000000..53eb6c5 --- /dev/null +++ b/docviewerapi/src/com/log4ic/utils/convert/office/document/OfficeDocumentFormatRegistry.java @@ -0,0 +1,80 @@ +package com.log4ic.utils.convert.office.document; + +import javolution.util.FastList; +import org.apache.commons.io.IOUtils; +import org.artofsolving.jodconverter.document.DocumentFamily; +import org.artofsolving.jodconverter.document.DocumentFormat; +import org.artofsolving.jodconverter.document.SimpleDocumentFormatRegistry; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author 张立鑫 IntelligentCode + * @date: 12-1-22 + * @time: 上午2:33 + */ +public class OfficeDocumentFormatRegistry extends SimpleDocumentFormatRegistry { + public OfficeDocumentFormatRegistry(InputStream input) throws IOException, JSONException { + readJsonArray(IOUtils.toString(input)); + } + + public OfficeDocumentFormatRegistry(String source) throws JSONException { + readJsonArray(source); + } + + private void readJsonArray(String source) throws JSONException { + JSONArray array = new JSONArray(source); + for (int i = 0; i < array.length(); i++) { + JSONObject jsonFormat = array.getJSONObject(i); + DocumentFormat format = new DocumentFormat(); + format.setName(jsonFormat.getString("name")); + format.setExtension(jsonFormat.getString("extension")); + format.setMediaType(jsonFormat.getString("mediaType")); + if (jsonFormat.has("inputFamily")) { + format.setInputFamily(DocumentFamily.valueOf(jsonFormat.getString("inputFamily"))); + } + if (jsonFormat.has("loadProperties")) { + format.setLoadProperties(toJavaMap(jsonFormat.getJSONObject("loadProperties"))); + } + if (jsonFormat.has("storePropertiesByFamily")) { + JSONObject jsonStorePropertiesByFamily = jsonFormat.getJSONObject("storePropertiesByFamily"); + for (String key : JSONObject.getNames(jsonStorePropertiesByFamily)) { + Map storeProperties = toJavaMap(jsonStorePropertiesByFamily.getJSONObject(key)); + format.setStoreProperties(DocumentFamily.valueOf(key), storeProperties); + } + } + addFormat(format); + } + } + + private Map toJavaMap(JSONObject jsonMap) throws JSONException { + Map map = new HashMap(); + for (String key : JSONObject.getNames(jsonMap)) { + Object value = jsonMap.get(key); + if (value instanceof JSONObject) { + map.put(key, toJavaMap((JSONObject) value)); + } else { + map.put(key, value); + } + } + return map; + } + + protected List documentFormats = new FastList(); + + public void addFormat(DocumentFormat documentFormat) { + super.addFormat(documentFormat); + documentFormats.add(documentFormat); + } + + public List getDocumentFormats() { + return new FastList(documentFormats); + } +} diff --git a/docviewerapi/src/com/log4ic/utils/convert/pdf/PDFConverter.java b/docviewerapi/src/com/log4ic/utils/convert/pdf/PDFConverter.java index 5e348ba..18edb3e 100644 --- a/docviewerapi/src/com/log4ic/utils/convert/pdf/PDFConverter.java +++ b/docviewerapi/src/com/log4ic/utils/convert/pdf/PDFConverter.java @@ -2,7 +2,7 @@ import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfReader; -import com.log4ic.utils.FileUtils; +import com.log4ic.utils.io.FileUtils; import com.log4ic.utils.security.PDFSecurer; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; @@ -51,7 +51,7 @@ public static void setCommandConfig(String command) throws Exception { setCommand(command); } - public int execConvertCommand(String command, final List outResources) throws InterruptedException, IOException { + public int execCommand(String command, final List outResources) throws InterruptedException, IOException { LOGGER.debug(command); final Process convertProcess = Runtime.getRuntime().exec(command); final InputStream inputStream = convertProcess.getInputStream(); @@ -65,12 +65,10 @@ public void run() { String line = null; while ((line = br.readLine()) != null) { - if (line != null) { - if (outResources != null) { - outResources.add(line); - } - LOGGER.debug(line); + if (outResources != null) { + outResources.add(line); } + LOGGER.debug(line); } } catch (IOException e) { LOGGER.error(e); @@ -85,11 +83,9 @@ public void run() { String line = null; while ((line = br.readLine()) != null) { - if (line != null) { - LOGGER.debug(line); - if (outResources != null) { - outResources.add(line); - } + LOGGER.debug(line); + if (outResources != null) { + outResources.add(line); } } } catch (IOException e) { @@ -133,44 +129,65 @@ private PDFConverterDeploy deploy(File pdfFile, String outPath, boolean splitPag } outPath = FileUtils.appendFileSeparator(outputDirectory.getPath()); + File decryptedPdf = new File(FileUtils.getFilePrefix(pdfFile) + "_decrypted.pdf"); + File info = new File(FileUtils.appendFileSeparator(outputDirectory.getPath()) + "info"); + int pageCount = 0; + if (!info.exists()) { + PdfReader reader = new PdfReader(pdfPath); + pageCount = reader.getNumberOfPages(); + + if(!decryptedPdf.exists()){ + // if pdf is a encrypted file unencrypted + if (reader.isEncrypted()) { + LOGGER.debug("encrypted pdf! 准备另存"); + pdfPath = PDFSecurer.decrypt(reader, FileUtils.getFilePrefix(pdfFile) + "_decrypted.pdf").getPath(); + LOGGER.debug("PDF解密完成"); + } else { + LOGGER.debug("---文档未加密---"); + } + }else { + pdfPath = decryptedPdf.getPath(); + } - PdfReader reader = new PdfReader(pdfPath); - int pageCount = reader.getNumberOfPages(); + reader.close(); - // if pdf is a encrypted file unencrypted - if (reader.isEncrypted()) { - LOGGER.debug("encrypted pdf! 准备另存"); - pdfPath = PDFSecurer.decrypt(reader, FileUtils.getFilePrefix(pdfFile) + "_decrypted.pdf").getPath(); - LOGGER.debug("PDF解密完成"); - } else { - LOGGER.debug("---文档未加密---"); - } + if (pageCount != 0) { + OutputStream out = null; + try { - reader.close(); + info.createNewFile(); - if (pageCount != 0) { - OutputStream out = null; - try { - File info = new File(FileUtils.appendFileSeparator(outputDirectory.getPath()) + "info"); + out = new FileOutputStream(info); - info.createNewFile(); + out.write((pageCount + "").getBytes("UTF-8")); + } finally { + if (out != null) { + out.flush(); + out.close(); + } + } + + } + } else { + pdfPath = decryptedPdf.getPath(); + + FileInputStream in = new FileInputStream(info); - out = new FileOutputStream(info); + BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); - out.write((pageCount + "").getBytes("UTF-8")); + try { + pageCount = Integer.parseInt(reader.readLine()); + } catch (Exception e) { } finally { - if (out != null) { - out.flush(); - out.close(); - } + reader.close(); + in.close(); } - } return new PDFConverterDeploy(outputDirectory, pageCount, COMMAND.replace("${in}", pdfPath) .replace("${out}", outPath + (splitPage ? "page%.swf" : "page.swf")) + //是否将图片转换成点阵形式 - (poly2bitmap ? " -s poly2bitmap" : "")); + (poly2bitmap ? " -s poly2bitmap -s multiply=4" : "")); } @@ -183,7 +200,7 @@ public PDFConvertError checkError(List outResources) { item = outResources.get(i); - if (errorMsg == false) { + if (!errorMsg) { if (item.lastIndexOf(PDFConvertErrorType.COMPLEX.getErrorMessage()) > -1) { errorMsg = true; @@ -205,11 +222,11 @@ public PDFConvertError checkError(List outResources) { return error; } - private void errorHandler(List outResources, final File pdfFile, final String outPath, boolean splitPage, boolean poly2bitmap) throws Exception { + private void errorHandler(String command, final File pdfFile, final String outPath, boolean splitPage, boolean poly2bitmap, List outResources) throws Exception { // 如果第一次没有将图片转换成点阵图报错,则进行第二次转换,并将图片转换成点阵 final PDFConvertError error = checkError(outResources); - if (error.getType() == PDFConvertErrorType.COMPLEX && poly2bitmap != true) { - LOGGER.debug("---第一次转换失败,进行第二次转换---"); + if (error.getType() == PDFConvertErrorType.COMPLEX && !poly2bitmap) { + LOGGER.debug("---第一次转换失败,进行第二次转换 poly2bitmap = true ---"); if (splitPage) { new Thread() { public void run() { @@ -222,7 +239,7 @@ public void run() { }.start(); convertAsOnePageMode(pdfFile, outPath, error.getPosition() + 1); } else { - convert(pdfFile, outPath, true); + convert(pdfFile, outPath, splitPage, true); } } else { throw new Exception("Conversion failed:" + error.getType() + ";\n" + StringUtils.join(outResources, "\n")); @@ -230,13 +247,13 @@ public void run() { } public void run(String command, File pdfFile, String outPath, boolean splitPage, boolean poly2bitmap) throws Exception { - LOGGER.debug("---转换开始---"); + LOGGER.debug("---开始---"); List outResources = new ArrayList(); - if (execConvertCommand(command, outResources) != 0) { - errorHandler(outResources, pdfFile, outPath, splitPage, poly2bitmap); + if (execCommand(command, outResources) != 0) { + errorHandler(command, pdfFile, outPath, splitPage, poly2bitmap, outResources); } - LOGGER.debug("---转换结束---"); + LOGGER.debug("---结束---"); } public File convertAsOnePageMode(File pdfFile, String outPath) throws Exception { @@ -266,24 +283,22 @@ public File convertAsOnePageMode(final File pdfFile, final String outPath, final int pageCount = deploy.getPageCount(); for (int i = startPage; i <= (endPage == null || endPage > pageCount ? pageCount : endPage); i++) { - final int nowPage = i; - final String commandExec = command += " -p " + nowPage; + final String commandExec = command += " -p " + i; Thread t = new Thread() { public void run() { List outResources = new ArrayList(); try { - if (execConvertCommand(commandExec, outResources) != 0) { + if (execCommand(commandExec, outResources) != 0) { PDFConvertError error = checkError(outResources); - if (error.getType() == PDFConvertErrorType.COMPLEX && poly2bitmap != true) { + if (error.getType() == PDFConvertErrorType.COMPLEX && !poly2bitmap) { LOGGER.debug("---第一次转换失败,进行第二次转换---"); - execConvertCommand(commandExec + " -s poly2bitmap", outResources); + execCommand(commandExec + " -s poly2bitmap", outResources); } else if (error.getType() != PDFConvertErrorType.NONE) { throw new Exception("Conversion failed:" + error.getType() + ";\n" + StringUtils.join(outResources, "\n")); } } } catch (Exception e) { LOGGER.error(e); - e.printStackTrace(); } } diff --git a/docviewerapi/src/com/log4ic/utils/filter/SplitSwfFileFilter.java b/docviewerapi/src/com/log4ic/utils/filter/SplitSwfFileFilter.java deleted file mode 100644 index ab8e3d5..0000000 --- a/docviewerapi/src/com/log4ic/utils/filter/SplitSwfFileFilter.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.log4ic.utils.filter; - -import java.io.File; -import java.io.FileFilter; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author: 张立鑫 - * @version: 1 - * @date: 11-8-25 下午12:05 - */ -public class SplitSwfFileFilter implements FileFilter { - public boolean accept(File pathname) { - Pattern pattern = Pattern.compile("^page\\d+\\.swf$"); - Matcher matcher = pattern.matcher(pathname.getName().toString()); - return matcher.matches(); - } -} diff --git a/docviewerapi/src/com/log4ic/utils/io/FileUtils.java b/docviewerapi/src/com/log4ic/utils/io/FileUtils.java new file mode 100644 index 0000000..93502fb --- /dev/null +++ b/docviewerapi/src/com/log4ic/utils/io/FileUtils.java @@ -0,0 +1,357 @@ +package com.log4ic.utils.io; + +import com.sun.istack.internal.Nullable; +import info.monitorenter.cpdetector.io.*; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.util.Properties; + +/** + * @author: 张立鑫 + * @version: 1 + * @date: 11-8-25 上午10:17 + */ +public class FileUtils { + + public static Properties getProperties(String config) throws Exception { + Properties properties = new Properties(); + //获取class文件夹 + ClassLoader loader = FileUtils.class.getClassLoader(); + //加载文件 + InputStream is = loader.getResourceAsStream(config); + if (is == null) { + throw new Exception("properties is not found"); + } + //读取 + properties.load(is); + return properties; + } + + public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator"); + + + public static String getFilePrefix(String fileFullName) { + int splitIndex = fileFullName.lastIndexOf("."); + return fileFullName.substring(0, splitIndex); + } + + public static String getFilePrefix(File file) { + String fileFullName = file.getName(); + return getFilePrefix(fileFullName); + } + + public static String getFileSuffix(String fileFullName) { + int splitIndex = fileFullName.lastIndexOf("."); + return fileFullName.substring(splitIndex + 1); + } + + public static String getFileSuffix(File file) { + String fileFullName = file.getName(); + return getFileSuffix(fileFullName); + } + + + public static String appendFileSeparator(String path) { + return path + (path.lastIndexOf(File.separator) == path.length() - 1 ? "" : File.separator); + } + + /** + * 文件转化为字节数组 + */ + public static byte[] getBytesFromFile(File f) { + if (f == null) { + return null; + } + try { + FileInputStream stream = new FileInputStream(f); + ByteArrayOutputStream out = new ByteArrayOutputStream(1000); + byte[] b = new byte[1000]; + int n; + while ((n = stream.read(b)) != -1) + out.write(b, 0, n); + stream.close(); + out.close(); + return out.toByteArray(); + } catch (IOException e) { + } + return null; + } + + /** + * 把字节数组保存为一个文件 + */ + public static File getFileFromBytes(byte[] b, String outputFile) { + BufferedOutputStream stream = null; + File file = null; + try { + file = new File(outputFile); + FileOutputStream fstream = new FileOutputStream(file); + stream = new BufferedOutputStream(fstream); + stream.write(b); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + return file; + } + + /** + * 从字节数组获取对象 + */ + public static Object getObjectFromBytes(byte[] objBytes) throws Exception { + if (objBytes == null || objBytes.length == 0) { + return null; + } + ByteArrayInputStream bi = new ByteArrayInputStream(objBytes); + ObjectInputStream oi = new ObjectInputStream(bi); + return oi.readObject(); + } + + /** + * 从对象获取一个字节数组 + */ + public static byte[] getBytesFromObject(Serializable obj) throws Exception { + if (obj == null) { + return null; + } + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ObjectOutputStream oo = new ObjectOutputStream(bo); + oo.writeObject(obj); + return bo.toByteArray(); + } + + /** + * 获取文件编码格式(字符集) + * + * @param file 输入文件 + * @return 字符集名称,如果不支持的字符集则返回null + */ + public static Charset getFileEncoding(File file) { + /*------------------------------------------------------------------------ + detector是探测器,它把探测任务交给具体的探测实现类的实例完成。 + cpDetector内置了一些常用的探测实现类,这些探测实现类的实例可以通过add方法 + 加进来,如ParsingDetector、 JChardetFacade、ASCIIDetector、UnicodeDetector。 + detector按照“谁最先返回非空的探测结果,就以该结果为准”的原则返回探测到的 + 字符集编码。 + 使用需要用到三个第三方JAR包:antlr.jar、chardet.jar和cpdetector.jar + cpDetector是基于统计学原理的,不保证完全正确。 + --------------------------------------------------------------------------*/ + CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance(); + /*------------------------------------------------------------------------- + ParsingDetector可用于检查HTML、XML等文件或字符流的编码,构造方法中的参数用于 + 指示是否显示探测过程的详细信息,为false不显示。 + ---------------------------------------------------------------------------*/ + detector.add(new ParsingDetector(false)); + /*-------------------------------------------------------------------------- + JChardetFacade封装了由Mozilla组织提供的JChardet,它可以完成大多数文件的编码 + 测定。所以,一般有了这个探测器就可满足大多数项目的要求,如果你还不放心,可以 + 再多加几个探测器,比如下面的ASCIIDetector、UnicodeDetector等。 + ---------------------------------------------------------------------------*/ + detector.add(JChardetFacade.getInstance());//用到antlr.jar、chardet.jar + // ASCIIDetector用于ASCII编码测定 + detector.add(ASCIIDetector.getInstance()); + // UnicodeDetector用于Unicode家族编码的测定 + detector.add(UnicodeDetector.getInstance()); + Charset charset = null; + try { + charset = detector.detectCodepage(file.toURI().toURL()); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return charset; + } + + + /** + * 文件编码格式转换 + * + * @param inFile 输入文件 + * @param inCharset 输入文件字符集 + * @param outFile 输出文件 + * @param outCharset 输出文件字符集 + * @return 转码后的字符流 + * @throws IOException + */ + public static byte[] convertFileEncoding(File inFile, Charset inCharset, @Nullable File outFile, Charset outCharset) throws IOException { + + RandomAccessFile inRandom = new RandomAccessFile(inFile, "r"); + + + FileChannel inChannel = inRandom.getChannel(); + + //将输入文件的通道通过只读的权限 映射到内存中。 + MappedByteBuffer byteMapper = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) inFile.length()); + + CharsetDecoder inDecoder = inCharset.newDecoder(); + CharsetEncoder outEncoder = outCharset.newEncoder(); + + CharBuffer cb = inDecoder.decode(byteMapper); + ByteBuffer outBuffer = null; + try { + outBuffer = outEncoder.encode(cb); + + RandomAccessFile outRandom = null; + FileChannel outChannel = null; + if (outFile != null) { + try { + outRandom = new RandomAccessFile(outFile, "rw"); + outChannel = outRandom.getChannel(); + outChannel.write(outBuffer); + } finally { + if (outChannel != null) { + outChannel.close(); + } + if (outRandom != null) { + outRandom.close(); + } + } + } + } finally { + inChannel.close(); + inRandom.close(); + } + + + return outBuffer.array(); + } + + /** + * 文件编码格式转换 + * + * @param inFile 输入文件 + * @param inCharset 输入文件字符集 + * @param outCharset 输出字符集 + * @return 转码后的字符流 + * @throws IOException Exception + */ + public static byte[] convertFileEncoding(File inFile, Charset inCharset, Charset outCharset) throws IOException { + return convertFileEncoding(inFile, inCharset, (File) null, outCharset); + } + + /** + * 将文件字符集转化为指定字符集 + * + * @param inFile 输入文件 + * @param outFile 输出文件 + * @param outCharset 输出文件字符集 + * @return 转码后的字符流 + * @throws IOException + */ + public static byte[] convertFileEncoding(File inFile, @Nullable File outFile, Charset outCharset) throws IOException { + return convertFileEncoding(inFile, getFileEncoding(inFile), outFile, outCharset); + } + + /** + * 将文件字符集转化为指定字符集 + * + * @param inFile 输入文件 + * @return 转码后的字符流 + * @throws IOException + */ + public static byte[] convertFileEncoding(File inFile, Charset outCharset) throws IOException { + return convertFileEncoding(inFile, (File) null, outCharset); + } + + /** + * 将文件字符集转换为系统字符集 + * + * @param inFile 输入文件 + * @return 转码后的字符流 + * @throws IOException + */ + public static byte[] convertFileEncodingToSys(File inFile) throws IOException { + return convertFileEncoding(inFile, (File) null, Charset.defaultCharset()); + } + + /** + * 将文件字符集转换为系统字符集 + * + * @param inFile 输入文件 + * @param outFile 输出文件 + * @return 转码后的字符流 + * @throws IOException + */ + public static byte[] convertFileEncodingToSys(File inFile, @Nullable File outFile) throws IOException { + return convertFileEncoding(inFile, outFile, Charset.defaultCharset()); + } + + + /** + * 将数据写入文件 + * + * @param inputStream + * @param filePath + * @return + */ + public static File writeFile(InputStream inputStream, String filePath) { + FileOutputStream out = null; + FileChannel outChannel = null; + + File file = new File(filePath); + + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + + try { + + out = new FileOutputStream(file); + outChannel = out.getChannel(); + + byte[] buffer = new byte[1024]; + + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + + ByteBuffer outBuffer = ByteBuffer.allocate(buffer.length); + + while (bufferedInputStream.read(buffer)!=-1) { + outBuffer.put(buffer); + outBuffer.flip(); + outChannel.write(outBuffer); + outBuffer.clear(); + } + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (outChannel != null) { + try { + outChannel.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (out != null) { + try { + out.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return file.exists() ? file : null; + } +} diff --git a/docviewerapi/src/com/log4ic/utils/security/PDFSecurer.java b/docviewerapi/src/com/log4ic/utils/security/PDFSecurer.java index 79bf4a6..581e18c 100644 --- a/docviewerapi/src/com/log4ic/utils/security/PDFSecurer.java +++ b/docviewerapi/src/com/log4ic/utils/security/PDFSecurer.java @@ -4,7 +4,7 @@ import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.pdf.*; -import com.log4ic.utils.FileUtils; +import com.log4ic.utils.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/docviewerapi/src/com/log4ic/support/DocViewerServiceListener.java b/docviewerapi/src/com/log4ic/utils/support/DocViewerServiceListener.java similarity index 96% rename from docviewerapi/src/com/log4ic/support/DocViewerServiceListener.java rename to docviewerapi/src/com/log4ic/utils/support/DocViewerServiceListener.java index c337766..a48a2e2 100644 --- a/docviewerapi/src/com/log4ic/support/DocViewerServiceListener.java +++ b/docviewerapi/src/com/log4ic/utils/support/DocViewerServiceListener.java @@ -1,4 +1,4 @@ -package com.log4ic.support; +package com.log4ic.utils.support; import com.log4ic.DocViewer; import org.apache.commons.logging.Log; diff --git a/docviewerapi/src/conf/documentFormats.js b/docviewerapi/src/conf/documentFormats.js index 6286c09..bbfcbfb 100644 --- a/docviewerapi/src/conf/documentFormats.js +++ b/docviewerapi/src/conf/documentFormats.js @@ -1,38 +1,179 @@ -importFormatTable = new Array(); -importFormatTable['odt'] = 'Text'; -importFormatTable['sxw'] = 'Text'; -importFormatTable['doc'] = 'Text'; -importFormatTable['docx'] = 'Text'; -importFormatTable['rtf'] = 'Text'; -importFormatTable['txt'] = 'Text'; -importFormatTable['csv'] = 'Spreadsheet'; -importFormatTable['ods'] = 'Spreadsheet'; -importFormatTable['sxc'] = 'Spreadsheet'; -importFormatTable['xls'] = 'Spreadsheet'; -importFormatTable['xlsx'] = 'Spreadsheet'; -importFormatTable['odp'] = 'Presentation'; -importFormatTable['sxi'] = 'Presentation'; -importFormatTable['ppt'] = 'Presentation'; -importFormatTable['pptx'] = 'Presentation'; - -exportFormatTable = new Array(); -exportFormatTable['Text'] = Array(); -exportFormatTable['Text'][0] = new Option('Portable Document Format (pdf)', 'pdf'); -exportFormatTable['Text'][1] = new Option('OpenDocument Text (odt)', 'odt'); -exportFormatTable['Text'][2] = new Option('OpenOffice.org 1.0 Text Document (sxw)', 'sxw'); -exportFormatTable['Text'][3] = new Option('Microsoft Word (doc)', 'doc'); -exportFormatTable['Text'][4] = new Option('Rich Text Format (rtf)', 'rtf'); -exportFormatTable['Text'][5] = new Option('Plain Text (txt)', 'txt'); -exportFormatTable['Spreadsheet'] = Array(); -exportFormatTable['Spreadsheet'][0] = new Option('Portable Document Format (pdf)', 'pdf'); -exportFormatTable['Spreadsheet'][1] = new Option('OpenDocument Spreadsheet (ods)', 'ods'); -exportFormatTable['Spreadsheet'][2] = new Option('OpenOffice.org 1.0 Spreadsheet (sxc)', 'sxc'); -exportFormatTable['Spreadsheet'][3] = new Option('Microsoft Excel (xls)', 'xls'); -exportFormatTable['Spreadsheet'][4] = new Option('Comma-Separated Values (csv)', 'csv'); -exportFormatTable['Presentation'] = Array(); -exportFormatTable['Presentation'][0] = new Option('Portable Document Format (pdf)', 'pdf'); -exportFormatTable['Presentation'][1] = new Option('Macromedia Flash (swf)', 'swf'); -exportFormatTable['Presentation'][2] = new Option('OpenDocument Presentation (odp)', 'odp'); -exportFormatTable['Presentation'][3] = new Option('OpenOffice.org 1.0 Presentation (sxi)', 'sxi'); -exportFormatTable['Presentation'][4] = new Option('Microsoft PowerPoint (ppt)', 'ppt'); - +[ + { + "name": "Portable Document Format", + "extension": "pdf", + "mediaType": "application/pdf", + "storePropertiesByFamily": { + "DRAWING": {"FilterName": "draw_pdf_Export"}, + "SPREADSHEET": {"FilterName": "calc_pdf_Export"}, + "PRESENTATION": {"FilterName": "impress_pdf_Export"}, + "TEXT": {"FilterName": "writer_pdf_Export"} + } + }, + { + "name": "HTML", + "extension": "html", + "mediaType": "text/html", + "inputFamily": "TEXT", + "storePropertiesByFamily": { + "SPREADSHEET": {"FilterName": "HTML (StarCalc)"}, + "PRESENTATION": {"FilterName": "impress_html_Export"}, + "TEXT": {"FilterName": "HTML (StarWriter)"} + } + }, + { + "name": "OpenDocument Text", + "extension": "odt", + "mediaType": "application/vnd.oasis.opendocument.text", + "inputFamily": "TEXT", + "storePropertiesByFamily": {"TEXT": {"FilterName": "writer8"}} + }, + { + "name": "OpenOffice.org 1.0 Text Document", + "extension": "sxw", + "mediaType": "application/vnd.sun.xml.writer", + "inputFamily": "TEXT", + "storePropertiesByFamily": {"TEXT": {"FilterName": "StarOffice XML (Writer)"}} + }, + { + "name": "Microsoft Word", + "extension": "doc", + "mediaType": "application/msword", + "inputFamily": "TEXT", + "storePropertiesByFamily": {"TEXT": {"FilterName": "MS Word 97"}} + }, + { + "name": "Microsoft Word 2007 XML", + "extension": "docx", + "mediaType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "inputFamily": "TEXT" + }, + { + "name": "Rich Text Format", + "extension": "rtf", + "mediaType": "text/rtf", + "inputFamily": "TEXT", + "storePropertiesByFamily": {"TEXT": {"FilterName": "Rich Text Format"}} + }, + { + "name": "WordPerfect", + "extension": "wpd", + "mediaType": "application/wordperfect", + "inputFamily": "TEXT" + }, + { + "name": "Plain Text", + "extension": "txt", + "mediaType": "text/plain", + "inputFamily": "TEXT", + "loadProperties": { + "FilterName": "Text (encoded)", + "FilterOptions": "utf8" + }, + "storePropertiesByFamily": {"TEXT": { + "FilterName": "Text (encoded)", + "FilterOptions": "utf8" + }} + }, + { + "name": "MediaWiki wikitext", + "extension": "wiki", + "mediaType": "text/x-wiki", + "storePropertiesByFamily": {"TEXT": {"FilterName": "MediaWiki"}} + }, + { + "name": "OpenDocument Spreadsheet", + "extension": "ods", + "mediaType": "application/vnd.oasis.opendocument.spreadsheet", + "inputFamily": "SPREADSHEET", + "storePropertiesByFamily": {"SPREADSHEET": {"FilterName": "calc8"}} + }, + { + "name": "OpenOffice.org 1.0 Spreadsheet", + "extension": "sxc", + "mediaType": "application/vnd.sun.xml.calc", + "inputFamily": "SPREADSHEET", + "storePropertiesByFamily": {"SPREADSHEET": {"FilterName": "StarOffice XML (Calc)"}} + }, + { + "name": "Microsoft Excel", + "extension": "xls", + "mediaType": "application/vnd.ms-excel", + "inputFamily": "SPREADSHEET", + "storePropertiesByFamily": {"SPREADSHEET": {"FilterName": "MS Excel 97"}} + }, + { + "name": "Microsoft Excel 2007 XML", + "extension": "xlsx", + "mediaType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "inputFamily": "SPREADSHEET" + }, + { + "name": "Comma Separated Values", + "extension": "csv", + "mediaType": "text/csv", + "inputFamily": "SPREADSHEET", + "loadProperties": { + "FilterName": "Text - txt - csv (StarCalc)", + "FilterOptions": "44,34,0" + }, + "storePropertiesByFamily": {"SPREADSHEET": { + "FilterName": "Text - txt - csv (StarCalc)", + "FilterOptions": "44,34,0" + }} + }, + { + "name": "Tab Separated Values", + "extension": "tsv", + "mediaType": "text/tab-separated-values", + "inputFamily": "SPREADSHEET", + "loadProperties": { + "FilterName": "Text - txt - csv (StarCalc)", + "FilterOptions": "9,34,0" + }, + "storePropertiesByFamily": {"SPREADSHEET": { + "FilterName": "Text - txt - csv (StarCalc)", + "FilterOptions": "9,34,0" + }} + }, + { + "name": "OpenDocument Presentation", + "extension": "odp", + "mediaType": "application/vnd.oasis.opendocument.presentation", + "inputFamily": "PRESENTATION", + "storePropertiesByFamily": {"PRESENTATION": {"FilterName": "impress8"}} + }, + { + "name": "OpenOffice.org 1.0 Presentation", + "extension": "sxi", + "mediaType": "application/vnd.sun.xml.impress", + "inputFamily": "PRESENTATION", + "storePropertiesByFamily": {"PRESENTATION": {"FilterName": "StarOffice XML (Impress)"}} + }, + { + "name": "Microsoft PowerPoint", + "extension": "ppt", + "mediaType": "application/vnd.ms-powerpoint", + "inputFamily": "PRESENTATION", + "storePropertiesByFamily": {"PRESENTATION": {"FilterName": "MS PowerPoint 97"}} + }, + { + "name": "Microsoft PowerPoint 2007 XML", + "extension": "pptx", + "mediaType": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "inputFamily": "PRESENTATION" + }, + { + "name": "OpenDocument Drawing", + "extension": "odg", + "mediaType": "application/vnd.oasis.opendocument.graphics", + "inputFamily": "DRAWING", + "storePropertiesByFamily": {"DRAWING": {"FilterName": "draw8"}} + }, + { + "name": "Scalable Vector Graphics", + "extension": "svg", + "mediaType": "image/svg+xml", + "storePropertiesByFamily": {"DRAWING": {"FilterName": "draw_svg_Export"}} + } +] diff --git a/docviewerapi/src/conf/docviewer.properties b/docviewerapi/src/conf/docviewer.properties index 718c1b3..fbf1296 100644 --- a/docviewerapi/src/conf/docviewer.properties +++ b/docviewerapi/src/conf/docviewer.properties @@ -1,35 +1,35 @@ -#\u8f6c\u6362\u6587\u6863\u5b58\u653e\u4f4d\u7f6e +#\u8F6C\u6362\u6587\u6863\u5B58\u653E\u4F4D\u7F6E docviewer.output=/home/icode/test/docviewer/ -#\u662f\u5426\u5206\u9875\u8f6c\u6362 -docviewer.converter.splitPage=true -#pdf\u8f6c\u6362\u6700\u5927\u7ebf\u7a0b\u6570 +#\u662F\u5426\u5206\u9875\u8F6C\u6362 +docviewer.converter.splitPage=false +#pdf\u8F6C\u6362\u6700\u5927\u7EBF\u7A0B\u6570 docviewer.converter.pdf.maxThread=10 -#Office\u8f6c\u6362\u6700\u5927\u7ebf\u7a0b\u6570 +#Office\u8F6C\u6362\u6700\u5927\u7EBF\u7A0B\u6570 docviewer.converter.office.maxThread=10 -#\u662f\u5426\u52a0\u5bc6 +#\u662F\u5426\u52A0\u5BC6 docviewer.encryption=true -#\u9759\u6001\u5bc6\u94a5 +#\u9759\u6001\u5BC6\u94A5 docviewer.encryption.key=UeMVef9Qwjqdet8tBhirIyeiPXosHHMaMMaPsWCN -#\u662f\u5426\u4e3a\u52a8\u6001\u5bc6\u94a5 +#\u662F\u5426\u4E3A\u52A8\u6001\u5BC6\u94A5 docviewer.encryption.dynamic=true -#\u52a8\u6001\u5bc6\u94a5\u957f\u5ea6 +#\u52A8\u6001\u5BC6\u94A5\u957F\u5EA6 docviewer.encryption.dynamic.key.length=40 -#\u9644\u4ef6\u670d\u52a1\u7c7b +#\u9644\u4EF6\u670D\u52A1\u7C7B docviewer.attachment.service=com.log4ic.service.DocAttachmentService -#\u5b89\u88c5\u4e2d\u4f1a\u63d0\u793a\u9700\u8981\u5b89\u88c5jre \u5ffd\u7565\u8fd9\u4e9b\u9519\u8bef\uff0c\u5b89\u88c5\u5b8c\u6bd5\u4e4b\u540e\u542f\u52a8word->"\u5de5\u5177"->"\u9009\u9879"->"LibreOffice"->"Java" -#office\u4e3b\u76ee\u5f55 +#\u5B89\u88C5\u4E2D\u4F1A\u63D0\u793A\u9700\u8981\u5B89\u88C5jre \u5FFD\u7565\u8FD9\u4E9B\u9519\u8BEF\uFF0C\u5B89\u88C5\u5B8C\u6BD5\u4E4B\u540E\u542F\u52A8word->"\u5DE5\u5177"->"\u9009\u9879"->"LibreOffice"->"Java" +#office\u4E3B\u76EE\u5F55 docviewer.converter.office.home=/usr/lib/libreoffice/ -#office\u7aef\u53e3 +#office\u7AEF\u53E3 docviewer.converter.office.port=8100 -#open office\u4e3b\u673a \u672a\u5b9e\u73b0 +#open office\u4E3B\u673A \u672A\u5B9E\u73B0 #docviewer.converter.office.host=127.0.0.1 -#\u534f\u8bae -docviewer.converter.office.protocol=pipe -#\u8f6c\u6362\u670d\u52a1\u4e34\u65f6\u5b9e\u4f8b\u76ee +#\u534F\u8BAE +docviewer.converter.office.protocol=socket +#\u8F6C\u6362\u670D\u52A1\u4E34\u65F6\u5B9E\u4F8B\u76EE #docviewer.converter.office.profile= -#swftools\u547d\u4ee4 pdf2swf windows\u4e0b\u52a0\u73af\u5883\u53d8\u91cf\u6216\u8005\u524d\u9762\u8ffd\u52a0\u8def\u5f84 languagedir \u4e2d\u6587\u652f\u6301 \u9700\u8981\u66f4\u6539\u8def\u5f84 \uff0c\u4f7f\u7528\u65f6\u9700\u66f4\u6539add-to-xpdfrc\u6587\u4ef6\u7684\u8def\u5f84\uff0c\u8def\u5f84\u4e2d\u4e0d\u80fd\u7528\u7a7a\u683c\u548c\u4e2d\u6587\uff0c\u914d\u7f6e\u8bf4\u660e\u8bf7\u53c2\u9605chinese-simplified/README -docviewer.converter.pdf.command=pdf2swf ${in} -o ${out} -T 10 -z -s disablelinks -s languagedir=/home/icode/Workspace/personal/docviewer/etc/xpdf-chinese-simplified -#\u5355\u9875\u8f6c\u6362\u6a21\u5f0f\u6700\u5927\u7ebf\u7a0b\u6570 +#swftools\u547D\u4EE4 pdf2swf windows\u4E0B\u52A0\u73AF\u5883\u53D8\u91CF\u6216\u8005\u524D\u9762\u8FFD\u52A0\u8DEF\u5F84 languagedir \u4E2D\u6587\u652F\u6301 \u9700\u8981\u66F4\u6539\u8DEF\u5F84 \uFF0C\u4F7F\u7528\u65F6\u9700\u66F4\u6539add-to-xpdfrc\u6587\u4EF6\u7684\u8DEF\u5F84\uFF0C\u8DEF\u5F84\u4E2D\u4E0D\u80FD\u7528\u7A7A\u683C\u548C\u4E2D\u6587\uFF0C\u914D\u7F6E\u8BF4\u660E\u8BF7\u53C2\u9605chinese-simplified/README +docviewer.converter.pdf.command=pdf2swf ${in} -o ${out} -T 9 -s ignoredraworder -s enablezlib -s disablelinks -s languagedir=/home/icode/Workspace/personal/docviewer/etc/xpdf-chinese-simplified +#\u5355\u9875\u8F6C\u6362\u6A21\u5F0F\u6700\u5927\u7EBF\u7A0B\u6570 docviewer.converter.pdf.mode.singlePage.maxThread=5 diff --git a/docviewerflex.backup/compiler-config.xml b/docviewerflex.backup/compiler-config.xml new file mode 100644 index 0000000..71746cc --- /dev/null +++ b/docviewerflex.backup/compiler-config.xml @@ -0,0 +1,18 @@ + + + true + + + /home/icode/Workspace/company/sinitek/xn-sirm/trunk/src/docviewer/docviewerflex/src + + + + + + /home/icode/Workspace/company/sinitek/xn-sirm/trunk/src/docviewer/docviewerflex/src/DocViewerFlex.mxml + + + + /home/icode/Workspace/company/sinitek/xn-sirm/trunk/src/out/production/docviewerflex/docviewerflex.swf + + \ No newline at end of file diff --git a/docviewerflex/lib/FlexPaper_Resources.swc b/docviewerflex.backup/lib/FlexPaper_Resources.swc similarity index 100% rename from docviewerflex/lib/FlexPaper_Resources.swc rename to docviewerflex.backup/lib/FlexPaper_Resources.swc diff --git a/docviewerflex.backup/locale/bg_BG/FlexPaper.properties b/docviewerflex.backup/locale/bg_BG/FlexPaper.properties new file mode 100644 index 0000000..bdad003 --- /dev/null +++ b/docviewerflex.backup/locale/bg_BG/FlexPaper.properties @@ -0,0 +1,31 @@ +# locale/bg_BG/FlexPaper.properties +Print=Принтирай +FitWidth=Запълни на ширина +FitPage=Запълни +Scale=Мащаб +ThumbView=Виж картинки +CurrentPage=Сегашна страница +Search=Търси +NextPage=Следваща страница +PreviousPage=Предишна страница +Fullscreen=Цял екран +About=Относно +Finishedsearching=Търсенето завърши. Не са открити съвпадения +Searchfinished=Търсенето завърши +Selectprintrange=Въведете страници за принтиране +All=Всички +CurrentPage=Сегашна страница +Pages=Страници: +Enterpagenumbers=Въведи номер на страницата или номера от/до, отделени със запетая. Пример: 1,3,5-12 +Cancel=Отмени +IncorrectRange=Въведен неправилен номер от-до +Incorrectrangespecified=Въведени неправилни номера на страници +About=Относно +Developedby=Разработено от Devaldi. +Formoreinformation=Виж за повече информация +CopyText=Копирай текста +TwoPage=Две страници +SinglePage=Една страница +Current\ Page=Create Property +TextSelect=Create Property +TextDrag=Create Property \ No newline at end of file diff --git a/docviewerflex.backup/locale/cz_CS/FlexPaper.properties b/docviewerflex.backup/locale/cz_CS/FlexPaper.properties new file mode 100644 index 0000000..3fdbf51 --- /dev/null +++ b/docviewerflex.backup/locale/cz_CS/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/cz_CS/FlexPaper.properties +Print=Tisk +FitWidth=Přizpůsobit na šířku +FitPage=Přizpůsobit na stránku +Scale=Velikost +ThumbView=Zobrazit náhled +CurrentPage=Aktuální stránka +Search=Hledat +NextPage=Další stránka +PreviousPage=Předchozí stránka +Fullscreen=Celá obrazovka +About=Informace +Finishedsearching=Prohledávaní dokumentu bylo dokončeno. Nebyly nalezeny žádné další hledané položky +Searchfinished=Vyhledávání dokončeno +Selectprintrange=Zvolte rozsah tisku +All=Vše +CurrentPage=Aktuální stránka +Pages=Stránky: +Enterpagenumbers=Zadejte čísla a/nebo rozsahy stránek oddělené čárkou. Například 1,3,5-12 +Cancel=Storno +IncorrectRange=Nesprávný rozsah +Incorrectrangespecified=Byl zadán nesprávný rozsah +About=Informace +Developedby=Vytvořeno Devaldi. +Formoreinformation=Další informace najdete na adrese +TwoPage=Dvě stránky +SinglePage=Single Page \ No newline at end of file diff --git a/docviewerflex.backup/locale/de_DE/FlexPaper.properties b/docviewerflex.backup/locale/de_DE/FlexPaper.properties new file mode 100644 index 0000000..f91517b --- /dev/null +++ b/docviewerflex.backup/locale/de_DE/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/de_DE/FlexPaper.properties +Print=Drucken +FitWidth=Weite anpassen +FitPage=Seite anpassen +Scale=Skalieren +ThumbView=Ansicht vereinfachen +CurrentPage=Derzeitige Seite +Search=Suche +NextPage=Nächste Seite +PreviousPage=Vorherige Seite +Fullscreen=Vollansicht +About=Über +Finishedsearching=Suche nach Dokument fertig. Keine weiteren Einträge gefunden +Searchfinished=Suche fertig +Selectprintrange=Druckbereich wählen +All=Alle +CurrentPage=Derzeitige Seite +Pages=Seiten: +Enterpagenumbers=Geben Sie die Seitenzahl und/oder den Seitenbereich an. Zum Beispiel 1,3,5-12 +Cancel=Abbrechen +IncorrectRange=Bereich nicht korrekt +Incorrectrangespecified=Bereich nicht richtig definiert +About=Über +Developedby=Erstellt von Devaldi. +Formoreinformation=Mehr Information +TwoPage=Zwei Page +SinglePage=Single Page \ No newline at end of file diff --git a/docviewerflex.backup/locale/dn_DN/FlexPaper.properties b/docviewerflex.backup/locale/dn_DN/FlexPaper.properties new file mode 100644 index 0000000..7554bfc --- /dev/null +++ b/docviewerflex.backup/locale/dn_DN/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/dn_DN/FlexPaper.properties +Print=Udskriv +FitWidth=Tilpas bredde +FitPage=Tilpas side +Scale=Skala +ThumbView=Miniaturevisning +CurrentPage=Aktuel side +Search=Søg +NextPage=Næste side +PreviousPage=Forrige side +Fullscreen=Fuld skærm +About=Om +Finishedsearching=Søgningen i dokumentet er færdig. Der blev ikke fundet nogen resultater +Searchfinished=Søgning afsluttet +Selectprintrange=Vælg udskriftsområde +All=Alle +CurrentPage=Aktuel side +Pages=Sider: +Enterpagenumbers=Skriv sidetal og/eller sideområder adskilt af kommaer. f.eks. 1,3,5-12 +Cancel=Annuller +IncorrectRange=Ukorrekt område +Incorrectrangespecified=Ukorrekt område angivet +About=Om +Developedby=Udviklet af Devaldi. +Formoreinformation=For yderligere oplysninger, se +TwoPage=To Page +SinglePage=Single Side \ No newline at end of file diff --git a/docviewerflex.backup/locale/el_EL/FlexPaper.properties b/docviewerflex.backup/locale/el_EL/FlexPaper.properties new file mode 100644 index 0000000..2597740 --- /dev/null +++ b/docviewerflex.backup/locale/el_EL/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/el_EL/FlexPaper.properties +Print=Εκτύπωση +FitWidth=Προσαρμογή πλάτος +FitPage=Προσαρμογή σελίδας +Scale=Κλίμακα +ThumbView=Προεπισκόπηση +CurrentPage=Τρέχων σελίδα +Search=Αναζήτηση +NextPage=Επόμενη σελίδα +PreviousPage=Προηγούμενη σελίδα +Fullscreen=Πλήρης οθόνη +About=Σχετικά +Finishedsearching=Ολοκληρώθηκε η αναζήτηση του εγγράφου. Δε βρέθηκαν άλλες αντιστοιχίες +Searchfinished=Ολοκληρώθηκε η αναζήτηση +Selectprintrange=Επιλογή περιοχής εκτύπωσης +All=Όλα +CurrentPage=Τρέχων σελίδα +Pages=Σελίδες: +Enterpagenumbers=Καταχωρήστε αριθμό σελίδας και/ή περιοχή σελιδών διαχωρισμένες από κόμματα. Για παράδειγμα 1,3,5-12 +Cancel=Ακύρωση +IncorrectRange=Λάθος περιοχή +Incorrectrangespecified=Προσδιορισμός λάθος περιοχής +About=Σχετικά +Developedby=Δημιουργήθηκε από Devaldi. +Formoreinformation=Για περαιτέρω πληροφορίες, βλέπε +TwoPage=Δύο Σελίδα +SinglePage=Ενιαία Σελίδα \ No newline at end of file diff --git a/docviewerflex.backup/locale/en_US/FlexPaper.properties b/docviewerflex.backup/locale/en_US/FlexPaper.properties new file mode 100644 index 0000000..aa3335c --- /dev/null +++ b/docviewerflex.backup/locale/en_US/FlexPaper.properties @@ -0,0 +1,30 @@ +# locale/en_US/FlexPaper.properties +Print=Print +FitWidth=Fit Width +FitPage=Fit Page +Scale=Scale +ThumbView=Thumb View +CurrentPage=Current Page +Search=Search +NextPage=Next Page +PreviousPage=Previous Page +Fullscreen=Fullscreen +About=About +Finishedsearching=Finished searching the document. No more matches were found +Searchfinished=Search finished +Selectprintrange=Select print range +All=All +CurrentPage=Current Page +Pages=Pages: +Enterpagenumbers=Enter page numbers and/or page ranges separated by commas. For example 1,3,5-12 +Cancel=Cancel +IncorrectRange=Incorrect Range +Incorrectrangespecified=Incorrect range specified +About=About +Developedby=Developed by Devaldi. +Formoreinformation=For more information, see +CopyText=Copy Text +TwoPage=Two Pages +SinglePage=Single Page +FirstPage=First Page +LastPage=Last Page \ No newline at end of file diff --git a/docviewerflex.backup/locale/es_ES/FlexPaper.properties b/docviewerflex.backup/locale/es_ES/FlexPaper.properties new file mode 100644 index 0000000..e972742 --- /dev/null +++ b/docviewerflex.backup/locale/es_ES/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/es_ES/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar ancho +FitPage=Ajustar página +Scale=% Zoom +ThumbView=Vista en miniatura +CurrentPage=Página actual +Search=Buscar +NextPage=Página siguiente +PreviousPage=Página anterior +Fullscreen=Pantalla completa +About=Acerca de +Finishedsearching=Búsqueda finalizada. No se encontraron más coincidencias en el documento. +Searchfinished=Búsqueda finalizada +Selectprintrange=Selecciona el área a imprimir +All=Todo +CurrentPage=Página actual +Pages=Páginas: +Enterpagenumbers=Introducir los números de página y/o los rangos separados por comas. Por ejemplo: 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Rango incorrecto +Incorrectrangespecified=El rango especificado no es correcto +About=Acerca de +Developedby=Developed by Devaldi. +Formoreinformation=For more information, see +TwoPage=Dos Page +SinglePage=sola página \ No newline at end of file diff --git a/docviewerflex.backup/locale/fi_FN/FlexPaper.properties b/docviewerflex.backup/locale/fi_FN/FlexPaper.properties new file mode 100644 index 0000000..7b2ca46 --- /dev/null +++ b/docviewerflex.backup/locale/fi_FN/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/fi_FN/FlexPaper.properties +Print=Tulosta +FitWidth=Sovita leveyteen +FitPage=Sovita sivulle +Scale=Muuta mittakaava +ThumbView=Pikkukuvanäkymä +CurrentPage=Nykyinen sivu +Search=Haku +NextPage=Seuraava sivu +PreviousPage=Edellinen sivu +Fullscreen=Kokoruutu +About=Tietoa aiheesta +Finishedsearching=Etsintä on valmis. Ei löytynyt uusia hakutuloksia. +Searchfinished=Haku päättynyt +Selectprintrange=Valitse tulostusalue +All=Kaikki +CurrentPage=Nykyinen sivu +Pages=Sivut: +Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 +Cancel=Peruuta +IncorrectRange=Väärä alue +Incorrectrangespecified=Virheellinen alue eriteltynä +About=Tietoa aiheesta +Developedby=Kehittämä Devaldi. +Formoreinformation=Saadaksesi lisätietoja, katso +TwoPage=Kaksi sivu +SinglePage=Single sivu \ No newline at end of file diff --git a/docviewerflex.backup/locale/fr_FR/FlexPaper.properties b/docviewerflex.backup/locale/fr_FR/FlexPaper.properties new file mode 100644 index 0000000..7df4e0e --- /dev/null +++ b/docviewerflex.backup/locale/fr_FR/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/fr_FR/FlexPaper.properties +Print=Imprimer +FitWidth=Ajuster Largeur +FitPage=Ajuster Page +Scale=Zoom +ThumbView=Vignettes +CurrentPage=Page Courante +Search=Recherche +NextPage=Page Suivante +PreviousPage=Page Précédente +Fullscreen=Plein Ecran +About=A Propos +Finishedsearching=Recherche dans le document terminée. Pas d'autre ocurrence trouvée +Searchfinished=Recherche terminée +Selectprintrange=Etendue de l'impression +All=Tout +CurrentPage=Page Courante +Pages=Pages: +Enterpagenumbers=Entrez les numéros de page et/ou les intervalles de page séparés par des virgules. Par exemple 1,3,5-12 +Cancel=Annuler +IncorrectRange=Intervalle non valide +Incorrectrangespecified=Intervalle non valide spécifié +About=A Propos +Developedby=Développé par Devaldi. +Formoreinformation=Pour plus d'informations, allez sur +TwoPage=Deux Page +SinglePage=Page unique \ No newline at end of file diff --git a/docviewerflex.backup/locale/he_IL/FlexPaper.properties b/docviewerflex.backup/locale/he_IL/FlexPaper.properties new file mode 100644 index 0000000..9765a29 --- /dev/null +++ b/docviewerflex.backup/locale/he_IL/FlexPaper.properties @@ -0,0 +1,28 @@ +# locale/he_IL/FlexPaper.properties +Print=הדפסה +FitWidth=התאם רוחב +FitPage=התאם עמוד +Scale=מידה +ThumbView=תמונות ממוזערות +CurrentPage=עמוד נוכחי +Search=חיפוש +NextPage=עמוד הבא +PreviousPage=עמוד קודם +Fullscreen=מסך מלא +About=אודות +Finishedsearching=החיפוש הסתיים ללא תוצאות +Searchfinished=החיפוש הסתיים +Selectprintrange=בחר טווח הדפסה +All=הכל +Pages=דפים: +Enterpagenumbers=הזן מספרי עמודים ו/או טווחי עמודים מופרדים בפיסוק. לדוגמא 1,3,5-12 +Cancel=ביטול +IncorrectRange=טווח שגואי +Incorrectrangespecified=הוזן טווח שגואי +Developedby=פותח על-ידי Devaldi. +Formoreinformation=לפרטים נוספים, צפה ב +CopyText=העתק טקסט +TwoPage=שני עמודים +SinglePage=עמוד בודד +FirstPage=עמוד ראשון +LastPage=עמוד אחרון \ No newline at end of file diff --git a/docviewerflex.backup/locale/hu_HU/FlexPaper.properties b/docviewerflex.backup/locale/hu_HU/FlexPaper.properties new file mode 100644 index 0000000..b61ae0f --- /dev/null +++ b/docviewerflex.backup/locale/hu_HU/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/hu_HU/FlexPaper.properties +Print=Nyomtatás +FitWidth=Oldalszélességhze igazít +FitPage=Lapszélességhez igazít +Scale=Nagyítás +ThumbView=Miniatürök +CurrentPage=Aktuális oldal +Search=Keresés +NextPage=Következő oldal +PreviousPage=Előző oldal +Fullscreen=Teljes képernyő +About=Névjegy +Finishedsearching=A dokumentum keresése befejeződött. Nincs több találat +Searchfinished=A keresés befejeződött +Selectprintrange=A nyomatási tartomány kiválasztása +All=Összes +CurrentPage=Aktuális oldal +Pages=Oldalak: +Enterpagenumbers=Írja be az oldalakat és/vagy a tartományokat vesszővel elválasztva. Például: 1,3,5-12 +Cancel=Mégse +IncorrectRange=Rossz tartomány +Incorrectrangespecified=Rossz tartományt adott meg +About=Névjegy +Developedby=Fejlesztő Devaldi. +Formoreinformation=További információk +TwoPage=Két oldal +SinglePage=egyetlen oldalon \ No newline at end of file diff --git a/docviewerflex.backup/locale/it_IT/FlexPaper.properties b/docviewerflex.backup/locale/it_IT/FlexPaper.properties new file mode 100644 index 0000000..79c5046 --- /dev/null +++ b/docviewerflex.backup/locale/it_IT/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/it_IT/FlexPaper.properties +Print=Stampa +FitWidth=Adatta Larghezza +FitPage=Adatta Pagina +Scale=Scala +ThumbView=Vista Anteprima +CurrentPage=Pagina Corrente +Search=Ricerca +NextPage=Pagina Seguente +PreviousPage=Pagina precedente +Fullscreen=Fullscreen +About=Su +Finishedsearching=Finita la ricerca nel documento . Trovata nienta occorenza di più. +Searchfinished=Ricerca finita +Selectprintrange=Selezionare la portata di stampa +All=Tutto +CurrentPage=Pagina corrente +Pages=Pagine: +Enterpagenumbers=Immettere i numeri di pagina e/o gli intervalli pagina separati da virgole. Es. 1,3,5-12 +Cancel=Annulla +IncorrectRange=Gamma sbagliata +Incorrectrangespecified=Gamma specificata sbagliata +About=Su +Developedby=Sviluppato da Devaldi. +Formoreinformation=Per più d'informazioni, si prega di visitare +TwoPage=Due pagina +SinglePage=singola pagina \ No newline at end of file diff --git a/docviewerflex.backup/locale/nl_NL/FlexPaper.properties b/docviewerflex.backup/locale/nl_NL/FlexPaper.properties new file mode 100644 index 0000000..95ea696 --- /dev/null +++ b/docviewerflex.backup/locale/nl_NL/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/nl_NL/FlexPaper.properties +Print=Print +FitWidth=Passend maken breedte +FitPage=Passend maken pagina +Scale=Schaal +ThumbView=Thumb bekijken +CurrentPage=Huidige pagina +Search=Zoeken +NextPage=Volgende pagina +PreviousPage=Vorige pagina +Fullscreen=Volledig Scherm +About=Over +Finishedsearching=Klaar met doorzoeken document. Er zijn geen matches meer gevonden +Searchfinished=Zoek is klaar +Selectprintrange=Selecteer de print range +All=Alle +CurrentPage=Huidige pagina +Pages=Paginas: +Enterpagenumbers=Voer paginanummers in en/of pagina schalen gescheiden door commas. Bijvoorbeeld 1,3,5-12 +Cancel=Annuleren +IncorrectRange=Foute range +Incorrectrangespecified=Foute range ingevoerd +About=Over +Developedby=Ontwikkeld door Devaldi. +Formoreinformation=Voor meer informatie, zie +TwoPage=Twee pagina +SinglePage=Single pagina \ No newline at end of file diff --git a/docviewerflex.backup/locale/pl_PL/FlexPaper.properties b/docviewerflex.backup/locale/pl_PL/FlexPaper.properties new file mode 100644 index 0000000..d607138 --- /dev/null +++ b/docviewerflex.backup/locale/pl_PL/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/pl_PL/FlexPaper.properties +Print=Drukuj +FitWidth=Dopasuj do szerokości +FitPage=Dopasuj do strony +Scale=Skaluj +ThumbView=Widok miniaturek +CurrentPage=Obecna strona +Search=Szukaj +NextPage=Następna strona +PreviousPage=Poprzednia strona +Fullscreen=Pełny ekran +About=O +Finishedsearching=Wyszukiwanie zakończone, nic więcej nie znaleziono +Searchfinished=Wyszukiwanie zakończone +Selectprintrange=Wybierz zakres wydruku +All=Wszystkie +CurrentPage=Obecna strona +Pages=Strony: +Enterpagenumbers=Podaj numery stron lub zakres, np. 1,3,5-12 +Cancel=Anuluj +IncorrectRange=Niepoprawny zakres +Incorrectrangespecified=Niepoprawny zakres +About=O +Developedby=Stworzony przez Devaldi. +Formoreinformation=Aby uzyskać więcej informacji zobacz +TwoPage=Dwie strony +SinglePage=jednej stronie \ No newline at end of file diff --git a/docviewerflex.backup/locale/pt_BR/FlexPaper.properties b/docviewerflex.backup/locale/pt_BR/FlexPaper.properties new file mode 100644 index 0000000..ddcc8f8 --- /dev/null +++ b/docviewerflex.backup/locale/pt_BR/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/pt_BR/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar Largura +FitPage=Ajustar Página +Scale=Escala +ThumbView=Ver Miniaturas +CurrentPage=Página atual +Search=Pesquisa +NextPage=Próxima página +PreviousPage=Página Anterior +Fullscreen=Tela cheia +About=Sobre +Finishedsearching=Terminou a procura no documento. Mais candidatos não foram encontrados +Searchfinished=Pesquisa concluída +Selectprintrange=Selecione o intervalo de impressão +All=Todos +CurrentPage=Página atual +Pages=Páginas: +Enterpagenumbers=Digite os números das páginas e / ou intervalos das páginas separados por vírgulas. Por exemplo, 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Ordem incorreta +Incorrectrangespecified=Ordem especificada incorreta +About=Sobre +Developedby=Desenvolvido por Devaldi. +Formoreinformation=Para obter mais informações, consulte: +TwoPage=Duas Páginas +SinglePage=Página Única \ No newline at end of file diff --git a/docviewerflex.backup/locale/pt_PT/FlexPaper.properties b/docviewerflex.backup/locale/pt_PT/FlexPaper.properties new file mode 100644 index 0000000..77f059f --- /dev/null +++ b/docviewerflex.backup/locale/pt_PT/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/pt_PT/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar Largura +FitPage=Ajustar Página +Scale=Escala +ThumbView=Ver Polegar +CurrentPage=Página atual +Search=Pesquisa +NextPage=Próxima página +PreviousPage=Página precedente +Fullscreen=Ecrã cheio +About=Sobre +Finishedsearching=Terminou a procura no documento. Mais competidores não foram encontrados +Searchfinished=Pesquisa concluída +Selectprintrange=Seleccione o intervalo de impressão +All=Todos +CurrentPage=Página actual +Pages=Páginas: +Enterpagenumbers=Digite os números das páginas e / ou intervalos das páginas separados por vírgulas. Por exemplo 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Ordem incorreta +Incorrectrangespecified=Ordem especificada incorreta +About=Sobre +Developedby=Developed by Devaldi. +Formoreinformation=Para obter mais informações, consulte: +TwoPage=Dois Página +SinglePage=Página Única \ No newline at end of file diff --git a/docviewerflex.backup/locale/pv_FN/FlexPaper.properties b/docviewerflex.backup/locale/pv_FN/FlexPaper.properties new file mode 100644 index 0000000..6467da0 --- /dev/null +++ b/docviewerflex.backup/locale/pv_FN/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/pv_FN/FlexPaper.properties +Print=Tulosta +FitWidth=Sovita leveyteen +FitPage=Sovita sivulle +Scale=Muuta mittakaava +ThumbView=Pikkukuvanäkymä +CurrentPage=Nykyinen sivu +Search=Haku +NextPage=Seuraava sivu +PreviousPage=Edellinen sivu +Fullscreen=Kokoruutu +About=Tietoa aiheesta +Finishedsearching=Etsintä on valmis. Ei löytynyt uusia hakutuloksia. +Searchfinished=Haku päättynyt +Selectprintrange=Valitse tulostusalue +All=Kaikki +CurrentPage=Nykyinen sivu +Pages=Sivut: +Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 +Cancel=Peruuta +IncorrectRange=Väärä alue +Incorrectrangespecified=Virheellinen alue eriteltynä +About=Tietoa aiheesta +Developedby=Devaldi Group. +Formoreinformation=Saadaksesi lisätietoja, katso +TwoPage=Kaksi sivu +SinglePage=Single sivu \ No newline at end of file diff --git a/docviewerflex.backup/locale/ru_RU/FlexPaper.properties b/docviewerflex.backup/locale/ru_RU/FlexPaper.properties new file mode 100644 index 0000000..ebbf3a4 --- /dev/null +++ b/docviewerflex.backup/locale/ru_RU/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/ru_RU/FlexPaper.properties +Print=Печать +FitWidth=По ширине +FitPage=По высоте +Scale=Масштаб +ThumbView=Эксизы +CurrentPage=Текущая страница +Search=Поиск +NextPage=Следующая +PreviousPage=Предыдущая +Fullscreen=Полноэкранный вид +About=О проекте +Finishedsearching=Поиск в документе завершен. Результатов не найдено. +Searchfinished=Поиск окончен. +Selectprintrange=Выберите страницы для печати +All=Все +CurrentPage=Только текущая +Pages=Выбор: +Enterpagenumbers=Укажите номера и/или диапазоны страниц через запятую. Например 1,3, 5-12 +Cancel=Отмена +IncorrectRange=Неправильный диапазон +Incorrectrangespecified=Неправильно указан диапазон +About=О проекте +Developedby=Разработано Devaldi. +Formoreinformation=Доп. информация: +TwoPage=Две страницы +SinglePage=Одна страница diff --git a/docviewerflex.backup/locale/se_SE/FlexPaper.properties b/docviewerflex.backup/locale/se_SE/FlexPaper.properties new file mode 100644 index 0000000..18e00df --- /dev/null +++ b/docviewerflex.backup/locale/se_SE/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/se_SE/FlexPaper.properties +Print=Skriv ut +FitWidth=Anpassa efter bredd +FitPage=Anpassa efter sida +Scale=Skala +ThumbView=Visa miniatyrer +CurrentPage=Aktuell sida +Search=Sök +NextPage=Nästa sida +PreviousPage=Föregående sida +Fullscreen=Helskärm +About=Om +Finishedsearching=Sökning i dokumentet har avslutats. Hittade inte fler träffar. +Searchfinished=Sökning avslutad +Selectprintrange=Välj utskriftsområde +All=Alla +CurrentPage=Aktuell sida +Pages=Sidor: +Enterpagenumbers=Ange sidnummer och/eller sidintervall avgränsade med kommatecken, t ex 1,3,5-12 +Cancel=Avbryt +IncorrectRange=Felaktigt intervall +Incorrectrangespecified=Felaktigt intervall har specifierats +About=Om +Developedby=Utvecklad av Devaldi. +Formoreinformation=För mer information, se +TwoPage=Dubbel sidvy +SinglePage=Enkel sida \ No newline at end of file diff --git a/docviewerflex.backup/locale/tr_TR/FlexPaper.properties b/docviewerflex.backup/locale/tr_TR/FlexPaper.properties new file mode 100644 index 0000000..6a16ede --- /dev/null +++ b/docviewerflex.backup/locale/tr_TR/FlexPaper.properties @@ -0,0 +1,26 @@ +# locale/tr_TR/FlexPaper.properties +Print=Yazdır +FitWidth=En uygun genişlik +FitPage=En uygun sayfa +Scale=Ölçekle +ThumbView=Gözetle +CurrentPage=Şimdiki sayfa +Search=Ara +NextPage=Sonraki sayfa +PreviousPage=Önceki sayfa +Fullscreen=Tam ekran +About=Hakkında +Finishedsearching=Dökümanı arama bitti. Eşleştirme bulunamadı +Searchfinished=Arama bitti +Selectprintrange=Yazdırma aralığını seç +All=Bütün +CurrentPage=Şimdiki sayfa +Pages=Sayfalar: +Enterpagenumbers=Virgülle aytılmış sayfa numaralarını gir Örneğin 1,3,5-12 +Cancel=İptal +IncorrectRange=Yanlış dizi +Incorrectrangespecified=Yanlış dizi tanımlanmış +Developedby=By Devaldi Group. +Formoreinformation=Daha fazla bilgi için... +TwoPage=İki Sayfa +SinglePage=Tek Sayfa \ No newline at end of file diff --git a/docviewerflex.backup/locale/zh_CN/FlexPaper.properties b/docviewerflex.backup/locale/zh_CN/FlexPaper.properties new file mode 100644 index 0000000..378dbc1 --- /dev/null +++ b/docviewerflex.backup/locale/zh_CN/FlexPaper.properties @@ -0,0 +1,27 @@ +# locale/zh_CN/FlexPaper.properties +Print=打印 +FitWidth=适合宽度 +FitPage=适合整页 +Scale=缩放 +ThumbView=缩略图 +CurrentPage=当前页 +Search=搜索 +NextPage=下一页 +PreviousPage=上一页 +Fullscreen=全屏 +About=关于 +Finishedsearching=文档搜索完成.没有发现更多 的匹配. +Searchfinished=搜索完成 +Selectprintrange=选择打印范围 +All=所有页 +CurrentPage=当前页 +Pages=页范围: +Enterpagenumbers=输 入页码,用逗号分割各页.例如 1,3,5-12 +Cancel=取消 +IncorrectRange=页范围输入不正确 +Incorrectrangespecified=没有按照规定输入页范围 +About=关于 +Developedby=开发者 Devaldi. +Formoreinformation=需要了解更多信息,请参见 +TwoPage=第二页 +SinglePage=单页 \ No newline at end of file diff --git a/docviewerflex.backup/module_docviewerflex.xml b/docviewerflex.backup/module_docviewerflex.xml new file mode 100644 index 0000000..d5613bb --- /dev/null +++ b/docviewerflex.backup/module_docviewerflex.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docviewerflex.backup/src/DocViewerFlex.mxml b/docviewerflex.backup/src/DocViewerFlex.mxml new file mode 100644 index 0000000..78734e5 --- /dev/null +++ b/docviewerflex.backup/src/DocViewerFlex.mxml @@ -0,0 +1,163 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/docviewerflex.backup/src/caurina/transitions/AuxFunctions.as b/docviewerflex.backup/src/caurina/transitions/AuxFunctions.as new file mode 100644 index 0000000..75dffc6 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/AuxFunctions.as @@ -0,0 +1,77 @@ +package caurina.transitions { + + /** + * Generic, auxiliary functions + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class AuxFunctions { + + /** + * Gets the R (xx0000) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The R value + */ + public static function numberToR(p_num:Number):Number { + // The initial & is meant to crop numbers bigger than 0xffffff + return (p_num & 0xff0000) >> 16; + } + + /** + * Gets the G (00xx00) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The G value + */ + public static function numberToG(p_num:Number):Number { + return (p_num & 0xff00) >> 8; + } + + /** + * Gets the B (0000xx) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The B value + */ + public static function numberToB(p_num:Number):Number { + return (p_num & 0xff); + } + + /** + * Returns the number of properties an object has + * + * @param p_object Object Target object with a number of properties + * @return Number Number of total properties the object has + */ + public static function getObjectLength(p_object:Object):uint { + var totalProperties:uint = 0; + for (var pName:String in p_object) totalProperties ++; + return totalProperties; + } + + /* Takes a variable number of objects as parameters and "adds" their properties, from left to right. If a latter object defines a property as null, it will be removed from the final object + * @param args Object(s) A variable number of objects + * @return Object An object with the sum of all paremeters added as properties. + */ + public static function concatObjects(...args) : Object{ + var finalObject : Object = {}; + var currentObject : Object; + for (var i : int = 0; i < args.length; i++){ + currentObject = args[i]; + for (var prop : String in currentObject){ + if (currentObject[prop] == null){ + // delete in case is null + delete finalObject[prop]; + }else{ + finalObject[prop] = currentObject[prop]; + } + } + } + return finalObject; + } + } +} diff --git a/docviewerflex.backup/src/caurina/transitions/Equations.as b/docviewerflex.backup/src/caurina/transitions/Equations.as new file mode 100644 index 0000000..d9893c4 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/Equations.as @@ -0,0 +1,714 @@ +/** + * Equations + * Main equations for the Tweener class + * + * @author Zeh Fernando, Nate Chatellier + * @version 1.0.2 + */ + +/* +Disclaimer for Robert Penner's Easing Equations license: + +TERMS OF USE - EASING EQUATIONS + +Open source under the BSD License. + +Copyright © 2001 Robert Penner +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package caurina.transitions { + + public class Equations { + + /** + * There's no constructor. + * @private + */ + public function Equations () { + trace ("Equations is a static class and should not be instantiated.") + } + + /** + * Registers all the equations to the Tweener class, so they can be found by the direct string parameters. + * This method doesn't actually have to be used - equations can always be referenced by their full function + * names. But "registering" them make them available as their shorthand string names. + */ + public static function init():void { + Tweener.registerTransition("easenone", easeNone); + Tweener.registerTransition("linear", easeNone); // mx.transitions.easing.None.easeNone + + Tweener.registerTransition("easeinquad", easeInQuad); // mx.transitions.easing.Regular.easeIn + Tweener.registerTransition("easeoutquad", easeOutQuad); // mx.transitions.easing.Regular.easeOut + Tweener.registerTransition("easeinoutquad", easeInOutQuad); // mx.transitions.easing.Regular.easeInOut + Tweener.registerTransition("easeoutinquad", easeOutInQuad); + + Tweener.registerTransition("easeincubic", easeInCubic); + Tweener.registerTransition("easeoutcubic", easeOutCubic); + Tweener.registerTransition("easeinoutcubic", easeInOutCubic); + Tweener.registerTransition("easeoutincubic", easeOutInCubic); + + Tweener.registerTransition("easeinquart", easeInQuart); + Tweener.registerTransition("easeoutquart", easeOutQuart); + Tweener.registerTransition("easeinoutquart", easeInOutQuart); + Tweener.registerTransition("easeoutinquart", easeOutInQuart); + + Tweener.registerTransition("easeinquint", easeInQuint); + Tweener.registerTransition("easeoutquint", easeOutQuint); + Tweener.registerTransition("easeinoutquint", easeInOutQuint); + Tweener.registerTransition("easeoutinquint", easeOutInQuint); + + Tweener.registerTransition("easeinsine", easeInSine); + Tweener.registerTransition("easeoutsine", easeOutSine); + Tweener.registerTransition("easeinoutsine", easeInOutSine); + Tweener.registerTransition("easeoutinsine", easeOutInSine); + + Tweener.registerTransition("easeincirc", easeInCirc); + Tweener.registerTransition("easeoutcirc", easeOutCirc); + Tweener.registerTransition("easeinoutcirc", easeInOutCirc); + Tweener.registerTransition("easeoutincirc", easeOutInCirc); + + Tweener.registerTransition("easeinexpo", easeInExpo); // mx.transitions.easing.Strong.easeIn + Tweener.registerTransition("easeoutexpo", easeOutExpo); // mx.transitions.easing.Strong.easeOut + Tweener.registerTransition("easeinoutexpo", easeInOutExpo); // mx.transitions.easing.Strong.easeInOut + Tweener.registerTransition("easeoutinexpo", easeOutInExpo); + + Tweener.registerTransition("easeinelastic", easeInElastic); // mx.transitions.easing.Elastic.easeIn + Tweener.registerTransition("easeoutelastic", easeOutElastic); // mx.transitions.easing.Elastic.easeOut + Tweener.registerTransition("easeinoutelastic", easeInOutElastic); // mx.transitions.easing.Elastic.easeInOut + Tweener.registerTransition("easeoutinelastic", easeOutInElastic); + + Tweener.registerTransition("easeinback", easeInBack); // mx.transitions.easing.Back.easeIn + Tweener.registerTransition("easeoutback", easeOutBack); // mx.transitions.easing.Back.easeOut + Tweener.registerTransition("easeinoutback", easeInOutBack); // mx.transitions.easing.Back.easeInOut + Tweener.registerTransition("easeoutinback", easeOutInBack); + + Tweener.registerTransition("easeinbounce", easeInBounce); // mx.transitions.easing.Bounce.easeIn + Tweener.registerTransition("easeoutbounce", easeOutBounce); // mx.transitions.easing.Bounce.easeOut + Tweener.registerTransition("easeinoutbounce", easeInOutBounce); // mx.transitions.easing.Bounce.easeInOut + Tweener.registerTransition("easeoutinbounce", easeOutInBounce); + } + + // ================================================================================================================================== + // TWEENING EQUATIONS functions ----------------------------------------------------------------------------------------------------- + // (the original equations are Robert Penner's work as mentioned on the disclaimer) + + /** + * Easing equation function for a simple linear tweening, with no easing. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeNone (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*t/d + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c *(t/=d)*(t-2) + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuad (t*2, b, c/2, d, p_params); + return easeInQuad((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a cubic (t^3) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t + b; + } + + /** + * Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*((t=t/d-1)*t*t + 1) + b; + } + + /** + * Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t + b; + return c/2*((t-=2)*t*t + 2) + b; + } + + /** + * Easing equation function for a cubic (t^3) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutCubic (t*2, b, c/2, d, p_params); + return easeInCubic((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t*t + b; + } + + /** + * Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + } + + /** + * Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + } + + /** + * Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuart (t*2, b, c/2, d, p_params); + return easeInQuart((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t*t*t + b; + } + + /** + * Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*((t=t/d-1)*t*t*t*t + 1) + b; + } + + /** + * Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; + return c/2*((t-=2)*t*t*t*t + 2) + b; + } + + /** + * Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuint (t*2, b, c/2, d, p_params); + return easeInQuint((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * Math.cos(t/d * (Math.PI/2)) + c + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c * Math.sin(t/d * (Math.PI/2)) + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutSine (t*2, b, c/2, d, p_params); + return easeInSine((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b - c * 0.001; + } + + /** + * Easing equation function for an exponential (2^t) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return (t==d) ? b+c : c * 1.001 * (-Math.pow(2, -10 * t/d) + 1) + b; + } + + /** + * Easing equation function for an exponential (2^t) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if (t==d) return b+c; + if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b - c * 0.0005; + return c/2 * 1.0005 * (-Math.pow(2, -10 * --t) + 2) + b; + } + + /** + * Easing equation function for an exponential (2^t) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutExpo (t*2, b, c/2, d, p_params); + return easeInExpo((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c * Math.sqrt(1 - (t=t/d-1)*t) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; + return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutCirc (t*2, b, c/2, d, p_params); + return easeInCirc((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d)==1) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d)==1) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b); + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeInOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d/2)==2) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*(.3*1.5) : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeOutInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutElastic (t*2, b, c/2, d, p_params); + return easeInElastic((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + return c*(t/=d)*t*((s+1)*t - s) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeInOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeOutInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutBack (t*2, b, c/2, d, p_params); + return easeInBack((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c - easeOutBounce (d-t, 0, c, d) + b; + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeInBounce (t*2, 0, c, d) * .5 + b; + else return easeOutBounce (t*2-d, 0, c, d) * .5 + c*.5 + b; + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutBounce (t*2, b, c/2, d, p_params); + return easeInBounce((t*2)-d, b+c/2, c/2, d, p_params); + } + } +} diff --git a/docviewerflex.backup/src/caurina/transitions/PropertyInfoObj.as b/docviewerflex.backup/src/caurina/transitions/PropertyInfoObj.as new file mode 100644 index 0000000..132aaa5 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/PropertyInfoObj.as @@ -0,0 +1,90 @@ +package caurina.transitions { + + /** + * PropertyInfoObj + * An object containing the updating info for a given property (its starting value, and its final value) + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class PropertyInfoObj { + + public var valueStart :Number; // Starting value of the tweening (null if not started yet) + public var valueComplete :Number; // Final desired value + public var originalValueComplete :Object; // Final desired value as declared initially + public var arrayIndex :Number; // Index (if this is an array item) + public var extra :Object; // Additional parameters, used by some special properties + public var isSpecialProperty :Boolean; // Whether or not this is a special property instead of a direct one + public var hasModifier :Boolean; // Whether or not it has a modifier function + public var modifierFunction :Function; // Modifier function, if any + public var modifierParameters :Array; // Additional array of modifier parameters + + // ================================================================================================================================== + // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- + + /** + * Initializes the basic PropertyInfoObj. + * + * @param p_valueStart Number Starting value of the tweening (null if not started yet) + * @param p_valueComplete Number Final (desired) property value + */ + function PropertyInfoObj(p_valueStart:Number, p_valueComplete:Number, p_originalValueComplete:Object, p_arrayIndex:Number, p_extra:Object, p_isSpecialProperty:Boolean, p_modifierFunction:Function, p_modifierParameters:Array) { + valueStart = p_valueStart; + valueComplete = p_valueComplete; + originalValueComplete = p_originalValueComplete; + arrayIndex = p_arrayIndex; + extra = p_extra; + isSpecialProperty = p_isSpecialProperty; + hasModifier = Boolean(p_modifierFunction); + modifierFunction = p_modifierFunction; + modifierParameters = p_modifierParameters; + } + + + // ================================================================================================================================== + // OTHER functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Clones this property info and returns the new PropertyInfoObj + * + * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted + * @return TweenListObj A copy of this object + */ + public function clone():PropertyInfoObj { + var nProperty:PropertyInfoObj = new PropertyInfoObj(valueStart, valueComplete, originalValueComplete, arrayIndex, extra, isSpecialProperty, modifierFunction, modifierParameters); + return nProperty; + } + + /** + * Returns this object described as a String. + * + * @return String The description of this object. + */ + public function toString():String { + var returnStr:String = "\n[PropertyInfoObj "; + returnStr += "valueStart:" + String(valueStart); + returnStr += ", "; + returnStr += "valueComplete:" + String(valueComplete); + returnStr += ", "; + returnStr += "originalValueComplete:" + String(originalValueComplete); + returnStr += ", "; + returnStr += "arrayIndex:" + String(arrayIndex); + returnStr += ", "; + returnStr += "extra:" + String(extra); + returnStr += ", "; + returnStr += "isSpecialProperty:" + String(isSpecialProperty); + returnStr += ", "; + returnStr += "hasModifier:" + String(hasModifier); + returnStr += ", "; + returnStr += "modifierFunction:" + String(modifierFunction); + returnStr += ", "; + returnStr += "modifierParameters:" + String(modifierParameters); + returnStr += "]\n"; + return returnStr; + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/SpecialProperty.as b/docviewerflex.backup/src/caurina/transitions/SpecialProperty.as new file mode 100644 index 0000000..a261597 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/SpecialProperty.as @@ -0,0 +1,49 @@ +package caurina.transitions { + + /** + * SpecialProperty + * A kind of a getter/setter for special properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialProperty { + + public var getValue:Function; // (p_obj:Object, p_parameters:Array, p_extra:Object): Number + public var setValue:Function; // (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object): Void + public var parameters:Array; + public var preProcess:Function; // (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number + + /** + * Builds a new special property object. + * + * @param p_getFunction Function Reference to the function used to get the special property value + * @param p_setFunction Function Reference to the function used to set the special property value + */ + public function SpecialProperty (p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null) { + getValue = p_getFunction; + setValue = p_setFunction; + parameters = p_parameters; + preProcess = p_preProcessFunction; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialProperty "; + value += "getValue:"+String(getValue); + value += ", "; + value += "setValue:"+String(setValue); + value += ", "; + value += "parameters:"+String(parameters); + value += ", "; + value += "preProcess:"+String(preProcess); + value += "]"; + return value; + } + } +} diff --git a/docviewerflex.backup/src/caurina/transitions/SpecialPropertyModifier.as b/docviewerflex.backup/src/caurina/transitions/SpecialPropertyModifier.as new file mode 100644 index 0000000..049af18 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/SpecialPropertyModifier.as @@ -0,0 +1,42 @@ +package caurina.transitions { + + /** + * SpecialPropertyModifier + * A special property which actually acts on other properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialPropertyModifier { + + public var modifyValues:Function; + public var getValue:Function; + + /** + * Builds a new special property modifier object. + * + * @param p_modifyFunction Function Function that returns the modifider parameters. + */ + public function SpecialPropertyModifier (p_modifyFunction:Function, p_getFunction:Function) { + modifyValues = p_modifyFunction; + getValue = p_getFunction; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialPropertyModifier "; + value += "modifyValues:"+String(modifyValues); + value += ", "; + value += "getValue:"+String(getValue); + value += "]"; + return value; + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/SpecialPropertySplitter.as b/docviewerflex.backup/src/caurina/transitions/SpecialPropertySplitter.as new file mode 100644 index 0000000..eeef903 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/SpecialPropertySplitter.as @@ -0,0 +1,42 @@ +package caurina.transitions { + + /** + * SpecialPropertySplitter + * A proxy setter for special properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialPropertySplitter { + + public var parameters:Array; + public var splitValues:Function; + + /** + * Builds a new group special property object. + * + * @param p_splitFunction Function Reference to the function used to split a value + */ + public function SpecialPropertySplitter (p_splitFunction:Function, p_parameters:Array) { + splitValues = p_splitFunction; + parameters = p_parameters; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialPropertySplitter "; + value += "splitValues:"+String(splitValues); // .toString(); + value += ", "; + value += "parameters:"+String(parameters); + value += "]"; + return value; + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/TweenListObj.as b/docviewerflex.backup/src/caurina/transitions/TweenListObj.as new file mode 100644 index 0000000..77fa1fe --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/TweenListObj.as @@ -0,0 +1,236 @@ +package caurina.transitions { + import caurina.transitions.AuxFunctions; + /** + * The tween list object. Stores all of the properties and information that pertain to individual tweens. + * + * @author Nate Chatellier, Zeh Fernando + * @version 1.0.4 + * @private + */ + + public class TweenListObj { + + public var scope :Object; // Object affected by this tweening + public var properties :Object; // List of properties that are tweened (PropertyInfoObj instances) + // .valueStart :Number // Initial value of the property + // .valueComplete :Number // The value the property should have when completed + public var timeStart :Number; // Time when this tweening should start + public var timeComplete :Number; // Time when this tweening should end + public var useFrames :Boolean; // Whether or not to use frames instead of time + public var transition :Function; // Equation to control the transition animation + public var transitionParams :Object; // Additional parameters for the transition + public var onStart :Function; // Function to be executed on the object when the tween starts (once) + public var onUpdate :Function; // Function to be executed on the object when the tween updates (several times) + public var onComplete :Function; // Function to be executed on the object when the tween completes (once) + public var onOverwrite :Function; // Function to be executed on the object when the tween is overwritten + public var onError :Function; // Function to be executed if an error is thrown when tweener exectues a callback (onComplete, onUpdate etc) + public var onStartParams :Array; // Array of parameters to be passed for the event + public var onUpdateParams :Array; // Array of parameters to be passed for the event + public var onCompleteParams :Array; // Array of parameters to be passed for the event + public var onOverwriteParams :Array; // Array of parameters to be passed for the event + public var onStartScope :Object; // Scope in which the event function is ran + public var onUpdateScope :Object; // Scope in which the event function is ran + public var onCompleteScope :Object; // Scope in which the event function is ran + public var onOverwriteScope :Object; // Scope in which the event function is ran + public var onErrorScope :Object; // Scope in which the event function is ran + public var rounded :Boolean; // Use rounded values when updating + public var isPaused :Boolean; // Whether or not this tween is paused + public var timePaused :Number; // Time when this tween was paused + public var isCaller :Boolean; // Whether or not this tween is a "caller" tween + public var count :Number; // Number of times this caller should be called + public var timesCalled :Number; // How many times the caller has already been called ("caller" tweens only) + public var waitFrames :Boolean; // Whether or not this caller should wait at least one frame for each call execution ("caller" tweens only) + public var skipUpdates :Number; // How many updates should be skipped (default = 0; 1 = update-skip-update-skip...) + public var updatesSkipped :Number; // How many updates have already been skipped + public var hasStarted :Boolean; // Whether or not this tween has already started + + // ================================================================================================================================== + // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- + + /** + * Initializes the basic TweenListObj. + * + * @param p_scope Object Object affected by this tweening + * @param p_timeStart Number Time when this tweening should start + * @param p_timeComplete Number Time when this tweening should end + * @param p_useFrames Boolean Whether or not to use frames instead of time + * @param p_transition Function Equation to control the transition animation + */ + function TweenListObj(p_scope:Object, p_timeStart:Number, p_timeComplete:Number, p_useFrames:Boolean, p_transition:Function, p_transitionParams:Object) { + scope = p_scope; + timeStart = p_timeStart; + timeComplete = p_timeComplete; + useFrames = p_useFrames; + transition = p_transition; + transitionParams = p_transitionParams; + + // Other default information + properties = new Object(); + isPaused = false; + timePaused = undefined; + isCaller = false; + updatesSkipped = 0; + timesCalled = 0; + skipUpdates = 0; + hasStarted = false; + } + + + // ================================================================================================================================== + // OTHER functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Clones this tweening and returns the new TweenListObj + * + * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted + * @return TweenListObj A copy of this object + */ + public function clone(omitEvents:Boolean):TweenListObj { + var nTween:TweenListObj = new TweenListObj(scope, timeStart, timeComplete, useFrames, transition, transitionParams); + nTween.properties = new Array(); + for (var pName:String in properties) { + nTween.properties[pName] = properties[pName].clone(); + } + nTween.skipUpdates = skipUpdates; + nTween.updatesSkipped = updatesSkipped; + if (!omitEvents) { + nTween.onStart = onStart; + nTween.onUpdate = onUpdate; + nTween.onComplete = onComplete; + nTween.onOverwrite = onOverwrite; + nTween.onError = onError; + nTween.onStartParams = onStartParams; + nTween.onUpdateParams = onUpdateParams; + nTween.onCompleteParams = onCompleteParams; + nTween.onOverwriteParams = onOverwriteParams; + nTween.onStartScope = onStartScope; + nTween.onUpdateScope = onUpdateScope; + nTween.onCompleteScope = onCompleteScope; + nTween.onOverwriteScope = onOverwriteScope; + nTween.onErrorScope = onErrorScope; + } + nTween.rounded = rounded; + nTween.isPaused = isPaused; + nTween.timePaused = timePaused; + nTween.isCaller = isCaller; + nTween.count = count; + nTween.timesCalled = timesCalled; + nTween.waitFrames = waitFrames; + nTween.hasStarted = hasStarted; + + return nTween; + } + + /** + * Returns this object described as a String. + * + * @return String The description of this object. + */ + public function toString():String { + var returnStr:String = "\n[TweenListObj "; + returnStr += "scope:" + String(scope); + returnStr += ", properties:"; + var isFirst:Boolean = true; + for (var i:String in properties) { + if (!isFirst) returnStr += ","; + returnStr += "[name:"+properties[i].name; + returnStr += ",valueStart:"+properties[i].valueStart; + returnStr += ",valueComplete:"+properties[i].valueComplete; + returnStr += "]"; + isFirst = false; + } + returnStr += ", timeStart:" + String(timeStart); + returnStr += ", timeComplete:" + String(timeComplete); + returnStr += ", useFrames:" + String(useFrames); + returnStr += ", transition:" + String(transition); + returnStr += ", transitionParams:" + String(transitionParams); + + if (skipUpdates) returnStr += ", skipUpdates:" + String(skipUpdates); + if (updatesSkipped) returnStr += ", updatesSkipped:" + String(updatesSkipped); + + if (Boolean(onStart)) returnStr += ", onStart:" + String(onStart); + if (Boolean(onUpdate)) returnStr += ", onUpdate:" + String(onUpdate); + if (Boolean(onComplete)) returnStr += ", onComplete:" + String(onComplete); + if (Boolean(onOverwrite)) returnStr += ", onOverwrite:" + String(onOverwrite); + if (Boolean(onError)) returnStr += ", onError:" + String(onError); + + if (onStartParams) returnStr += ", onStartParams:" + String(onStartParams); + if (onUpdateParams) returnStr += ", onUpdateParams:" + String(onUpdateParams); + if (onCompleteParams) returnStr += ", onCompleteParams:" + String(onCompleteParams); + if (onOverwriteParams) returnStr += ", onOverwriteParams:" + String(onOverwriteParams); + + if (onStartScope) returnStr += ", onStartScope:" + String(onStartScope); + if (onUpdateScope) returnStr += ", onUpdateScope:" + String(onUpdateScope); + if (onCompleteScope) returnStr += ", onCompleteScope:" + String(onCompleteScope); + if (onOverwriteScope) returnStr += ", onOverwriteScope:" + String(onOverwriteScope); + if (onErrorScope) returnStr += ", onErrorScope:" + String(onErrorScope); + + if (rounded) returnStr += ", rounded:" + String(rounded); + if (isPaused) returnStr += ", isPaused:" + String(isPaused); + if (timePaused) returnStr += ", timePaused:" + String(timePaused); + if (isCaller) returnStr += ", isCaller:" + String(isCaller); + if (count) returnStr += ", count:" + String(count); + if (timesCalled) returnStr += ", timesCalled:" + String(timesCalled); + if (waitFrames) returnStr += ", waitFrames:" + String(waitFrames); + if (hasStarted) returnStr += ", hasStarted:" + String(hasStarted); + + returnStr += "]\n"; + return returnStr; + } + + /** + * Checks if p_obj "inherits" properties from other objects, as set by the "base" property. Will create a new object, leaving others intact. + * o_bj.base can be an object or an array of objects. Properties are collected from the first to the last element of the "base" filed, with higher + * indexes overwritting smaller ones. Does not modify any of the passed objects, but makes a shallow copy of all properties. + * + * @param p_obj Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @return Object A new object with all properties from the p_obj and p_obj.base. + */ + + public static function makePropertiesChain(p_obj : Object) : Object{ + // Is this object inheriting properties from another object? + var baseObject : Object = p_obj.base; + if(baseObject){ + // object inherits. Are we inheriting from an object or an array + var chainedObject : Object = {}; + var chain : Object; + if (baseObject is Array){ + // Inheritance chain is the base array + chain = []; + // make a shallow copy + for (var k : Number = 0 ; k< baseObject.length; k++) chain.push(baseObject[k]); + }else{ + // Only one object to be added to the array + chain = [baseObject]; + } + // add the final object to the array, so it's properties are added last + chain.push(p_obj); + var currChainObj : Object; + // Loops through each object adding it's property to the final object + var len : Number = chain.length; + for(var i : Number = 0; i < len ; i ++){ + if(chain[i]["base"]){ + // deal with recursion: watch the order! "parent" base must be concatenated first! + currChainObj = AuxFunctions.concatObjects( makePropertiesChain(chain[i]["base"] ), chain[i]); + }else{ + currChainObj = chain[i] ; + } + chainedObject = AuxFunctions.concatObjects(chainedObject, currChainObj ); + } + if( chainedObject["base"]){ + delete chainedObject["base"]; + } + return chainedObject; + }else{ + // No inheritance, just return the object it self + return p_obj; + } + } + + + } + + + + +} diff --git a/docviewerflex.backup/src/caurina/transitions/Tweener.as b/docviewerflex.backup/src/caurina/transitions/Tweener.as new file mode 100644 index 0000000..99b958b --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/Tweener.as @@ -0,0 +1,1143 @@ +/** + * Tweener + * Transition controller for movieclips, sounds, textfields and other objects + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert, Francis Turmel + * @version 1.33.74 + */ + +/* +Licensed under the MIT License + +Copyright (c) 2006-2008 Zeh Fernando, Nate Chatellier, Arthur Debert and Francis +Turmel + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +http://code.google.com/p/tweener/ +http://code.google.com/p/tweener/wiki/License +*/ + +package caurina.transitions { + + import flash.display.*; + import flash.events.Event; + import flash.utils.getTimer; + + public class Tweener { + + private static var __tweener_controller__:MovieClip; // Used to ensure the stage copy is always accessible (garbage collection) + + private static var _engineExists:Boolean = false; // Whether or not the engine is currently running + private static var _inited:Boolean = false; // Whether or not the class has been initiated + private static var _currentTime:Number; // The current time. This is generic for all tweenings for a "time grid" based update + private static var _currentTimeFrame:Number; // The current frame. Used on frame-based tweenings + + private static var _tweenList:Array; // List of active tweens + + private static var _timeScale:Number = 1; // Time scale (default = 1) + + private static var _transitionList:Object; // List of "pre-fetched" transition functions + private static var _specialPropertyList:Object; // List of special properties + private static var _specialPropertyModifierList:Object; // List of special property modifiers + private static var _specialPropertySplitterList:Object; // List of special property splitters + + public static var autoOverwrite:Boolean = true; // If true, auto overwrite on new tweens is on unless declared as false + + /** + * There's no constructor. + * @private + */ + public function Tweener () { + trace ("Tweener is a static class and should not be instantiated."); + } + + // ================================================================================================================================== + // TWEENING CONTROL functions ------------------------------------------------------------------------------------------------------- + + /** + * Adds a new tweening. + * + * @param (first-n param) Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @param (last param) Object Object containing the specified parameters in any order, as well as the properties that should be tweened and their values + * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) + * @param .delay Number Delay time (defaults 0) + * @param .useFrames Boolean Whether to use frames instead of seconds for time control (defaults false) + * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") + * @param .onStart Function * Direct property, See the TweenListObj class + * @param .onUpdate Function * Direct property, See the TweenListObj class + * @param .onComplete Function * Direct property, See the TweenListObj class + * @param .onOverwrite Function * Direct property, See the TweenListObj class + * @param .onStartParams Array * Direct property, See the TweenListObj class + * @param .onUpdateParams Array * Direct property, See the TweenListObj class + * @param .onCompleteParams Array * Direct property, See the TweenListObj class + * @param .onOverwriteParams Array * Direct property, See the TweenListObj class + * @param .rounded Boolean * Direct property, See the TweenListObj class + * @param .skipUpdates Number * Direct property, See the TweenListObj class + * @return Boolean TRUE if the tween was successfully added, FALSE if otherwise + */ + public static function addTween (p_scopes:Object = null, p_parameters:Object = null):Boolean { + if (!Boolean(p_scopes)) return false; + + var i:Number, j:Number, istr:String; + + var rScopes:Array; // List of objects to tween + if (p_scopes is Array) { + // The first argument is an array + rScopes = p_scopes.concat(); + } else { + // The first argument(s) is(are) object(s) + rScopes = [p_scopes]; + } + + // make properties chain ("inheritance") + var p_obj:Object = TweenListObj.makePropertiesChain(p_parameters); + + // Creates the main engine if it isn't active + if (!_inited) init(); + if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... + + // Creates a "safer", more strict tweening object + var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time + var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay + + // Creates the property list; everything that isn't a hardcoded variable + var rProperties:Array = new Array(); // Object containing a list of PropertyInfoObj instances + var restrictedWords:Object = {overwrite:true, time:true, delay:true, useFrames:true, skipUpdates:true, transition:true, transitionParams:true, onStart:true, onUpdate:true, onComplete:true, onOverwrite:true, onError:true, rounded:true, onStartParams:true, onUpdateParams:true, onCompleteParams:true, onOverwriteParams:true, onStartScope:true, onUpdateScope:true, onCompleteScope:true, onOverwriteScope:true, onErrorScope:true}; + var modifiedProperties:Object = new Object(); + for (istr in p_obj) { + if (!restrictedWords[istr]) { + // It's an additional pair, so adds + if (_specialPropertySplitterList[istr]) { + // Special property splitter + var splitProperties:Array = _specialPropertySplitterList[istr].splitValues(p_obj[istr], _specialPropertySplitterList[istr].parameters); + for (i = 0; i < splitProperties.length; i++) { + if (_specialPropertySplitterList[splitProperties[i].name]) { + var splitProperties2:Array = _specialPropertySplitterList[splitProperties[i].name].splitValues(splitProperties[i].value, _specialPropertySplitterList[splitProperties[i].name].parameters); + for (j = 0; j < splitProperties2.length; j++) { + rProperties[splitProperties2[j].name] = {valueStart:undefined, valueComplete:splitProperties2[j].value, arrayIndex:splitProperties2[j].arrayIndex, isSpecialProperty:false}; + } + } else { + rProperties[splitProperties[i].name] = {valueStart:undefined, valueComplete:splitProperties[i].value, arrayIndex:splitProperties[i].arrayIndex, isSpecialProperty:false}; + } + } + } else if (_specialPropertyModifierList[istr] != undefined) { + // Special property modifier + var tempModifiedProperties:Array = _specialPropertyModifierList[istr].modifyValues(p_obj[istr]); + for (i = 0; i < tempModifiedProperties.length; i++) { + modifiedProperties[tempModifiedProperties[i].name] = {modifierParameters:tempModifiedProperties[i].parameters, modifierFunction:_specialPropertyModifierList[istr].getValue}; + } + } else { + // Regular property or special property, just add the property normally + rProperties[istr] = {valueStart:undefined, valueComplete:p_obj[istr]}; + } + } + } + + // Verifies whether the properties exist or not, for warning messages + for (istr in rProperties) { + if (_specialPropertyList[istr] != undefined) { + rProperties[istr].isSpecialProperty = true; + } else { + if (rScopes[0][istr] == undefined) { + printError("The property '" + istr + "' doesn't seem to be a normal object property of " + String(rScopes[0]) + " or a registered special property."); + } + } + } + + // Adds the modifiers to the list of properties + for (istr in modifiedProperties) { + if (rProperties[istr] != undefined) { + rProperties[istr].modifierParameters = modifiedProperties[istr].modifierParameters; + rProperties[istr].modifierFunction = modifiedProperties[istr].modifierFunction; + } + + } + + var rTransition:Function; // Real transition + + if (typeof p_obj.transition == "string") { + // String parameter, transition names + var trans:String = p_obj.transition.toLowerCase(); + rTransition = _transitionList[trans]; + } else { + // Proper transition function + rTransition = p_obj.transition; + } + if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; + + var nProperties:Object; + var nTween:TweenListObj; + var myT:Number; + + for (i = 0; i < rScopes.length; i++) { + // Makes a copy of the properties + nProperties = new Object(); + for (istr in rProperties) { + nProperties[istr] = new PropertyInfoObj(rProperties[istr].valueStart, rProperties[istr].valueComplete, rProperties[istr].valueComplete, rProperties[istr].arrayIndex, {}, rProperties[istr].isSpecialProperty, rProperties[istr].modifierFunction, rProperties[istr].modifierParameters); + } + + if (p_obj.useFrames == true) { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), + /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), + /* useFrames */ true, + /* transition */ rTransition, + p_obj.transitionParams + ); + } else { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), + /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), + /* useFrames */ false, + /* transition */ rTransition, + p_obj.transitionParams + ); + } + + nTween.properties = nProperties; + nTween.onStart = p_obj.onStart; + nTween.onUpdate = p_obj.onUpdate; + nTween.onComplete = p_obj.onComplete; + nTween.onOverwrite = p_obj.onOverwrite; + nTween.onError = p_obj.onError; + nTween.onStartParams = p_obj.onStartParams; + nTween.onUpdateParams = p_obj.onUpdateParams; + nTween.onCompleteParams = p_obj.onCompleteParams; + nTween.onOverwriteParams = p_obj.onOverwriteParams; + nTween.onStartScope = p_obj.onStartScope; + nTween.onUpdateScope = p_obj.onUpdateScope; + nTween.onCompleteScope = p_obj.onCompleteScope; + nTween.onOverwriteScope = p_obj.onOverwriteScope; + nTween.onErrorScope = p_obj.onErrorScope; + nTween.rounded = p_obj.rounded; + nTween.skipUpdates = p_obj.skipUpdates; + + // Remove other tweenings that occur at the same time + if (p_obj.overwrite == undefined ? autoOverwrite : p_obj.overwrite) removeTweensByTime(nTween.scope, nTween.properties, nTween.timeStart, nTween.timeComplete); // Changed on 1.32.74 + + // And finally adds it to the list + _tweenList.push(nTween); + + // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution + if (rTime == 0 && rDelay == 0) { + myT = _tweenList.length-1; + updateTweenByIndex(myT); + removeTweenByIndex(myT); + } + } + + return true; + } + + // A "caller" is like this: [ | | | ||] got it? :) + // this function is crap - should be fixed later/extend on addTween() + + /** + * Adds a new caller tweening. + * + * @param (first-n param) Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @param (last param) Object containing the specified parameters in any order, as well as the properties that should be tweened and their values + * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) + * @param .delay Number Delay time (defaults 0) + * @param .count Number Number of times this caller should be called + * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") + * @param .onStart Function Event called when tween starts + * @param .onUpdate Function Event called when tween updates + * @param .onComplete Function Event called when tween ends + * @param .waitFrames Boolean Whether to wait (or not) one frame for each call + * @return true if the tween was successfully added, false if otherwise. + */ + public static function addCaller (p_scopes:Object = null, p_parameters:Object = null):Boolean { + if (!Boolean(p_scopes)) return false; + + var i:Number; + + var rScopes:Array; // List of objects to tween + if (p_scopes is Array) { + // The first argument is an array + rScopes = p_scopes.concat(); + } else { + // The first argument(s) is(are) object(s) + rScopes = [p_scopes]; + } + + var p_obj:Object = p_parameters; + + // Creates the main engine if it isn't active + if (!_inited) init(); + if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... + + // Creates a "safer", more strict tweening object + var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time + var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay + + var rTransition:Function; // Real transition + if (typeof p_obj.transition == "string") { + // String parameter, transition names + var trans:String = p_obj.transition.toLowerCase(); + rTransition = _transitionList[trans]; + } else { + // Proper transition function + rTransition = p_obj.transition; + } + if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; + + var nTween:TweenListObj; + var myT:Number; + for (i = 0; i < rScopes.length; i++) { + + if (p_obj.useFrames == true) { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), + /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), + /* useFrames */ true, + /* transition */ rTransition, + p_obj.transitionParams + ); + } else { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), + /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), + /* useFrames */ false, + /* transition */ rTransition, + p_obj.transitionParams + ); + } + + nTween.properties = null; + nTween.onStart = p_obj.onStart; + nTween.onUpdate = p_obj.onUpdate; + nTween.onComplete = p_obj.onComplete; + nTween.onOverwrite = p_obj.onOverwrite; + nTween.onStartParams = p_obj.onStartParams; + nTween.onUpdateParams = p_obj.onUpdateParams; + nTween.onCompleteParams = p_obj.onCompleteParams; + nTween.onOverwriteParams = p_obj.onOverwriteParams; + nTween.onStartScope = p_obj.onStartScope; + nTween.onUpdateScope = p_obj.onUpdateScope; + nTween.onCompleteScope = p_obj.onCompleteScope; + nTween.onOverwriteScope = p_obj.onOverwriteScope; + nTween.onErrorScope = p_obj.onErrorScope; + nTween.isCaller = true; + nTween.count = p_obj.count; + nTween.waitFrames = p_obj.waitFrames; + + // And finally adds it to the list + _tweenList.push(nTween); + + // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution + if (rTime == 0 && rDelay == 0) { + myT = _tweenList.length-1; + updateTweenByIndex(myT); + removeTweenByIndex(myT); + } + } + + return true; + } + + /** + * Remove an specified tweening of a specified object the tweening list, if it conflicts with the given time. + * + * @param p_scope Object List of objects affected + * @param p_properties Object List of properties affected (PropertyInfoObj instances) + * @param p_timeStart Number Time when the new tween starts + * @param p_timeComplete Number Time when the new tween ends + * @return Boolean Whether or not it actually deleted something + */ + public static function removeTweensByTime (p_scope:Object, p_properties:Object, p_timeStart:Number, p_timeComplete:Number):Boolean { + var removed:Boolean = false; + var removedLocally:Boolean; + + var i:uint; + var tl:uint = _tweenList.length; + var pName:String; + + for (i = 0; i < tl; i++) { + if (Boolean(_tweenList[i]) && p_scope == _tweenList[i].scope) { + // Same object... + if (p_timeComplete > _tweenList[i].timeStart && p_timeStart < _tweenList[i].timeComplete) { + // New time should override the old one... + removedLocally = false; + for (pName in _tweenList[i].properties) { + if (Boolean(p_properties[pName])) { + // Same object, same property + // Finally, remove this old tweening and use the new one + if (Boolean(_tweenList[i].onOverwrite)) { + var eventScope:Object = Boolean(_tweenList[i].onOverwriteScope) ? _tweenList[i].onOverwriteScope : _tweenList[i].scope; + try { + _tweenList[i].onOverwrite.apply(eventScope, _tweenList[i].onOverwriteParams); + } catch(e:Error) { + handleError(_tweenList[i], e, "onOverwrite"); + } + } + _tweenList[i].properties[pName] = undefined; + delete _tweenList[i].properties[pName]; + removedLocally = true; + removed = true; + } + } + if (removedLocally) { + // Verify if this can be deleted + if (AuxFunctions.getObjectLength(_tweenList[i].properties) == 0) removeTweenByIndex(i); + } + } + } + } + + return removed; + } + + /* + public static function removeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(removeTweenByIndex, p_scope, properties); + } + */ + + /** + * Remove tweenings from a given object from the tweening list. + * + * @param p_tween Object Object that must have its tweens removed + * @param (2nd-last params) Object Property(ies) that must be removed + * @return Boolean Whether or not it successfully removed this tweening + */ + public static function removeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1){ + if (_specialPropertySplitterList[args[i]]){ + //special property, get splitter array first + var sps:SpecialPropertySplitter = _specialPropertySplitterList[args[i]]; + var specialProps:Array = sps.splitValues(p_scope, null); + for (var j:uint = 0; jtrue if it successfully removed any tweening, false if otherwise. + */ + public static function removeAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var removed:Boolean = false; + var i:uint; + for (i = 0; i<_tweenList.length; i++) { + removeTweenByIndex(i); + removed = true; + } + return removed; + } + + /** + * Pause tweenings for a given object. + * + * @param p_scope Object that must have its tweens paused + * @param (2nd-last params) Property(ies) that must be paused + * @return true if it successfully paused any tweening, false if otherwise. + */ + public static function pauseTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(pauseTweenByIndex, p_scope, properties); + } + + /** + * Pause all tweenings on the engine. + * + * @return true if it successfully paused any tweening, false if otherwise. + * @see #resumeAllTweens() + */ + public static function pauseAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var paused:Boolean = false; + var i:uint; + for (i = 0; i < _tweenList.length; i++) { + pauseTweenByIndex(i); + paused = true; + } + return paused; + } + + /** + * Resume tweenings from a given object. + * + * @param p_scope Object Object that must have its tweens resumed + * @param (2nd-last params) Object Property(ies) that must be resumed + * @return Boolean Whether or not it successfully resumed something + */ + public static function resumeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(resumeTweenByIndex, p_scope, properties); + } + + /** + * Resume all tweenings on the engine. + * + * @return true if it successfully resumed any tweening, false if otherwise. + * @see #pauseAllTweens() + */ + public static function resumeAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var resumed:Boolean = false; + var i:uint; + for (i = 0; i < _tweenList.length; i++) { + resumeTweenByIndex(i); + resumed = true; + } + return resumed; + } + + /** + * Do some generic action on specific tweenings (pause, resume, remove, more?) + * + * @param p_function Function Function to run on the tweenings that match + * @param p_scope Object Object that must have its tweens affected by the function + * @param p_properties Array Array of strings that must be affected + * @return Boolean Whether or not it successfully affected something + */ + private static function affectTweens (p_affectFunction:Function, p_scope:Object, p_properties:Array):Boolean { + var affected:Boolean = false; + var i:uint; + + if (!Boolean(_tweenList)) return false; + + for (i = 0; i < _tweenList.length; i++) { + if (_tweenList[i] && _tweenList[i].scope == p_scope) { + if (p_properties.length == 0) { + // Can affect everything + p_affectFunction(i); + affected = true; + } else { + // Must check whether this tween must have specific properties affected + var affectedProperties:Array = new Array(); + var j:uint; + for (j = 0; j < p_properties.length; j++) { + if (Boolean(_tweenList[i].properties[p_properties[j]])) { + affectedProperties.push(p_properties[j]); + } + } + if (affectedProperties.length > 0) { + // This tween has some properties that need to be affected + var objectProperties:uint = AuxFunctions.getObjectLength(_tweenList[i].properties); + if (objectProperties == affectedProperties.length) { + // The list of properties is the same as all properties, so affect it all + p_affectFunction(i); + affected = true; + } else { + // The properties are mixed, so split the tween and affect only certain specific properties + var slicedTweenIndex:uint = splitTweens(i, affectedProperties); + p_affectFunction(slicedTweenIndex); + affected = true; + } + } + } + } + } + return affected; + } + + /** + * Splits a tweening in two + * + * @param p_tween Number Object that must have its tweens split + * @param p_properties Array Array of strings containing the list of properties that must be separated + * @return Number The index number of the new tween + */ + public static function splitTweens (p_tween:Number, p_properties:Array):uint { + // First, duplicates + var originalTween:TweenListObj = _tweenList[p_tween]; + var newTween:TweenListObj = originalTween.clone(false); + + // Now, removes tweenings where needed + var i:uint; + var pName:String; + + // Removes the specified properties from the old one + for (i = 0; i < p_properties.length; i++) { + pName = p_properties[i]; + if (Boolean(originalTween.properties[pName])) { + originalTween.properties[pName] = undefined; + delete originalTween.properties[pName]; + } + } + + // Removes the unspecified properties from the new one + var found:Boolean; + for (pName in newTween.properties) { + found = false; + for (i = 0; i < p_properties.length; i++) { + if (p_properties[i] == pName) { + found = true; + break; + } + } + if (!found) { + newTween.properties[pName] = undefined; + delete newTween.properties[pName]; + } + } + + // If there are empty property lists, a cleanup is done on the next updateTweens() cycle + _tweenList.push(newTween); + return (_tweenList.length - 1); + + } + + // ================================================================================================================================== + // ENGINE functions ----------------------------------------------------------------------------------------------------------------- + + /** + * Updates all existing tweenings. + * + * @return Boolean FALSE if no update was made because there's no tweening (even delayed ones) + */ + private static function updateTweens ():Boolean { + if (_tweenList.length == 0) return false; + var i:int; + for (i = 0; i < _tweenList.length; i++) { + // Looping throught each Tweening and updating the values accordingly + if (_tweenList[i] == undefined || !_tweenList[i].isPaused) { + if (!updateTweenByIndex(i)) removeTweenByIndex(i); + if (_tweenList[i] == null) { + removeTweenByIndex(i, true); + i--; + } + } + } + + return true; + } + + /** + * Remove a specific tweening from the tweening list. + * + * @param p_tween Number Index of the tween to be removed on the tweenings list + * @return Boolean Whether or not it successfully removed this tweening + */ + public static function removeTweenByIndex (i:Number, p_finalRemoval:Boolean = false):Boolean { + _tweenList[i] = null; + if (p_finalRemoval) _tweenList.splice(i, 1); + return true; + } + + /** + * Pauses a specific tween. + * + * @param p_tween Number Index of the tween to be paused + * @return Boolean Whether or not it successfully paused this tweening + */ + public static function pauseTweenByIndex (p_tween:Number):Boolean { + var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening + if (tTweening == null || tTweening.isPaused) return false; + tTweening.timePaused = getCurrentTweeningTime(tTweening); + tTweening.isPaused = true; + + return true; + } + + /** + * Resumes a specific tween. + * + * @param p_tween Number Index of the tween to be resumed + * @return Boolean Whether or not it successfully resumed this tweening + */ + public static function resumeTweenByIndex (p_tween:Number):Boolean { + var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening + if (tTweening == null || !tTweening.isPaused) return false; + var cTime:Number = getCurrentTweeningTime(tTweening); + tTweening.timeStart += cTime - tTweening.timePaused; + tTweening.timeComplete += cTime - tTweening.timePaused; + tTweening.timePaused = undefined; + tTweening.isPaused = false; + + return true; + } + + /** + * Updates a specific tween. + * + * @param i Number Index (from the tween list) of the tween that should be updated + * @return Boolean FALSE if it's already finished and should be deleted, TRUE if otherwise + */ + private static function updateTweenByIndex (i:Number):Boolean { + + var tTweening:TweenListObj = _tweenList[i]; // Shortcut to this tweening + + if (tTweening == null || !Boolean(tTweening.scope)) return false; + + var isOver:Boolean = false; // Whether or not it's over the update time + var mustUpdate:Boolean; // Whether or not it should be updated (skipped if false) + + var nv:Number; // New value for each property + + var t:Number; // current time (frames, seconds) + var b:Number; // beginning value + var c:Number; // change in value + var d:Number; // duration (frames, seconds) + + var pName:String; // Property name, used in loops + var eventScope:Object; // Event scope, used to call functions + + // Shortcut stuff for speed + var tScope:Object; // Current scope + var cTime:Number = getCurrentTweeningTime(tTweening); + var tProperty:Object; // Property being checked + + if (cTime >= tTweening.timeStart) { + // Can already start + + tScope = tTweening.scope; + + if (tTweening.isCaller) { + // It's a 'caller' tween + if (!tTweening.hasStarted) { + if (Boolean(tTweening.onStart)) { + eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; + try { + tTweening.onStart.apply(eventScope, tTweening.onStartParams); + } catch(e2:Error) { + handleError(tTweening, e2, "onStart"); + } + } + tTweening.hasStarted = true; + } + do { + t = ((tTweening.timeComplete - tTweening.timeStart)/tTweening.count) * (tTweening.timesCalled+1); + b = tTweening.timeStart; + c = tTweening.timeComplete - tTweening.timeStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, b, c, d); + + if (cTime >= nv) { + if (Boolean(tTweening.onUpdate)) { + eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; + try { + tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); + } catch(e1:Error) { + handleError(tTweening, e1, "onUpdate"); + } + } + + tTweening.timesCalled++; + if (tTweening.timesCalled >= tTweening.count) { + isOver = true; + break; + } + if (tTweening.waitFrames) break; + } + + } while (cTime >= nv); + } else { + // It's a normal transition tween + + mustUpdate = tTweening.skipUpdates < 1 || !tTweening.skipUpdates || tTweening.updatesSkipped >= tTweening.skipUpdates; + + if (cTime >= tTweening.timeComplete) { + isOver = true; + mustUpdate = true; + } + + if (!tTweening.hasStarted) { + // First update, read all default values (for proper filter tweening) + if (Boolean(tTweening.onStart)) { + eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; + try { + tTweening.onStart.apply(eventScope, tTweening.onStartParams); + } catch(e2:Error) { + handleError(tTweening, e2, "onStart"); + } + } + var pv:Number; + for (pName in tTweening.properties) { + if (tTweening.properties[pName].isSpecialProperty) { + // It's a special property, tunnel via the special property function + if (Boolean(_specialPropertyList[pName].preProcess)) { + tTweening.properties[pName].valueComplete = _specialPropertyList[pName].preProcess(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].originalValueComplete, tTweening.properties[pName].extra); + } + pv = _specialPropertyList[pName].getValue(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); + } else { + // Directly read property + pv = tScope[pName]; + } + tTweening.properties[pName].valueStart = isNaN(pv) ? tTweening.properties[pName].valueComplete : pv; + } + mustUpdate = true; + tTweening.hasStarted = true; + } + + if (mustUpdate) { + for (pName in tTweening.properties) { + tProperty = tTweening.properties[pName]; + + if (isOver) { + // Tweening time has finished, just set it to the final value + nv = tProperty.valueComplete; + } else { + if (tProperty.hasModifier) { + // Modified + t = cTime - tTweening.timeStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, 0, 1, d, tTweening.transitionParams); + nv = tProperty.modifierFunction(tProperty.valueStart, tProperty.valueComplete, nv, tProperty.modifierParameters); + } else { + // Normal update + t = cTime - tTweening.timeStart; + b = tProperty.valueStart; + c = tProperty.valueComplete - tProperty.valueStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, b, c, d, tTweening.transitionParams); + } + } + + if (tTweening.rounded) nv = Math.round(nv); + if (tProperty.isSpecialProperty) { + // It's a special property, tunnel via the special property method + _specialPropertyList[pName].setValue(tScope, nv, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); + } else { + // Directly set property + tScope[pName] = nv; + } + } + + tTweening.updatesSkipped = 0; + + if (Boolean(tTweening.onUpdate)) { + eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; + try { + tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); + } catch(e3:Error) { + handleError(tTweening, e3, "onUpdate"); + } + } + } else { + tTweening.updatesSkipped++; + } + } + + if (isOver && Boolean(tTweening.onComplete)) { + eventScope = Boolean(tTweening.onCompleteScope) ? tTweening.onCompleteScope : tScope; + try { + tTweening.onComplete.apply(eventScope, tTweening.onCompleteParams); + } catch(e4:Error) { + handleError(tTweening, e4, "onComplete"); + } + } + + return (!isOver); + } + + // On delay, hasn't started, so returns true + return (true); + + } + + /** + * Initiates the Tweener--should only be ran once. + */ + public static function init(...rest):void { + _inited = true; + + // Registers all default equations + _transitionList = new Object(); + Equations.init(); + + // Registers all default special properties + _specialPropertyList = new Object(); + _specialPropertyModifierList = new Object(); + _specialPropertySplitterList = new Object(); + } + + /** + * Adds a new function to the available transition list "shortcuts". + * + * @param p_name String Shorthand transition name + * @param p_function Function The proper equation function + */ + public static function registerTransition(p_name:String, p_function:Function): void { + if (!_inited) init(); + _transitionList[p_name] = p_function; + } + + /** + * Adds a new special property to the available special property list. + * + * @param p_name Name of the "special" property. + * @param p_getFunction Function that gets the value. + * @param p_setFunction Function that sets the value. + */ + public static function registerSpecialProperty(p_name:String, p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null): void { + if (!_inited) init(); + var sp:SpecialProperty = new SpecialProperty(p_getFunction, p_setFunction, p_parameters, p_preProcessFunction); + _specialPropertyList[p_name] = sp; + } + + /** + * Adds a new special property modifier to the available modifier list. + * + * @param p_name Name of the "special" property modifier. + * @param p_modifyFunction Function that modifies the value. + * @param p_getFunction Function that gets the value. + */ + public static function registerSpecialPropertyModifier(p_name:String, p_modifyFunction:Function, p_getFunction:Function): void { + if (!_inited) init(); + var spm:SpecialPropertyModifier = new SpecialPropertyModifier(p_modifyFunction, p_getFunction); + _specialPropertyModifierList[p_name] = spm; + } + + /** + * Adds a new special property splitter to the available splitter list. + * + * @param p_name Name of the "special" property splitter. + * @param p_splitFunction Function that splits the value. + */ + public static function registerSpecialPropertySplitter(p_name:String, p_splitFunction:Function, p_parameters:Array = null): void { + if (!_inited) init(); + var sps:SpecialPropertySplitter = new SpecialPropertySplitter(p_splitFunction, p_parameters); + _specialPropertySplitterList[p_name] = sps; + } + + /** + * Starts the Tweener class engine. It is supposed to be running every time a tween exists. + */ + private static function startEngine():void { + _engineExists = true; + _tweenList = new Array(); + + __tweener_controller__ = new MovieClip(); + __tweener_controller__.addEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); + + _currentTimeFrame = 0; + updateTime(); + } + + /** + * Stops the Tweener class engine. + */ + private static function stopEngine():void { + _engineExists = false; + _tweenList = null; + _currentTime = 0; + _currentTimeFrame = 0; + __tweener_controller__.removeEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); + __tweener_controller__ = null; + } + + /** + * Updates the time to enforce time grid-based updates. + */ + public static function updateTime():void { + _currentTime = getTimer(); + } + + /** + * Updates the current frame count + */ + public static function updateFrame():void { + _currentTimeFrame++; + } + + /** + * Ran once every frame. It's the main engine; updates all existing tweenings. + */ + public static function onEnterFrame(e:Event):void { + updateTime(); + updateFrame(); + var hasUpdated:Boolean = false; + hasUpdated = updateTweens(); + if (!hasUpdated) stopEngine(); // There's no tweening to update or wait, so it's better to stop the engine + } + + /** + * Sets the new time scale. + * + * @param p_time Number New time scale (0.5 = slow, 1 = normal, 2 = 2x fast forward, etc) + */ + public static function setTimeScale(p_time:Number):void { + var i:Number; + var cTime:Number; + + if (isNaN(p_time)) p_time = 1; + if (p_time < 0.00001) p_time = 0.00001; + if (p_time != _timeScale) { + if (_tweenList != null) { + // Multiplies all existing tween times accordingly + for (i = 0; i<_tweenList.length; i++) { + cTime = getCurrentTweeningTime(_tweenList[i]); + _tweenList[i].timeStart = cTime - ((cTime - _tweenList[i].timeStart) * _timeScale / p_time); + _tweenList[i].timeComplete = cTime - ((cTime - _tweenList[i].timeComplete) * _timeScale / p_time); + if (_tweenList[i].timePaused != undefined) _tweenList[i].timePaused = cTime - ((cTime - _tweenList[i].timePaused) * _timeScale / p_time); + } + } + // Sets the new timescale value (for new tweenings) + _timeScale = p_time; + } + } + + + // ================================================================================================================================== + // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- + + /** + * Finds whether or not an object has any tweening. + * + * @param p_scope Target object. + * @return true if there's a tweening occuring on this object (paused, delayed, or active), false if otherwise. + */ + public static function isTweening (p_scope:Object):Boolean { + if (!Boolean(_tweenList)) return false; + var i:uint; + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + return true; + } + } + return false; + } + + /** + * Returns an array containing a list of the properties being tweened for this object. + * + * @param p_scope Target object. + * @return Total number of properties being tweened (including delayed or paused tweens). + */ + public static function getTweens (p_scope:Object):Array { + if (!Boolean(_tweenList)) return []; + var i:uint; + var pName:String; + var tList:Array = new Array(); + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + for (pName in _tweenList[i].properties) tList.push(pName); + } + } + return tList; + } + + /** + * Returns the number of properties being tweened for a given object. + * + * @param p_scope Target object. + * @return Total number of properties being tweened (including delayed or paused tweens). + */ + public static function getTweenCount (p_scope:Object):Number { + if (!Boolean(_tweenList)) return 0; + var i:uint; + var c:Number = 0; + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + c += AuxFunctions.getObjectLength(_tweenList[i].properties); + } + } + return c; + } + + + /* Handles errors when Tweener executes any callbacks (onStart, onUpdate, etc) + * If the TweenListObj specifies an onError callback it well get called, passing the Error object and the current scope as parameters. If no onError callback is specified, it will trace a stackTrace. + */ + private static function handleError(pTweening : TweenListObj, pError : Error, pCallBackName : String) : void{ + // do we have an error handler? + if (Boolean(pTweening.onError) && (pTweening.onError is Function)){ + // yup, there's a handler. Wrap this in a try catch in case the onError throws an error itself. + var eventScope:Object = Boolean(pTweening.onErrorScope) ? pTweening.onErrorScope : pTweening.scope; + try { + pTweening.onError.apply(eventScope, [pTweening.scope, pError]); + } catch (metaError : Error){ + printError(String(pTweening.scope) + " raised an error while executing the 'onError' handler. Original error:\n " + pError.getStackTrace() + "\nonError error: " + metaError.getStackTrace()); + } + } else { + // no handler, simply trace the stack trace: + if (!Boolean(pTweening.onError)){ + printError(String(pTweening.scope) + " raised an error while executing the '" + pCallBackName + "'handler. \n" + pError.getStackTrace() ); + } + } + } + + /** + * Get the current tweening time (no matter if it uses frames or time as basis), given a specific tweening + * + * @param p_tweening TweenListObj Tween information + */ + public static function getCurrentTweeningTime(p_tweening:Object):Number { + return p_tweening.useFrames ? _currentTimeFrame : _currentTime; + } + + /** + * Return the current tweener version + * + * @return String The number of the current Tweener version + */ + public static function getVersion():String { + return "AS3 1.33.74"; + } + + + // ================================================================================================================================== + // DEBUG functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Output an error message + * + * @param p_message String The error message to output + */ + public static function printError(p_message:String): void { + // + trace("## [Tweener] Error: "+p_message); + } + + } +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/ColorShortcuts.as b/docviewerflex.backup/src/caurina/transitions/properties/ColorShortcuts.as new file mode 100644 index 0000000..01e7d74 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/ColorShortcuts.as @@ -0,0 +1,471 @@ +package caurina.transitions.properties { + + /** + * properties.ColorShortcuts + * List of default special color properties (normal and splitter properties) for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.geom.ColorTransform; + import flash.filters.ColorMatrixFilter; + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + public class ColorShortcuts { + + // Sources: + // http://www.graficaobscura.com/matrix/index.html + // And mario Klingemann's ColorMatrix class as mentioned on the credits: + // http://www.quasimondo.com/archives/000565.php + + // Defines luminance using sRGB luminance + private static var LUMINANCE_R:Number = 0.212671; + private static var LUMINANCE_G:Number = 0.715160; + private static var LUMINANCE_B:Number = 0.072169; + + /** + * There's no constructor. + */ + public function ColorShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Normal properties + Tweener.registerSpecialProperty("_color_ra", _oldColor_property_get, _oldColor_property_set, ["redMultiplier"]); + Tweener.registerSpecialProperty("_color_rb", _color_property_get, _color_property_set, ["redOffset"]); + Tweener.registerSpecialProperty("_color_ga", _oldColor_property_get, _oldColor_property_set, ["greenMultiplier"]); + Tweener.registerSpecialProperty("_color_gb", _color_property_get, _color_property_set, ["greenOffset"]); + Tweener.registerSpecialProperty("_color_ba", _oldColor_property_get, _oldColor_property_set, ["blueMultiplier"]); + Tweener.registerSpecialProperty("_color_bb", _color_property_get, _color_property_set, ["blueOffset"]); + Tweener.registerSpecialProperty("_color_aa", _oldColor_property_get, _oldColor_property_set, ["alphaMultiplier"]); + Tweener.registerSpecialProperty("_color_ab", _color_property_get, _color_property_set, ["alphaOffset"]); + + Tweener.registerSpecialProperty("_color_redMultiplier", _color_property_get, _color_property_set, ["redMultiplier"]); + Tweener.registerSpecialProperty("_color_redOffset", _color_property_get, _color_property_set, ["redOffset"]); + Tweener.registerSpecialProperty("_color_greenMultiplier", _color_property_get, _color_property_set, ["greenMultiplier"]); + Tweener.registerSpecialProperty("_color_greenOffset", _color_property_get, _color_property_set, ["greenOffset"]); + Tweener.registerSpecialProperty("_color_blueMultiplier", _color_property_get, _color_property_set, ["blueMultiplier"]); + Tweener.registerSpecialProperty("_color_blueOffset", _color_property_get, _color_property_set, ["blueOffset"]); + Tweener.registerSpecialProperty("_color_alphaMultiplier", _color_property_get, _color_property_set, ["alphaMultiplier"]); + Tweener.registerSpecialProperty("_color_alphaOffset", _color_property_get, _color_property_set, ["alphaOffset"]); + + // Normal splitter properties + Tweener.registerSpecialPropertySplitter("_color", _color_splitter); + Tweener.registerSpecialPropertySplitter("_colorTransform", _colorTransform_splitter); + + // Color changes that depend on the ColorMatrixFilter + Tweener.registerSpecialProperty("_brightness", _brightness_get, _brightness_set, [false]); + Tweener.registerSpecialProperty("_tintBrightness", _brightness_get, _brightness_set, [true]); + Tweener.registerSpecialProperty("_contrast", _contrast_get, _contrast_set); + Tweener.registerSpecialProperty("_hue", _hue_get, _hue_set); + Tweener.registerSpecialProperty("_saturation", _saturation_get, _saturation_set, [false]); + Tweener.registerSpecialProperty("_dumbSaturation", _saturation_get, _saturation_set, [true]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _color + + /** + * Splits the _color parameter into specific color variables + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _color_splitter (p_value:*, p_parameters:Array):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so just resets the color + nArray.push({name:"_color_redMultiplier", value:1}); + nArray.push({name:"_color_redOffset", value:0}); + nArray.push({name:"_color_greenMultiplier", value:1}); + nArray.push({name:"_color_greenOffset", value:0}); + nArray.push({name:"_color_blueMultiplier", value:1}); + nArray.push({name:"_color_blueOffset", value:0}); + } else { + // A color tinting is passed, so converts it to the object values + nArray.push({name:"_color_redMultiplier", value:0}); + nArray.push({name:"_color_redOffset", value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:"_color_greenMultiplier", value:0}); + nArray.push({name:"_color_greenOffset", value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:"_color_blueMultiplier", value:0}); + nArray.push({name:"_color_blueOffset", value:AuxFunctions.numberToB(p_value)}); + } + return nArray; + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _colorTransform + + /** + * Splits the _colorTransform parameter into specific color variables + * + * @param p_value Number The original _colorTransform value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _colorTransform_splitter (p_value:Object, p_parameters:Array):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so just resets the color + nArray.push({name:"_color_redMultiplier", value:1}); + nArray.push({name:"_color_redOffset", value:0}); + nArray.push({name:"_color_greenMultiplier", value:1}); + nArray.push({name:"_color_greenOffset", value:0}); + nArray.push({name:"_color_blueMultiplier", value:1}); + nArray.push({name:"_color_blueOffset", value:0}); + } else { + // A color transformation object is passed, so converts it to the object values + nArray.push({name:"_color_redMultiplier", value:p_value.redMultiplier}); + nArray.push({name:"_color_redOffset", value:p_value.redOffset}); + nArray.push({name:"_color_blueMultiplier", value:p_value.blueMultiplier}); + nArray.push({name:"_color_blueOffset", value:p_value.blueOffset}); + nArray.push({name:"_color_greenMultiplier", value:p_value.greenMultiplier}); + nArray.push({name:"_color_greenOffset", value:p_value.greenOffset}); + nArray.push({name:"_color_alphaMultiplier", value:p_value.alphaMultiplier}); + nArray.push({name:"_color_alphaOffset", value:p_value.alphaOffset}); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _color_* + + /** + * _color_* + * Generic function for the ra/rb/etc components of the deprecated colorTransform object + */ + public static function _oldColor_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.transform.colorTransform[p_parameters[0]] * 100; + } + public static function _oldColor_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var tf:ColorTransform = p_obj.transform.colorTransform; + tf[p_parameters[0]] = p_value / 100; + p_obj.transform.colorTransform = tf; + } + + /** + * _color_* + * Generic function for the redMultiplier/redOffset/etc components of the new colorTransform + */ + public static function _color_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.transform.colorTransform[p_parameters[0]]; + } + public static function _color_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var cfm:ColorTransform = p_obj.transform.colorTransform; + cfm[p_parameters[0]] = p_value; + p_obj.transform.colorTransform = cfm; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // Special coloring + + /** + * _brightness + * Brightness of an object: -1 -> [0] -> +1 + */ + public static function _brightness_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var isTint:Boolean = p_parameters[0]; + + /* + // Using ColorMatrix: + + var mtx:Array = getObjectMatrix(p_obj); + + var mc:Number = 1 - ((mtx[0] + mtx[6] + mtx[12]) / 3); // Brightness as determined by the main channels + var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3; // Brightness as determined by the offset channels + */ + + var cfm:ColorTransform = p_obj.transform.colorTransform; + var mc:Number = 1 - ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3); // Brightness as determined by the main channels + var co:Number = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3; + + if (isTint) { + // Tint style + //return (mc+(co/255))/2; + return co > 0 ? co / 255 : -mc; + } else { + // Native, Flash "Adjust Color" and Photoshop style + return co / 100; + } + } + public static function _brightness_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + //var mtx:Array = getObjectMatrix(p_obj); + + var isTint:Boolean = p_parameters[0]; + + var mc:Number; // Main channel + var co:Number; // Channel offset + + if (isTint) { + // Tint style + mc = 1 - Math.abs(p_value); + co = p_value > 0 ? Math.round(p_value*255) : 0; + } else { + // Native, Flash "Adjust Color" and Photoshop style + mc = 1; + co = Math.round(p_value*100); + } + + /* + // Using ColorMatrix: + var mtx:Array = [ + mc, cc, cc, cc, co, + cc, mc, cc, cc, co, + cc, cc, mc, cc, co, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + */ + var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); + p_obj.transform.colorTransform = cfm; + } + + /** + * _saturation + * Saturation of an object: 0 -> [1] -> 2 + */ + public static function _saturation_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var mtx:Array = getObjectMatrix(p_obj); + + var isDumb:Boolean = p_parameters[0]; + var rl:Number = isDumb ? 1/3 : LUMINANCE_R; + var gl:Number = isDumb ? 1/3 : LUMINANCE_G; + var bl:Number = isDumb ? 1/3 : LUMINANCE_B; + + var mc:Number = ((mtx[0]-rl)/(1-rl) + (mtx[6]-gl)/(1-gl) + (mtx[12]-bl)/(1-bl)) / 3; // Color saturation as determined by the main channels + var cc:Number = 1 - ((mtx[1]/gl + mtx[2]/bl + mtx[5]/rl + mtx[7]/bl + mtx[10]/rl + mtx[11]/gl) / 6); // Color saturation as determined by the other channels + return (mc + cc) / 2; + } + public static function _saturation_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + + var isDumb:Boolean = p_parameters[0]; + var rl:Number = isDumb ? 1/3 : LUMINANCE_R; + var gl:Number = isDumb ? 1/3 : LUMINANCE_G; + var bl:Number = isDumb ? 1/3 : LUMINANCE_B; + + var sf:Number = p_value; + var nf:Number = 1-sf; + var nr:Number = rl * nf; + var ng:Number = gl * nf; + var nb:Number = bl * nf; + + var mtx:Array = [ + nr+sf, ng, nb, 0, 0, + nr, ng+sf, nb, 0, 0, + nr, ng, nb+sf, 0, 0, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + } + + /** + * _contrast + * Contrast of an object: -1 -> [0] -> +1 + */ + public static function _contrast_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + /* + // Using ColorMatrix: + var mtx:Array = getObjectMatrix(p_obj); + + var mc:Number = ((mtx[0] + mtx[6] + mtx[12]) / 3) - 1; // Contrast as determined by the main channels + var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3 / -128; // Contrast as determined by the offset channel + */ + var cfm:ColorTransform = p_obj.transform.colorTransform; + var mc:Number; // Contrast as determined by the main channels + var co:Number; // Contrast as determined by the offset channel + mc = ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3) - 1; + co = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3 / -128; + /* + if (cfm.ra < 100) { + // Low contrast + mc = ((cfm.ra + cfm.ga + cfm.ba) / 300) - 1; + co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -128; + } else { + // High contrast + mc = (((cfm.ra + cfm.ga + cfm.ba) / 300) - 1) / 37; + co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -3840; + } + */ + + return (mc+co)/2; + } + public static function _contrast_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + + var mc:Number; // Main channel + var co:Number; // Channel offset + mc = p_value + 1; + co = Math.round(p_value*-128); + + /* + if (p_value < 0) { + // Low contrast + mc = p_value + 1; + co = Math.round(p_value*-128); + } else { + // High contrast + mc = (p_value * 37) + 1; + co = Math.round(p_value*-3840); + } + */ + + // Flash: * 8, * -512 + + /* + // Using ColorMatrix: + var mtx:Array = [ + mc, 0, 0, 0, co, + 0, mc, 0, 0, co, + 0, 0, mc, 0, co, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + */ + var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); + p_obj.transform.colorTransform = cfm; + } + + /** + * _hue + * Hue of an object: -180 -> [0] -> 180 + */ + public static function _hue_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var mtx:Array = getObjectMatrix(p_obj); + + // Find the current Hue based on a given matrix. + // This is a kind of a brute force method by sucessive division until a close enough angle is found. + // Reverse-engineering the hue equation would be is a better choice, but it's hard to find material + // on the correct calculation employed by Flash. + // This code has to run only once (before the tween starts), so it's good enough. + + var hues:Array = []; + var i:Number; + + hues[0] = {angle:-179.9, matrix:getHueMatrix(-179.9)}; + hues[1] = {angle:180, matrix:getHueMatrix(180)}; + + for (i = 0; i < hues.length; i++) { + hues[i].distance = getHueDistance(mtx, hues[i].matrix); + } + + var maxTries:Number = 15; // Number o maximum divisions until the hue is found + var angleToSplit:Number; + + for (i = 0; i < maxTries; i++) { + // Find the nearest angle + if (hues[0].distance < hues[1].distance) { + // First is closer + angleToSplit = 1; + } else { + // Second is closer + angleToSplit = 0; + } + hues[angleToSplit].angle = (hues[0].angle + hues[1].angle)/2; + hues[angleToSplit].matrix = getHueMatrix(hues[angleToSplit].angle) + hues[angleToSplit].distance = getHueDistance(mtx, hues[angleToSplit].matrix); + } + + return hues[angleToSplit].angle; + } + + public static function _hue_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + setObjectMatrix(p_obj, getHueMatrix(p_value)); + } + + public static function getHueDistance (mtx1:Array, mtx2:Array): Number { + return (Math.abs(mtx1[0] - mtx2[0]) + Math.abs(mtx1[1] - mtx2[1]) + Math.abs(mtx1[2] - mtx2[2])); + } + + public static function getHueMatrix (hue:Number): Array { + var ha:Number = hue * Math.PI/180; // Hue angle, to radians + + var rl:Number = LUMINANCE_R; + var gl:Number = LUMINANCE_G; + var bl:Number = LUMINANCE_B; + + var c:Number = Math.cos(ha); + var s:Number = Math.sin(ha); + + var mtx:Array = [ + (rl + (c * (1 - rl))) + (s * (-rl)), + (gl + (c * (-gl))) + (s * (-gl)), + (bl + (c * (-bl))) + (s * (1 - bl)), + 0, 0, + + (rl + (c * (-rl))) + (s * 0.143), + (gl + (c * (1 - gl))) + (s * 0.14), + (bl + (c * (-bl))) + (s * -0.283), + 0, 0, + + (rl + (c * (-rl))) + (s * (-(1 - rl))), + (gl + (c * (-gl))) + (s * gl), + (bl + (c * (1 - bl))) + (s * bl), + 0, 0, + + 0, 0, 0, 1, 0 + ]; + + return mtx; + } + + + // ================================================================================================================================== + // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- + + private static function getObjectMatrix(p_obj:Object): Array { + // Get the current color matrix of an object + for (var i:Number = 0; i < p_obj.filters.length; i++) { + if (p_obj.filters[i] is ColorMatrixFilter) { + return p_obj.filters[i].matrix.concat(); + } + } + return [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 + ]; + } + + private static function setObjectMatrix(p_obj:Object, p_matrix:Array): void { + // Set the current color matrix of an object + var objFilters:Array = p_obj.filters.concat(); + var found:Boolean = false; + for (var i:Number = 0; i < objFilters.length; i++) { + if (objFilters[i] is ColorMatrixFilter) { + objFilters[i].matrix = p_matrix.concat(); + found = true; + } + } + if (!found) { + // Has to create a new color matrix filter + var cmtx:ColorMatrixFilter = new ColorMatrixFilter(p_matrix); + objFilters[objFilters.length] = cmtx; + } + p_obj.filters = objFilters; + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/CurveModifiers.as b/docviewerflex.backup/src/caurina/transitions/properties/CurveModifiers.as new file mode 100644 index 0000000..b004c1f --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/CurveModifiers.as @@ -0,0 +1,109 @@ +package caurina.transitions.properties { + + /** + * properties.CurveModifiers + * List of default special properties modifiers for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import caurina.transitions.Tweener; + + public class CurveModifiers { + + /** + * There's no constructor. + */ + public function CurveModifiers () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Bezier modifiers + Tweener.registerSpecialPropertyModifier("_bezier", _bezier_modifier, _bezier_get); + } + + + // ================================================================================================================================== + // SPECIAL PROPERTY MODIFIER functions ---------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _bezier + + /** + * Given the parameter object passed to this special property, return an array listing the properties that should be modified, and their parameters + * + * @param p_obj Object Parameter passed to this property + * @return Array Array listing name and parameter of each property + */ + public static function _bezier_modifier (p_obj:*):Array { + var mList:Array = []; // List of properties to be modified + var pList:Array; // List of parameters passed, normalized as an array + if (p_obj is Array) { + // Complex + pList = p_obj; + } else { + pList = [p_obj]; + } + + var i:uint; + var istr:String; + var mListObj:Object = {}; // Object describing each property name and parameter + + for (i = 0; i < pList.length; i++) { + for (istr in pList[i]) { + if (mListObj[istr] == undefined) mListObj[istr] = []; + mListObj[istr].push(pList[i][istr]); + } + } + for (istr in mListObj) { + mList.push({name:istr, parameters:mListObj[istr]}); + } + return mList; + } + + /** + * Given tweening specifications (beging, end, t), applies the property parameter to it, returning new t + * + * @param b Number Beginning value of the property + * @param e Number Ending (desired) value of the property + * @param t Number Current t of this tweening (0-1), after applying the easing equation + * @param p Array Array of parameters passed to this specific property + * @return Number New t, with the p parameters applied to it + */ + public static function _bezier_get (b:Number, e:Number, t:Number, p:Array):Number { + // This is based on Robert Penner's code + if (p.length == 1) { + // Simple curve with just one bezier control point + return b + t*(2*(1-t)*(p[0]-b) + t*(e - b)); + } else { + // Array of bezier control points, must find the point between each pair of bezier points + var ip:uint = Math.floor(t * p.length); // Position on the bezier list + var it:Number = (t - (ip * (1 / p.length))) * p.length; // t inside this ip + var p1:Number, p2:Number; + if (ip == 0) { + // First part: belongs to the first control point, find second midpoint + p1 = b; + p2 = (p[0]+p[1])/2; + } else if (ip == p.length - 1) { + // Last part: belongs to the last control point, find first midpoint + p1 = (p[ip-1]+p[ip])/2; + p2 = e; + } else { + // Any middle part: find both midpoints + p1 = (p[ip-1]+p[ip])/2; + p2 = (p[ip]+p[ip+1])/2; + } + return p1+it*(2*(1-it)*(p[ip]-p1) + it*(p2 - p1)); + } + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/DisplayShortcuts.as b/docviewerflex.backup/src/caurina/transitions/properties/DisplayShortcuts.as new file mode 100644 index 0000000..fff4568 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/DisplayShortcuts.as @@ -0,0 +1,161 @@ +package caurina.transitions.properties { + + /** + * properties.DisplayShortcuts.as + * List of default special MovieClip properties (normal and splitter properties) for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.geom.Point; + import flash.geom.Rectangle; + + import caurina.transitions.Tweener; + + public class DisplayShortcuts { + + /** + * There's no constructor. + */ + public function DisplayShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Normal properties + Tweener.registerSpecialProperty("_frame", _frame_get, _frame_set); + Tweener.registerSpecialProperty("_autoAlpha", _autoAlpha_get, _autoAlpha_set); + + // Scale splitter properties + Tweener.registerSpecialPropertySplitter("_scale", _scale_splitter); + + // scrollRect splitter properties + Tweener.registerSpecialPropertySplitter("_scrollRect", _scrollRect_splitter); + + // scrollrect normal properties + Tweener.registerSpecialProperty("_scrollRect_x", _scrollRect_property_get, _scrollRect_property_set, ["x"]); + Tweener.registerSpecialProperty("_scrollRect_y", _scrollRect_property_get, _scrollRect_property_set, ["y"]); + Tweener.registerSpecialProperty("_scrollRect_left", _scrollRect_property_get, _scrollRect_property_set, ["left"]); + Tweener.registerSpecialProperty("_scrollRect_right", _scrollRect_property_get, _scrollRect_property_set, ["right"]); + Tweener.registerSpecialProperty("_scrollRect_top", _scrollRect_property_get, _scrollRect_property_set, ["top"]); + Tweener.registerSpecialProperty("_scrollRect_bottom", _scrollRect_property_get, _scrollRect_property_set, ["bottom"]); + Tweener.registerSpecialProperty("_scrollRect_width", _scrollRect_property_get, _scrollRect_property_set, ["width"]); + Tweener.registerSpecialProperty("_scrollRect_height", _scrollRect_property_get, _scrollRect_property_set, ["height"]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // scale + public static function _scale_splitter(p_value:Number, p_parameters:Array) : Array{ + var nArray:Array = new Array(); + nArray.push({name:"scaleX", value: p_value}); + nArray.push({name:"scaleY", value: p_value}); + return nArray; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _scrollRect + + /** + * Splits the _scrollRect parameter into specific scrollRect variables + * + * @param p_value Rectangle The original _scrollRect rectangle + * @return Array An array containing the .name and .value of all new properties + */ + public static function _scrollRect_splitter (p_value:Rectangle, p_parameters:Array, p_extra:Object = null):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so try any rectangle :/ + nArray.push({name:"_scrollRect_x", value:0}); + nArray.push({name:"_scrollRect_y", value:0}); + nArray.push({name:"_scrollRect_width", value:100}); + nArray.push({name:"_scrollRect_height", value:100}); + } else { + // A rectangle is passed, so just return the properties + nArray.push({name:"_scrollRect_x", value:p_value.x}); + nArray.push({name:"_scrollRect_y", value:p_value.y}); + nArray.push({name:"_scrollRect_width", value:p_value.width}); + nArray.push({name:"_scrollRect_height", value:p_value.height}); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _frame + + /** + * Returns the current frame number from the movieclip timeline + * + * @param p_obj Object MovieClip object + * @return Number The current frame + */ + public static function _frame_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.currentFrame; + } + + /** + * Sets the timeline frame + * + * @param p_obj Object MovieClip object + * @param p_value Number New frame number + */ + public static function _frame_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + p_obj.gotoAndStop(Math.round(p_value)); + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _autoAlpha + + /** + * Returns the current alpha + * + * @param p_obj Object MovieClip or Textfield object + * @return Number The current alpha + */ + public static function _autoAlpha_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.alpha; + } + + /** + * Sets the current autoAlpha + * + * @param p_obj Object MovieClip or Textfield object + * @param p_value Number New alpha + */ + public static function _autoAlpha_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + p_obj.alpha = p_value; + p_obj.visible = p_value > 0; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _scrollRect_* + + /** + * _scrollRect_* + * Generic function for the properties of the scrollRect object + */ + public static function _scrollRect_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.scrollRect[p_parameters[0]]; + } + public static function _scrollRect_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var rect:Rectangle = p_obj.scrollRect; + rect[p_parameters[0]] = Math.round(p_value); + p_obj.scrollRect = rect; + } + } +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/FilterShortcuts.as b/docviewerflex.backup/src/caurina/transitions/properties/FilterShortcuts.as new file mode 100644 index 0000000..932393a --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/FilterShortcuts.as @@ -0,0 +1,520 @@ +package caurina.transitions.properties { + + /** + * properties.FilterShortcuts + * Special properties for the Tweener class to handle MovieClip filters + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.display.BitmapData; + import flash.filters.BevelFilter; + import flash.filters.BitmapFilter; + import flash.filters.BlurFilter; + import flash.filters.ColorMatrixFilter; + import flash.filters.ConvolutionFilter; + import flash.filters.DisplacementMapFilter; + import flash.filters.DropShadowFilter; + import flash.filters.GlowFilter; + import flash.filters.GradientBevelFilter; + import flash.filters.GradientGlowFilter; + import flash.geom.Point; + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + public class FilterShortcuts { + + /** + * There's no constructor. + */ + public function FilterShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Filter tweening splitter properties + Tweener.registerSpecialPropertySplitter("_filter", _filter_splitter); + + // Shortcuts - BevelFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/BevelFilter.html + Tweener.registerSpecialProperty("_Bevel_angle", _filter_property_get, _filter_property_set, [BevelFilter, "angle"]); + Tweener.registerSpecialProperty("_Bevel_blurX", _filter_property_get, _filter_property_set, [BevelFilter, "blurX"]); + Tweener.registerSpecialProperty("_Bevel_blurY", _filter_property_get, _filter_property_set, [BevelFilter, "blurY"]); + Tweener.registerSpecialProperty("_Bevel_distance", _filter_property_get, _filter_property_set, [BevelFilter, "distance"]); + Tweener.registerSpecialProperty("_Bevel_highlightAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "highlightAlpha"]); + Tweener.registerSpecialPropertySplitter("_Bevel_highlightColor", _generic_color_splitter, ["_Bevel_highlightColor_r", "_Bevel_highlightColor_g", "_Bevel_highlightColor_b"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "r"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "g"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "b"]); + Tweener.registerSpecialProperty("_Bevel_knockout", _filter_property_get, _filter_property_set, [BevelFilter, "knockout"]); + Tweener.registerSpecialProperty("_Bevel_quality", _filter_property_get, _filter_property_set, [BevelFilter, "quality"]); + Tweener.registerSpecialProperty("_Bevel_shadowAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "shadowAlpha"]); + Tweener.registerSpecialPropertySplitter("_Bevel_shadowColor", _generic_color_splitter, ["_Bevel_shadowColor_r", "_Bevel_shadowColor_g", "_Bevel_shadowColor_b"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "r"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "g"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "b"]); + Tweener.registerSpecialProperty("_Bevel_strength", _filter_property_get, _filter_property_set, [BevelFilter, "strength"]); + Tweener.registerSpecialProperty("_Bevel_type", _filter_property_get, _filter_property_set, [BevelFilter, "type"]); + + // Shortcuts - BlurFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/BlurFilter.html + Tweener.registerSpecialProperty("_Blur_blurX", _filter_property_get, _filter_property_set, [BlurFilter, "blurX"]); + Tweener.registerSpecialProperty("_Blur_blurY", _filter_property_get, _filter_property_set, [BlurFilter, "blurY"]); + Tweener.registerSpecialProperty("_Blur_quality", _filter_property_get, _filter_property_set, [BlurFilter, "quality"]); + + // Shortcuts - ColorMatrixFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/ColorMatrixFilter.html + Tweener.registerSpecialPropertySplitter("_ColorMatrix_matrix", _generic_matrix_splitter, [[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], + ["_ColorMatrix_matrix_rr", "_ColorMatrix_matrix_rg", "_ColorMatrix_matrix_rb", "_ColorMatrix_matrix_ra", "_ColorMatrix_matrix_ro", + "_ColorMatrix_matrix_gr", "_ColorMatrix_matrix_gg", "_ColorMatrix_matrix_gb", "_ColorMatrix_matrix_ga", "_ColorMatrix_matrix_go", + "_ColorMatrix_matrix_br", "_ColorMatrix_matrix_bg", "_ColorMatrix_matrix_bb", "_ColorMatrix_matrix_ba", "_ColorMatrix_matrix_bo", + "_ColorMatrix_matrix_ar", "_ColorMatrix_matrix_ag", "_ColorMatrix_matrix_ab", "_ColorMatrix_matrix_aa", "_ColorMatrix_matrix_ao"]]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 0]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 1]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 2]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ra", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 3]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ro", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 4]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 5]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 6]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 7]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ga", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 8]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_go", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 9]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_br", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 10]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 11]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 12]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ba", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 13]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bo", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 14]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ar", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 15]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ag", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 16]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ab", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 17]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_aa", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 18]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ao", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 19]); + + // Shortcuts - ConvolutionFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/ConvolutionFilter.html + Tweener.registerSpecialProperty("_Convolution_alpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "alpha"]); + Tweener.registerSpecialProperty("_Convolution_bias", _filter_property_get, _filter_property_set, [ConvolutionFilter, "bias"]); + Tweener.registerSpecialProperty("_Convolution_clamp", _filter_property_get, _filter_property_set, [ConvolutionFilter, "clamp"]); + Tweener.registerSpecialPropertySplitter("_Convolution_color", _generic_color_splitter, ["_Convolution_color_r", "_Convolution_color_g", "_Convolution_color_b"]); + Tweener.registerSpecialProperty("_Convolution_color_r", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_Convolution_color_g", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_Convolution_color_b", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_Convolution_divisor", _filter_property_get, _filter_property_set, [ConvolutionFilter, "divisor"]); + //Tweener.registerSpecialPropertySplitter("_Convolution_matrix", _generic_array_splitter, ["_Convolution_matrix_array"]); + //Tweener.registerSpecialProperty("_Convolution_matrix_array", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrix", "array"]); + Tweener.registerSpecialProperty("_Convolution_matrixX", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixX"]); + Tweener.registerSpecialProperty("_Convolution_matrixY", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixY"]); + Tweener.registerSpecialProperty("_Convolution_preserveAlpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "preserveAlpha"]); + + // Shortcuts - DisplacementMapFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/DisplacementMapFilter.html + Tweener.registerSpecialProperty("_DisplacementMap_alpha", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "alpha"]); + Tweener.registerSpecialPropertySplitter("_DisplacementMap_color", _generic_color_splitter, ["_DisplacementMap_color_r", "_DisplacementMap_color_r", "_DisplacementMap_color_r"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_r", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_g", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_b", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_DisplacementMap_componentX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentX"]); + Tweener.registerSpecialProperty("_DisplacementMap_componentY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentY"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapBitmap", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapBitmap"]); + Tweener.registerSpecialPropertySplitter("_DisplacementMap_mapPoint",_generic_point_splitter, ["_DisplacementMap_mapPoint_x", "_DisplacementMap_mapPoint_y"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_x", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "x"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_y", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "y"]); + Tweener.registerSpecialProperty("_DisplacementMap_mode", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mode"]); + Tweener.registerSpecialProperty("_DisplacementMap_scaleX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleX"]); + Tweener.registerSpecialProperty("_DisplacementMap_scaleY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleY"]); + + // Shortcuts - DropShadowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/DropShadowFilter.html + Tweener.registerSpecialProperty("_DropShadow_alpha", _filter_property_get, _filter_property_set, [DropShadowFilter, "alpha"]); + Tweener.registerSpecialProperty("_DropShadow_angle", _filter_property_get, _filter_property_set, [DropShadowFilter, "angle"]); + Tweener.registerSpecialProperty("_DropShadow_blurX", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurX"]); + Tweener.registerSpecialProperty("_DropShadow_blurY", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurY"]); + Tweener.registerSpecialPropertySplitter("_DropShadow_color", _generic_color_splitter, ["_DropShadow_color_r", "_DropShadow_color_g", "_DropShadow_color_b"]); + Tweener.registerSpecialProperty("_DropShadow_color_r", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_DropShadow_color_g", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_DropShadow_color_b", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_DropShadow_distance", _filter_property_get, _filter_property_set, [DropShadowFilter, "distance"]); + Tweener.registerSpecialProperty("_DropShadow_hideObject", _filter_property_get, _filter_property_set, [DropShadowFilter, "hideObject"]); + Tweener.registerSpecialProperty("_DropShadow_inner", _filter_property_get, _filter_property_set, [DropShadowFilter, "inner"]); + Tweener.registerSpecialProperty("_DropShadow_knockout", _filter_property_get, _filter_property_set, [DropShadowFilter, "knockout"]); + Tweener.registerSpecialProperty("_DropShadow_quality", _filter_property_get, _filter_property_set, [DropShadowFilter, "quality"]); + Tweener.registerSpecialProperty("_DropShadow_strength", _filter_property_get, _filter_property_set, [DropShadowFilter, "strength"]); + + // Shortcuts - GlowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GlowFilter.html + Tweener.registerSpecialProperty("_Glow_alpha", _filter_property_get, _filter_property_set, [GlowFilter, "alpha"]); + Tweener.registerSpecialProperty("_Glow_blurX", _filter_property_get, _filter_property_set, [GlowFilter, "blurX"]); + Tweener.registerSpecialProperty("_Glow_blurY", _filter_property_get, _filter_property_set, [GlowFilter, "blurY"]); + Tweener.registerSpecialPropertySplitter("_Glow_color", _generic_color_splitter, ["_Glow_color_r", "_Glow_color_g", "_Glow_color_b"]); + Tweener.registerSpecialProperty("_Glow_color_r", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_Glow_color_g", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_Glow_color_b", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_Glow_inner", _filter_property_get, _filter_property_set, [GlowFilter, "inner"]); + Tweener.registerSpecialProperty("_Glow_knockout", _filter_property_get, _filter_property_set, [GlowFilter, "knockout"]); + Tweener.registerSpecialProperty("_Glow_quality", _filter_property_get, _filter_property_set, [GlowFilter, "quality"]); + Tweener.registerSpecialProperty("_Glow_strength", _filter_property_get, _filter_property_set, [GlowFilter, "strength"]); + + // Shortcuts - GradientBevelFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientBevelFilter.html + // .alphas (array) + Tweener.registerSpecialProperty("_GradientBevel_angle", _filter_property_get, _filter_property_set, [GradientBevelFilter, "angle"]); + Tweener.registerSpecialProperty("_GradientBevel_blurX", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurX"]); + Tweener.registerSpecialProperty("_GradientBevel_blurY", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurY"]); + // .colors (array) + Tweener.registerSpecialProperty("_GradientBevel_distance", _filter_property_get, _filter_property_set, [GradientBevelFilter, "distance"]); + Tweener.registerSpecialProperty("_GradientBevel_quality", _filter_property_get, _filter_property_set, [GradientBevelFilter, "quality"]); + // .ratios(array) + Tweener.registerSpecialProperty("_GradientBevel_strength", _filter_property_get, _filter_property_set, [GradientBevelFilter, "strength"]); + Tweener.registerSpecialProperty("_GradientBevel_type", _filter_property_get, _filter_property_set, [GradientBevelFilter, "type"]); + + // Shortcuts - GradientGlowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientGlowFilter.html + // .alphas (array) + Tweener.registerSpecialProperty("_GradientGlow_angle", _filter_property_get, _filter_property_set, [GradientGlowFilter, "angle"]); + Tweener.registerSpecialProperty("_GradientGlow_blurX", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurX"]); + Tweener.registerSpecialProperty("_GradientGlow_blurY", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurY"]); + // .colors (array) + Tweener.registerSpecialProperty("_GradientGlow_distance", _filter_property_get, _filter_property_set, [GradientGlowFilter, "distance"]); + Tweener.registerSpecialProperty("_GradientGlow_knockout", _filter_property_get, _filter_property_set, [GradientGlowFilter, "knockout"]); + Tweener.registerSpecialProperty("_GradientGlow_quality", _filter_property_get, _filter_property_set, [GradientGlowFilter, "quality"]); + // .ratios (array) + Tweener.registerSpecialProperty("_GradientGlow_strength", _filter_property_get, _filter_property_set, [GradientGlowFilter, "strength"]); + Tweener.registerSpecialProperty("_GradientGlow_type", _filter_property_get, _filter_property_set, [GradientGlowFilter, "type"]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // generic splitters + + /** + * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); + return nArray; + } + + /** + * A generic mapPoint splitter - from Point to x, y with the name of the parameters passed + * + * @param p_value Point The original point + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_point_splitter (p_value:Point, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:p_value.x}); + nArray.push({name:p_parameters[1], value:p_value.y}); + return nArray; + } + + /** + * A generic matrix splitter - from [] to items with the name of the parameters passed + * + * @param p_value Array The original matrix + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_matrix_splitter (p_value:Array, p_parameters:Array):Array { + if (p_value == null) p_value = p_parameters[0].concat(); + var nArray:Array = new Array(); + for (var i:Number = 0; i < p_value.length; i++) { + nArray.push({name:p_parameters[1][i], value:p_value[i]}); + } + return nArray; + } + + /** + * A generic array splitter - from [] to items with the index passed back + * + * @param p_value Array The original array value + * @return Array An array containing the .name and .value of all new properties + */ + /* + public static function _generic_array_splitter (p_value:Array, p_parameters:Array):Array { + if (p_value == null) p_value = p_parameters[0].concat(); + var nArray:Array = new Array(); + for (var i:Number = 0; i < p_value.length; i++) { + nArray.push({name:p_parameters[1][i], value:p_value[i], arrayIndex:i}); + } + return nArray; + } + */ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // filters + + /** + * Splits the _filter, _blur, etc parameter into specific filter variables + * + * @param p_value BitmapFilter A BitmapFilter instance + * @return Array An array containing the .name and .value of all new properties + */ + public static function _filter_splitter (p_value:BitmapFilter, p_parameters:Array, p_extra:Object = null):Array { + var nArray:Array = new Array(); + if (p_value is BevelFilter) { + nArray.push({name:"_Bevel_angle", value:BevelFilter(p_value).angle}); + nArray.push({name:"_Bevel_blurX", value:BevelFilter(p_value).blurX}); + nArray.push({name:"_Bevel_blurY", value:BevelFilter(p_value).blurY}); + nArray.push({name:"_Bevel_distance", value:BevelFilter(p_value).distance}); + nArray.push({name:"_Bevel_highlightAlpha", value:BevelFilter(p_value).highlightAlpha}); + nArray.push({name:"_Bevel_highlightColor", value:BevelFilter(p_value).highlightColor}); + nArray.push({name:"_Bevel_knockout", value:BevelFilter(p_value).knockout}); + nArray.push({name:"_Bevel_quality", value:BevelFilter(p_value).quality}); + nArray.push({name:"_Bevel_shadowAlpha", value:BevelFilter(p_value).shadowAlpha}); + nArray.push({name:"_Bevel_shadowColor", value:BevelFilter(p_value).shadowColor}); + nArray.push({name:"_Bevel_strength", value:BevelFilter(p_value).strength}); + nArray.push({name:"_Bevel_type", value:BevelFilter(p_value).type}); + } else if (p_value is BlurFilter) { + nArray.push({name:"_Blur_blurX", value:BlurFilter(p_value).blurX}); + nArray.push({name:"_Blur_blurY", value:BlurFilter(p_value).blurY}); + nArray.push({name:"_Blur_quality", value:BlurFilter(p_value).quality}); + } else if (p_value is ColorMatrixFilter) { + nArray.push({name:"_ColorMatrix_matrix", value:ColorMatrixFilter(p_value).matrix}); + } else if (p_value is ConvolutionFilter) { + nArray.push({name:"_Convolution_alpha", value:ConvolutionFilter(p_value).alpha}); + nArray.push({name:"_Convolution_bias", value:ConvolutionFilter(p_value).bias}); + nArray.push({name:"_Convolution_clamp", value:ConvolutionFilter(p_value).clamp}); + nArray.push({name:"_Convolution_color", value:ConvolutionFilter(p_value).color}); + // .matrix + nArray.push({name:"_Convolution_divisor", value:ConvolutionFilter(p_value).divisor}); + nArray.push({name:"_Convolution_matrixX", value:ConvolutionFilter(p_value).matrixX}); + nArray.push({name:"_Convolution_matrixY", value:ConvolutionFilter(p_value).matrixY}); + nArray.push({name:"_Convolution_preserveAlpha", value:ConvolutionFilter(p_value).preserveAlpha}); + } else if (p_value is DisplacementMapFilter) { + nArray.push({name:"_DisplacementMap_alpha", value:DisplacementMapFilter(p_value).alpha}); + nArray.push({name:"_DisplacementMap_color", value:DisplacementMapFilter(p_value).color}); + nArray.push({name:"_DisplacementMap_componentX", value:DisplacementMapFilter(p_value).componentX}); + nArray.push({name:"_DisplacementMap_componentY", value:DisplacementMapFilter(p_value).componentY}); + nArray.push({name:"_DisplacementMap_mapBitmap", value:DisplacementMapFilter(p_value).mapBitmap}); + nArray.push({name:"_DisplacementMap_mapPoint", value:DisplacementMapFilter(p_value).mapPoint}); + nArray.push({name:"_DisplacementMap_mode", value:DisplacementMapFilter(p_value).mode}); + nArray.push({name:"_DisplacementMap_scaleX", value:DisplacementMapFilter(p_value).scaleX}); + nArray.push({name:"_DisplacementMap_scaleY", value:DisplacementMapFilter(p_value).scaleY}); + } else if (p_value is DropShadowFilter) { + nArray.push({name:"_DropShadow_alpha", value:DropShadowFilter(p_value).alpha}); + nArray.push({name:"_DropShadow_angle", value:DropShadowFilter(p_value).angle}); + nArray.push({name:"_DropShadow_blurX", value:DropShadowFilter(p_value).blurX}); + nArray.push({name:"_DropShadow_blurY", value:DropShadowFilter(p_value).blurY}); + nArray.push({name:"_DropShadow_color", value:DropShadowFilter(p_value).color}); + nArray.push({name:"_DropShadow_distance", value:DropShadowFilter(p_value).distance}); + nArray.push({name:"_DropShadow_hideObject", value:DropShadowFilter(p_value).hideObject}); + nArray.push({name:"_DropShadow_inner", value:DropShadowFilter(p_value).inner}); + nArray.push({name:"_DropShadow_knockout", value:DropShadowFilter(p_value).knockout}); + nArray.push({name:"_DropShadow_quality", value:DropShadowFilter(p_value).quality}); + nArray.push({name:"_DropShadow_strength", value:DropShadowFilter(p_value).strength}); + } else if (p_value is GlowFilter) { + nArray.push({name:"_Glow_alpha", value:GlowFilter(p_value).alpha}); + nArray.push({name:"_Glow_blurX", value:GlowFilter(p_value).blurX}); + nArray.push({name:"_Glow_blurY", value:GlowFilter(p_value).blurY}); + nArray.push({name:"_Glow_color", value:GlowFilter(p_value).color}); + nArray.push({name:"_Glow_inner", value:GlowFilter(p_value).inner}); + nArray.push({name:"_Glow_knockout", value:GlowFilter(p_value).knockout}); + nArray.push({name:"_Glow_quality", value:GlowFilter(p_value).quality}); + nArray.push({name:"_Glow_strength", value:GlowFilter(p_value).strength}); + } else if (p_value is GradientBevelFilter) { + // .alphas (array) + nArray.push({name:"_GradientBevel_angle", value:GradientBevelFilter(p_value).strength}); + nArray.push({name:"_GradientBevel_blurX", value:GradientBevelFilter(p_value).blurX}); + nArray.push({name:"_GradientBevel_blurY", value:GradientBevelFilter(p_value).blurY}); + // .colors (array) + nArray.push({name:"_GradientBevel_distance", value:GradientBevelFilter(p_value).distance}); + nArray.push({name:"_GradientBevel_quality", value:GradientBevelFilter(p_value).quality}); + // .ratios(array) + nArray.push({name:"_GradientBevel_strength", value:GradientBevelFilter(p_value).strength}); + nArray.push({name:"_GradientBevel_type", value:GradientBevelFilter(p_value).type}); + } else if (p_value is GradientGlowFilter) { + // .alphas (array) + nArray.push({name:"_GradientGlow_angle", value:GradientGlowFilter(p_value).strength}); + nArray.push({name:"_GradientGlow_blurX", value:GradientGlowFilter(p_value).blurX}); + nArray.push({name:"_GradientGlow_blurY", value:GradientGlowFilter(p_value).blurY}); + // .colors (array) + nArray.push({name:"_GradientGlow_distance", value:GradientGlowFilter(p_value).distance}); + nArray.push({name:"_GradientGlow_knockout", value:GradientGlowFilter(p_value).knockout}); + nArray.push({name:"_GradientGlow_quality", value:GradientGlowFilter(p_value).quality}); + // .ratios(array) + nArray.push({name:"_GradientGlow_strength", value:GradientGlowFilter(p_value).strength}); + nArray.push({name:"_GradientGlow_type", value:GradientGlowFilter(p_value).type}); + } else { + // ? + trace ("Tweener FilterShortcuts Error :: Unknown filter class used"); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // filters + + /** + * (filters) + * Generic function for the properties of filter objects + */ + public static function _filter_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + var f:Array = p_obj.filters; + var i:Number; + var filterClass:Object = p_parameters[0]; + var propertyName:String = p_parameters[1]; + var splitType:String = p_parameters[2]; + for (i = 0; i < f.length; i++) { + if (f[i] is Class(filterClass)) { + if (splitType == "color") { + // Composite, color channel + var colorComponent:String = p_parameters[3]; + if (colorComponent == "r") return AuxFunctions.numberToR(f[i][propertyName]); + if (colorComponent == "g") return AuxFunctions.numberToG(f[i][propertyName]); + if (colorComponent == "b") return AuxFunctions.numberToB(f[i][propertyName]); + } else if (splitType == "matrix") { + // Composite, some kind of matrix + return f[i][propertyName][p_parameters[3]]; + } else if (splitType == "point") { + // Composite, a point + return f[i][propertyName][p_parameters[3]]; + } else { + // Standard property + return (f[i][propertyName]); + } + } + } + + // No value found for this property - no filter instance found using this class! + // Must return default desired values + var defaultValues:Object; + switch (filterClass) { + case BevelFilter: + defaultValues = {angle:NaN, blurX:0, blurY:0, distance:0, highlightAlpha:1, highlightColor:NaN, knockout:null, quality:NaN, shadowAlpha:1, shadowColor:NaN, strength:2, type:null}; + break; + case BlurFilter: + defaultValues = {blurX:0, blurY:0, quality:NaN}; + break; + case ColorMatrixFilter: + defaultValues = {matrix:[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]}; + break; + case ConvolutionFilter: + defaultValues = {alpha:0, bias:0, clamp:null, color:NaN, divisor:1, matrix:[1], matrixX:1, matrixY:1, preserveAlpha:null}; + break; + case DisplacementMapFilter: + defaultValues = {alpha:0, color:NaN, componentX:null, componentY:null, mapBitmap:null, mapPoint:null, mode:null, scaleX:0, scaleY:0}; + break; + case DropShadowFilter: + defaultValues = {distance:0, angle:NaN, color:NaN, alpha:1, blurX:0, blurY:0, strength:1, quality:NaN, inner:null, knockout:null, hideObject:null}; + break; + case GlowFilter: + defaultValues = {alpha:1, blurX:0, blurY:0, color:NaN, inner:null, knockout:null, quality:NaN, strength:2}; + break; + case GradientBevelFilter: + defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; + break; + case GradientGlowFilter: + defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; + break; + } + // When returning NaN, the Tweener engine sets the starting value as being the same as the final value (if not found) + // When returning null, the Tweener engine doesn't tween it at all, just setting it to the final value + // This is DIFFERENT from the default filter applied as default on _filter_property_set because some values shouldn't be tweened + if (splitType == "color") { + // Composite, color channel; always defaults to target value + return NaN; + } else if (splitType == "matrix") { + // Composite, matrix; always defaults to target value + return defaultValues[propertyName][p_parameters[3]]; + } else if (splitType == "point") { + // Composite, point; always defaults to target value + return defaultValues[propertyName][p_parameters[3]]; + } else { + // Standard property + return defaultValues[propertyName]; + } + } + + public static function _filter_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var f:Array = p_obj.filters; + var i:Number; + var filterClass:Object = p_parameters[0]; + var propertyName:String = p_parameters[1]; + var splitType:String = p_parameters[2]; + for (i = 0; i < f.length; i++) { + if (f[i] is Class(filterClass)) { + if (splitType == "color") { + // Composite, color channel + var colorComponent:String = p_parameters[3]; + if (colorComponent == "r") f[i][propertyName] = (f[i][propertyName] & 0xffff) | (p_value << 16); + if (colorComponent == "g") f[i][propertyName] = (f[i][propertyName] & 0xff00ff) | (p_value << 8); + if (colorComponent == "b") f[i][propertyName] = (f[i][propertyName] & 0xffff00) | p_value; + } else if (splitType == "matrix") { + var mtx:Array = f[i][propertyName]; + mtx[p_parameters[3]] = p_value; + f[i][propertyName] = mtx; + } else if (splitType == "point") { + var pt:Point = Point(f[i][propertyName]); + pt[p_parameters[3]] = p_value; + f[i][propertyName] = pt; + } else { + // Standard property + f[i][propertyName] = p_value; + } + p_obj.filters = f; + return; + } + } + + // The correct filter class wasn't found, so create a new one that is the equivalent of the object without the filter + if (f == null) f = new Array(); + var fi:BitmapFilter; + switch (filterClass) { + case BevelFilter: + fi = new BevelFilter(0, 45, 0xffffff, 1, 0x000000, 1, 0, 0); + break; + case BlurFilter: + fi = new BlurFilter(0, 0); + break; + case ColorMatrixFilter: + fi = new ColorMatrixFilter([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]); + break; + case ConvolutionFilter: + fi = new ConvolutionFilter(1, 1, [1], 1, 0, true, true, 0x000000, 0); + break; + case DisplacementMapFilter: + // Doesn't make much sense to create a new empty DisplacementMapFilter if there's nothing to tween + fi = new DisplacementMapFilter(new BitmapData(10, 10), new Point(0, 0), 0, 1, 0, 0); + break; + case DropShadowFilter: + fi = new DropShadowFilter(0, 45, 0x000000, 1, 0, 0); + break; + case GlowFilter: + fi = new GlowFilter(0xff0000, 1, 0, 0); + break; + case GradientBevelFilter: + fi = new GradientBevelFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); + break; + case GradientGlowFilter: + fi = new GradientGlowFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); + break; + } + //fi[propertyName] = p_value; + f.push(fi); + p_obj.filters = f; + _filter_property_set(p_obj, p_value, p_parameters); + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/SoundShortcuts.as b/docviewerflex.backup/src/caurina/transitions/properties/SoundShortcuts.as new file mode 100644 index 0000000..6e8b8a7 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/SoundShortcuts.as @@ -0,0 +1,93 @@ +package caurina.transitions.properties { + + /** + * properties.SoundShortcuts + * List of default special properties for Sounds + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.media.SoundTransform; + + import caurina.transitions.Tweener; + + public class SoundShortcuts { + + /** + * There's no constructor. + */ + public function SoundShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init():void { + + // Normal properties + Tweener.registerSpecialProperty("_sound_volume", _sound_volume_get, _sound_volume_set); + Tweener.registerSpecialProperty("_sound_pan", _sound_pan_get, _sound_pan_set); + + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _sound_volume + + /** + * Returns the current sound volume + * + * @param p_obj Object SoundChannel object + * @return Number The current volume + */ + public static function _sound_volume_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.soundTransform.volume; + } + + /** + * Sets the sound volume + * + * @param p_obj Object SoundChannel object + * @param p_value Number New volume + */ + public static function _sound_volume_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { + var sndTransform:SoundTransform = p_obj.soundTransform; + sndTransform.volume = p_value; + p_obj.soundTransform = sndTransform; + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _sound_pan + + /** + * Returns the current sound pan + * + * @param p_obj Object SoundChannel object + * @return Number The current pan + */ + public static function _sound_pan_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.soundTransform.pan; + } + + /** + * Sets the sound volume + * + * @param p_obj Object SoundChannel object + * @param p_value Number New pan + */ + public static function _sound_pan_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { + var sndTransform:SoundTransform = p_obj.soundTransform; + sndTransform.pan = p_value; + p_obj.soundTransform = sndTransform; + } + + } + +} diff --git a/docviewerflex.backup/src/caurina/transitions/properties/TextShortcuts.as b/docviewerflex.backup/src/caurina/transitions/properties/TextShortcuts.as new file mode 100644 index 0000000..6d8f3f8 --- /dev/null +++ b/docviewerflex.backup/src/caurina/transitions/properties/TextShortcuts.as @@ -0,0 +1,157 @@ +package caurina.transitions.properties { + + /** + * properties.TextShortcuts + * Special properties for the Tweener class to handle MovieClip filters + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + import flash.text.TextFormat; + + public class TextShortcuts { + + /** + * There's no constructor. + */ + public function TextShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + // Normal properties + Tweener.registerSpecialProperty("_text", _text_get, _text_set, null, _text_preProcess); + // Tweener.registerSpecialPropertyModifier("_text", _text_modifier, _text_get); + + // TextFormat-based properties + Tweener.registerSpecialPropertySplitter("_text_color", _generic_color_splitter, ["_text_color_r", "_text_color_g", "_text_color_b"]); + Tweener.registerSpecialProperty("_text_color_r", _textFormat_property_get, _textFormat_property_set, ["color", true, "r"]); + Tweener.registerSpecialProperty("_text_color_g", _textFormat_property_get, _textFormat_property_set, ["color", true, "g"]); + Tweener.registerSpecialProperty("_text_color_b", _textFormat_property_get, _textFormat_property_set, ["color", true, "b"]); + Tweener.registerSpecialProperty("_text_indent", _textFormat_property_get, _textFormat_property_set, ["indent"]); + Tweener.registerSpecialProperty("_text_leading", _textFormat_property_get, _textFormat_property_set, ["leading"]); + Tweener.registerSpecialProperty("_text_leftMargin", _textFormat_property_get, _textFormat_property_set, ["leftMargin"]); + Tweener.registerSpecialProperty("_text_letterSpacing", _textFormat_property_get, _textFormat_property_set, ["letterSpacing"]); + Tweener.registerSpecialProperty("_text_rightMargin", _textFormat_property_get, _textFormat_property_set, ["rightMargin"]); + Tweener.registerSpecialProperty("_text_size", _textFormat_property_get, _textFormat_property_set, ["size"]); + + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _text + + /** + * Returns the current frame number from the movieclip timeline + * + * @param p_obj Object MovieClip object + * @return Number The current frame + */ + public static function _text_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + //return p_obj._currentFrame; + return -p_obj.text.length; + } + + /** + * Sets the timeline frame + * + * @param p_obj Object MovieClip object + * @param p_value Number New frame number + */ + public static function _text_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + //p_obj.gotoAndStop(Math.round(p_value)); + //p_obj.text = + if (p_value < 0) { + // Old text + p_obj.text = p_extra.oldText.substr(0, -Math.round(p_value)); + } else { + // New text + p_obj.text = p_extra.newText.substr(0, Math.round(p_value)); + } + } + + public static function _text_preProcess (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number { + p_extra.oldText = p_obj.text; + p_extra.newText = p_originalValueComplete; + return p_extra.newText.length; + } + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // generic splitters + + /** + * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + /** + * Generic function for the textformat properties + */ + public static function _textFormat_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + var fmt:TextFormat = p_obj.getTextFormat(); + var propertyName:String = p_parameters[0]; + var isColor:Boolean = p_parameters[1]; + if (!isColor) { + // Standard property + return (fmt[propertyName]); + } else { + // Composite, color channel + var colorComponent:String = p_parameters[2]; + if (colorComponent == "r") return AuxFunctions.numberToR(fmt[propertyName]); + if (colorComponent == "g") return AuxFunctions.numberToG(fmt[propertyName]); + if (colorComponent == "b") return AuxFunctions.numberToB(fmt[propertyName]); + } + + return NaN; + } + + public static function _textFormat_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var fmt:TextFormat = p_obj.getTextFormat(); + var propertyName:String = p_parameters[0]; + var isColor:Boolean = p_parameters[1]; + if (!isColor) { + // Standard property + fmt[propertyName] = p_value; + } else { + // Composite, color channel + var colorComponent:String = p_parameters[2]; + if (colorComponent == "r") fmt[propertyName] = (fmt[propertyName] & 0xffff) | (p_value << 16); + if (colorComponent == "g") fmt[propertyName] = (fmt[propertyName] & 0xff00ff) | (p_value << 8); + if (colorComponent == "b") fmt[propertyName] = (fmt[propertyName] & 0xffff00) | p_value; + } + + p_obj.defaultTextFormat = fmt; + p_obj.setTextFormat(fmt); + + } + + } + +} diff --git a/docviewerflex.backup/src/com/devaldi/controls/FlowBox.as b/docviewerflex.backup/src/com/devaldi/controls/FlowBox.as new file mode 100644 index 0000000..d393b78 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/FlowBox.as @@ -0,0 +1,314 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls +{ + + import flash.display.Bitmap; + import flash.display.DisplayObject; + import flash.events.Event; + + import mx.collections.ArrayCollection; + import mx.containers.Box; + import mx.containers.BoxDirection; + import mx.controls.Image; + import mx.events.ResizeEvent; + + + [DefaultProperty("children")] + public class FlowBox extends Box + { + + private var _children:ArrayCollection = new ArrayCollection(); + private var _childrenChanged:Boolean = false; + + public function FlowBox() + { + this.addEventListener(ResizeEvent.RESIZE,resizeHanlder); + } + + + /** + * If this component is resized, the child + * components must be laid out again + */ + private function resizeHanlder(e:Event):void + { + relayoutChildren(); + } + + + /** + * Layout all child components (if we need to) during + * the commit properties phase of execution + */ + protected override function commitProperties():void + { + super.commitProperties(); + + if( _childrenChanged ) + { + _childrenChanged = false; + + layoutChildren(); + } + } + + + /** + * Detect if any styles have been set which would + * require the child components to be laid out again + */ + override public function setStyle(styleProp:String, newValue:*):void + { + super.setStyle( styleProp, newValue ); + + if( this.initialized && + ( styleProp == "horizontalAlign" + || styleProp == "verticalAlign" + || styleProp == "horizontalGap" + || styleProp == "verticalGap" + || styleProp == "paddingLeft" + || styleProp == "paddingTop" + || styleProp == "paddingRight" + || styleProp == "paddingBottom" ) ) + relayoutChildren(); + } + + + /** + * Add all child components to ourself, creating + * sub containers as required for the layout + */ + private function layoutChildren():void + { + clearContentsForRelayout(); + + var currentSubContainer:Box = createSubContainer(); + super.addChildAt( currentSubContainer, super.numChildren ); + + for each( var child:DisplayObject in _children ) + { + if( !canFit( child, currentSubContainer ) ) + { + currentSubContainer = createSubContainer(); + super.addChildAt( currentSubContainer, super.numChildren ); + } + + currentSubContainer.addChild( child ); + } + } + + + /** + * Create a sub container (row or column) for + * this component will the required configuration + */ + private function createSubContainer():Box + { + var subContainer:Box = new Box(); + + subContainer.direction = this.direction; + + if( this.direction == BoxDirection.HORIZONTAL ) + subContainer.width = super.width - super.getStyle("paddingLeft") - super.getStyle("paddingRight"); + else + subContainer.height = super.height - super.getStyle("paddingTop") - super.getStyle("paddingBottom"); + + subContainer.setStyle( "paddingLeft", 0 ); + subContainer.setStyle( "paddingTop", 0 ); + subContainer.setStyle( "paddingBottom", 0 ); + subContainer.setStyle( "paddingRight", 0 ); + + subContainer.setStyle( "horizontalAlign", this.getStyle( "horizontalAlign" ) ); + subContainer.setStyle( "verticalAlign", this.getStyle( "verticalAlign" ) ); + subContainer.setStyle( "horizontalGap", this.getStyle( "horizontalGap" ) ); + subContainer.setStyle( "verticalGap", this.getStyle( "verticalGap" ) ); + + subContainer.setStyle( "backgroundAlpha", 0 ); + + return subContainer; + } + + + /** + * Removes all internal layout containers from this + * container so that the children can be re-laid out + */ + private function clearContentsForRelayout():void + { + for each( var child:DisplayObject in super.getChildren() ) + { + super.removeChild( child ); + } + } + + + /** + * Tests whether the specified component could fit within + * the specfied container without any clipping or scrollbars + */ + private function canFit( child:DisplayObject, parent:Box ):Boolean + { + var gap:Number; + var padding:Number; + var criticalDimension:String; + + if( parent.direction == BoxDirection.HORIZONTAL ) + { + gap = parent.getStyle( "horizontalGap" ); + padding = parent.getStyle( "paddingLeft" ) + parent.getStyle( "paddingRight" ); + criticalDimension = "width"; + } + else + { + gap = parent.getStyle( "verticalGap" ); + padding = parent.getStyle( "paddingTop" ) + parent.getStyle( "paddingBottom" ); + criticalDimension = "height"; + } + + var usedSpace:Number = padding; + var seperator:Number = 0; + for each( var existingChild:DisplayObject in parent.getChildren() ) + { + usedSpace += seperator + existingChild[criticalDimension]; + seperator = gap; + } + + var requiredSpace:Number = usedSpace + gap + child[criticalDimension]; + return ( requiredSpace < parent[criticalDimension] ); + } + + + /** + * Flag that the children of this control have changed, + * and should be redrawn at the next convenient time + */ + public function relayoutChildren():void + { + _childrenChanged = true; + invalidateProperties(); + } + + + /** + * Need to invert the direction property of this control + * so that the behaviour is logical + */ + override public function set direction(value:String):void + { + if( value == BoxDirection.HORIZONTAL ) + super.direction = BoxDirection.VERTICAL; + else + super.direction = BoxDirection.HORIZONTAL; + + relayoutChildren(); + } + override public function get direction():String + { + if( super.direction == BoxDirection.HORIZONTAL ) + return BoxDirection.VERTICAL; + else + return BoxDirection.HORIZONTAL; + } + + + /** + * Override all of the child manipulation functions to mask + * the internal child layout functions of this container + */ + public override function addChild(child:DisplayObject):DisplayObject + { + _children.addItem( child ); + relayoutChildren(); + return child; + } + override public function addChildAt(child:DisplayObject, index:int):DisplayObject + { + _children.addItemAt( child, index ); + relayoutChildren(); + return child; + } + override public function removeChild(child:DisplayObject):DisplayObject + { + var tmp:DisplayObject = _children.removeItemAt( _children.getItemIndex( child ) ) as DisplayObject; + relayoutChildren(); + return tmp; + } + override public function removeChildAt(index:int):DisplayObject + { + var tmp:DisplayObject = _children.removeItemAt( index ) as DisplayObject; + relayoutChildren(); + return tmp; + } + override public function removeAllChildren():void + { + var du:Object; + + for(var c:int=0;c<_children.length;c++){ + for(var i:int=0;i<_children[c].numChildren;i++){ + du = _children[c].getChildAt(i); + + if( du is Bitmap && (du as Bitmap).bitmapData != null) + du.bitmapData.dispose(); + } + } + + + _children.removeAll(); + relayoutChildren(); + } + override public function getChildren():Array + { + return _children.toArray(); + } + override public function getChildIndex(child:DisplayObject):int + { + return _children.getItemIndex( child ); + } + + public function getItemAt(i:int):DisplayObject{ + return _children.getItemAt(i) as DisplayObject; + } + + /** + * This property recieves the child components + * of this container when they are set in MXML + * + * This is set as the default property of this component + */ + public function set children( value:* ):void + { + if( value is DisplayObject ) + { + _children = new ArrayCollection([value]); + } + else if( value is Array ) + { + var tmp:Array = value as Array; + _children = new ArrayCollection(); + + for each( var child:DisplayObject in tmp ) + { + _children.addItem( child ); + } + } + relayoutChildren(); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/FlowVBox.as b/docviewerflex.backup/src/com/devaldi/controls/FlowVBox.as new file mode 100644 index 0000000..9fbeaa9 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/FlowVBox.as @@ -0,0 +1,16 @@ +package com.devaldi.controls +{ + + import flash.display.Bitmap; + + import mx.containers.VBox; + import mx.core.Container; + + public class FlowVBox extends VBox + { + public function FlowVBox() + { + + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/MatrixTransformer.as b/docviewerflex.backup/src/com/devaldi/controls/MatrixTransformer.as new file mode 100644 index 0000000..2c5c274 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/MatrixTransformer.as @@ -0,0 +1,109 @@ +package com.devaldi.controls +{ + import flash.geom.Matrix; + + /** + * Supports simple matrix transformations: scaling, translation, rotation, and skewing. + */ + + public class MatrixTransformer + { + /** + * Calls the appropriate method of the MatrixTransformer class, based on the radio buttons + * selected. Then updates the transformation matrix based on the results of the method. + * + * Runs the same transformation matrix through successive transformations and then applies + * the matrix to the image at the very end, which is more efficient than applying after + * each individual transformation. + */ + public static function transform(sourceMatrix:Matrix, + xScale:Number=100, + yScale:Number=100, + dx:Number=0, + dy:Number=0, + rotation:Number=0, + skew:Number=0, + skewType:String="right"):Matrix + { + // skew: + sourceMatrix = MatrixTransformer.skew(sourceMatrix, skew, skewType); + + // scale: + sourceMatrix = MatrixTransformer.scale(sourceMatrix, xScale, yScale); + + // translate: + sourceMatrix = MatrixTransformer.translate(sourceMatrix, dx, dy); + + // rotate: + sourceMatrix = MatrixTransformer.rotate(sourceMatrix, rotation, "degrees"); + + return sourceMatrix; + } + + /** + * Scales a matrix and returns the result. The percent parameter lets the user specify scale + * factors (xScale and yScale) as percentages (such as 33) instead of absolute values (such as 0.33). + */ + public static function scale(sourceMatrix:Matrix, xScale:Number, yScale:Number, percent:Boolean = true):Matrix + { + if (percent) + { + xScale = xScale / 100; + yScale = yScale / 100; + } + sourceMatrix.scale(xScale, yScale) + return sourceMatrix; + } + + /** + * Translates a matrix and returns the result. + */ + public static function translate(sourceMatrix:Matrix, dx:Number, dy:Number):Matrix { + sourceMatrix.translate(dx, dy); + return sourceMatrix; + } + + /** + * Rotates a matrix and returns the result. The unit parameter lets the user specify "degrees", + * "gradients", or "radians". + */ + public static function rotate(sourceMatrix:Matrix, angle:Number, unit:String = "radians"):Matrix { + if (unit == "degrees") + { + angle = Math.PI * 2 * angle / 360; + } + if (unit == "gradients") + { + angle = Math.PI * 2 * angle / 100; + } + sourceMatrix.rotate(angle) + return sourceMatrix; + } + + /** + * Scales a matrix and returns the result. The skewSide parameter lets the user + * determine which side to skew (right or bottom).The unit parameter lets the user + * specify "degrees", "gradients", or "radians". + */ + public static function skew(sourceMatrix:Matrix, angle:Number, skewSide:String = "right", unit:String = "degrees"):Matrix { + if (unit == "degrees") + { + angle = Math.PI * 2 * angle / 360; + } + if (unit == "gradients") + { + angle = Math.PI * 2 * angle / 100; + } + var skewMatrix:Matrix = new Matrix(); + if (skewSide == "right") + { + skewMatrix.b = Math.tan(angle); + } else { // skewSide == "bottom" + skewMatrix.c = Math.tan(angle); + } + sourceMatrix.concat(skewMatrix) + return sourceMatrix; + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/Spinner.as b/docviewerflex.backup/src/com/devaldi/controls/Spinner.as new file mode 100644 index 0000000..eb2faab --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/Spinner.as @@ -0,0 +1,433 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls +{ + import flash.display.GradientType; + import flash.display.Graphics; + import flash.events.Event; + import flash.events.TimerEvent; + import flash.geom.Matrix; + import flash.utils.Timer; + + import mx.core.UIComponent; + import mx.styles.CSSStyleDeclaration; + import mx.styles.StyleManager; + + /** + * The background alpha value (0-1). + * @default 1 + */ + [Style(name="backgroundAlpha", type="Number", format="Length", inherit="no")] + + /** + * The background color. + * @default NaN (no background) + */ + [Style(name="backgroundColor", type="uint", format="Color", inherit="no")] + + /** + * The spinner alpha value (0-1). + * @default 1 + */ + [Style(name="spinnerAlpha", type="Number", format="Length", inherit="no")] + + /** + * The normal spinner color. + * @default #829AD1 + */ + [Style(name="spinnerColor", type="uint", format="Color", inherit="no")] + + /** + * The normal spinner color. + * @default #829AD1 + */ + [Style(name="spinnerHighlightColor", type="uint", format="Color", inherit="no")] + + /** + * The thickness of the spinner when the default type is used. + * @default 3 + */ + [Style(name="spinnerThickness", type="Number", format="Length", inherit="no")] + + /** + * The thickness of the spinner when the lines type is used. + * @default 2 + */ + [Style(name="spinnerLineThickness", type="Number", format="Length", inherit="no")] + + /** + * The type of spinner - "circles", "lines", "gradientlines", or "gradientcircle". + * @default "gradientcircle" + */ + [Style(name="spinnerType", type="String", enumeration="gradientcircle,circles,lines,gradientlines", inherit="no")] + + + /** + * Draws an animated spinner in the shape of a circle. + * A timer is used to animate the spinner. + * If the startImmediately property is set to true, then the timer is started + * when the spinner is added to its parent + * It is always stopped when it is removed from its parent. + * Otherwise you can call the stop() function or set running = false. + * + *

+	 *  <ui:Spinner
+	 *   Properties
+	 *   delay="100"
+	 * 	 startImmediately="false"
+	 *   Styles
+	 *   backgroundAlpha="1"
+	 *   backgroundColor="NaN"
+ 	 *   spinnerColor="#829AD1"
+ 	 *   spinnerHighlightColor="#001A8E"
+ 	 *   spinnerThickness="3"
+ 	 *   spinnerLineThickness="2"
+ 	 *   spinnerType="gradientcircle"
+ 	 * >
+ 	 *      ...
+ 	 *      child tags
+ 	 *      ...
+ 	 *  </ui:Spinner>
+ 	 *  
+ * + * @author Chris Callendar + * @date April 16th, 2009 + */ + public class Spinner extends UIComponent + { + + // setup the default styles + private static var classConstructed:Boolean = classConstruct(); + private static function classConstruct():Boolean { + var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration("Spinner"); + if (!style) { + style = new CSSStyleDeclaration(); + } + style.defaultFactory = function():void { + this.backgroundAlpha = 1; + this.backgroundColor = NaN; // no default + this.spinnerAlpha = 1; + this.spinnerColor = 0x829AD1; + this.spinnerHighlightColor = 0x001A8E; + this.spinnerThickness = 3; + this.spinnerLineThickness = 2; + this.spinnerType = GRADIENT_CIRCLE; + }; + StyleManager.setStyleDeclaration("Spinner", style, true); + return true; + }; + + public static const GRADIENT_CIRCLE:String = "gradientcircle"; + public static const CIRCLES:String = "circles"; + public static const LINES:String = "lines"; + public static const GRADIENT_LINES:String = "gradientlines"; + + private static const MAX_ANGLE:Number = 2 * Math.PI; // 360 degrees + private static const POSITIONS:int = 8; + private static const ANGLE_INCR:Number = MAX_ANGLE / POSITIONS; // 45 degrees + + private var currentPosition:int; + private var timer:Timer; + private var matrix:Matrix; + + private var _startImmediately:Boolean; + + public function Spinner(spinnerWidth:Number = 16, spinnerHeight:Number = 16, + spinnerDelay:uint = 100) { + super(); + this.width = spinnerWidth; + this.height = spinnerHeight; + this._startImmediately = false; + currentPosition = 0; + timer = new Timer(spinnerDelay); + timer.addEventListener(TimerEvent.TIMER, timerHandler); + + // these listeners start and stop the timer + addEventListener(Event.ADDED, addedToParent); + addEventListener(Event.REMOVED, removedFromParent); + } + + [Bindable(event="delayChanged")] + [Inspectable(category="General", defaultValue="100")] + public function get delay():Number { + return timer.delay; + } + + public function set delay(ms:Number):void { + if ((ms >= 0) && (ms != timer.delay)) { + timer.delay = ms; + dispatchEvent(new Event("delayChanged")); + } + } + + [Inspectable(category="General", defaultValue="false")] + public function get startImmediately():Boolean { + return _startImmediately; + } + + public function set startImmediately(now:Boolean):void { + _startImmediately = now; + } + + private function addedToParent(event:Event):void { + if (startImmediately) { + start(); + } + } + + private function removedFromParent(event:Event):void { + stop(); + } + + private function timerHandler(event:TimerEvent):void { + currentPosition = (currentPosition + 1) % POSITIONS; + updateDisplayList(unscaledWidth, unscaledHeight); + } + + public function get running():Boolean { + return timer.running; + } + + public function set running(run:Boolean):void { + if (run != timer.running) { + if (run) { + timer.start(); + } else { + timer.stop(); + } + } + } + + public function stop():void { + if (timer.running) { + timer.stop(); + } + } + + public function start():void { + if (!timer.running) { + timer.start(); + } + } + + override protected function updateDisplayList(w:Number, h:Number):void { + super.updateDisplayList(w, h); + + var g:Graphics = graphics; + g.clear(); + fillBackground(g, w, h); + drawSpinner(g, w, h); + } + + /** + * Draws the spinner depending on the spinner styles + * and the spinner type. + */ + protected function drawSpinner(g:Graphics, w:Number, h:Number):void { + var spinnerAlpha:Number = getNumberStyle("spinnerAlpha", 1); + if (spinnerAlpha == 0) { + return; + } + var normal:uint = uint(getStyle("spinnerColor")); + var highlight:uint = uint(getStyle("spinnerHighlightColor")); + var thickness:Number = getNumberStyle("spinnerThickness", 3); + var lineThickness:Number = getNumberStyle("spinnerLineThickness", 2); + + var midX:Number = Math.floor(w / 2); + var midY:Number = Math.floor(h / 2); + var diameter:Number = Math.min(w, h); + var radius:int = Math.floor(diameter / 2); + + var spinnerType:String = getStyle("spinnerType"); + if (spinnerType == null) { + spinnerType = GRADIENT_CIRCLE; + } + var drawLines:Boolean = (spinnerType == LINES); + var drawCircles:Boolean = (spinnerType == CIRCLES); + if (drawLines || drawCircles) { + // draw 8 small spinning circles or lines + var smallRadius:int = int(Math.min(w, h) / 8); + var angle:Number = 0; + var count:int = 0; + while (angle < MAX_ANGLE) { + // figure out the position around the outer circle + // also adjust for the small radius to keep the small circles/lines inside the bounds + var x1:Number = midX + (radius * Math.sin(angle)) - (smallRadius * Math.sin(angle)); + var y1:Number = midY - (radius * Math.cos(angle)) + (smallRadius * Math.cos(angle)); + var color:uint = (count == currentPosition ? highlight : normal); + + if (drawLines) { + var x2:Number = midX; + var y2:Number = midY; + // make a hole in the center? + x2 = x2 + (3 * Math.sin(angle)); + y2 = y2 - (3 * Math.cos(angle)); + drawLine(g, color, x1, y1, x2, y2, lineThickness, spinnerAlpha); + } else if (drawCircles) { + drawCircle(g, color, x1, y1, smallRadius, spinnerAlpha); + } + + angle += ANGLE_INCR; + count++; + } + } else if (spinnerType == GRADIENT_LINES) { + drawGradientLines(g, normal, highlight, midX, midY, radius, lineThickness, spinnerAlpha); + } else { + // draw a large solid spinning circle + radius = Math.floor(diameter - thickness - 1) / 2; // keep the circle inside the bounds + drawGradientCircle(g, normal, highlight, midX, midY, radius, thickness, spinnerAlpha); + } + } + + /** + * Draws a small circle at the given position. + */ + protected function drawCircle(g:Graphics, color:uint, midX:Number, midY:Number, radius:Number, + circleAlpha:Number = 1):void { + if ((radius > 0) && (circleAlpha > 0)) { + g.lineStyle(0, 0, 0); // no border + g.beginFill(color, circleAlpha); + g.drawCircle(midX, midY, radius); + g.endFill(); + } + } + + /** + * Draws a small line from the given points. + */ + protected function drawLine(g:Graphics, color:uint, x1:Number, y1:Number, x2:Number, y2:Number, + thickness:int = 2, lineAlpha:Number = 1):void { + if ((thickness > 0) && (lineAlpha > 0)) { + // draw the line + g.lineStyle(thickness, color, lineAlpha, true); + g.moveTo(x1, y1); + g.lineTo(x2, y2); + } + } + + /** + * Draws a circle of lines with a gradient style. + */ + protected function drawGradientLines(g:Graphics, color:uint, highlight:uint, + midX:Number, midY:Number, radius:Number, thickness:Number = 2, lineAlpha:Number = 1):void { + if ((radius > 0) && (thickness > 0) && (lineAlpha > 0)) { + // draw the gradient lines - the matrix rotation value changes to give the spinning appearance + g.lineStyle(thickness); + if (matrix == null) { + matrix = new Matrix(); + } + var gradientAngle:Number = currentPosition * ANGLE_INCR; + matrix.createGradientBox(2 * radius, 2 * radius, gradientAngle, midX - radius, midY - radius); + var avg:uint = average(highlight, color); + g.lineGradientStyle(GradientType.LINEAR, [color, avg, highlight], + [lineAlpha, lineAlpha, lineAlpha], [0, 128, 255], matrix); + + var angle:Number = 0; + var incr:Number = MAX_ANGLE / 12; + while (angle < MAX_ANGLE) { + // figure out the position around the outer circle + // also adjust keep the small lines inside the bounds + var x1:Number = midX + (radius * Math.sin(angle)) - (1 * Math.sin(angle)); + var y1:Number = midY - (radius * Math.cos(angle)) + (1 * Math.cos(angle)); + // make a hole in the center? + var x2:Number = midX + (4 * Math.sin(angle)); + var y2:Number = midY - (4 * Math.cos(angle)); + g.moveTo(x1, y1); + g.lineTo(x2, y2); + + angle += incr; + } + + } + } + + /** + * Draws a gradient circle. + */ + protected function drawGradientCircle(g:Graphics, color:uint, highlight:uint, + midX:Number, midY:Number, radius:Number, thickness:Number = 3, circleAlpha:Number = 1):void { + if ((radius > 0) && (thickness > 0) && (circleAlpha > 0)) { + // draw the circle - the matrix rotation value changes to give the + // impression that the circle is spinning + g.lineStyle(thickness); + if (matrix == null) { + matrix = new Matrix(); + } + var angle:Number = currentPosition * ANGLE_INCR; + matrix.createGradientBox(2 * radius, 2 * radius, angle, midX - radius, midY - radius); + g.lineGradientStyle(GradientType.LINEAR, [highlight, color], [circleAlpha, circleAlpha], [0, 96], matrix); + g.drawCircle(midX, midY, radius); + } + } + + /** + * Fills the background using the backgroundAlpha and backgroundColor styles. + */ + protected function fillBackground(g:Graphics, w:Number, h:Number):void { + var bgAlpha:Number = getNumberStyle("backgroundAlpha", 1); + var color:Number = Number(getStyle("backgroundColor")); + if (!isNaN(color) && (bgAlpha > 0) && (bgAlpha <= 1)) { + g.lineStyle(0, 0, 0); + g.beginFill(uint(color), bgAlpha); + g.drawRect(0, 0, w, h); + g.endFill(); + } + } + + protected function getNumberStyle(styleName:String, defaultValue:Number):Number { + var num:Number = getStyle(styleName); + if (isNaN(num)) { + num = defaultValue; + } + return num; + } + + /** + * Combines the red, green, and blue color components into one 24 bit uint. + */ + public static function combine(r:uint, g:uint, b:uint):uint { + return (Math.min(Math.max(0, r), 255) << 16) | + (Math.min(Math.max(0, g), 255) << 8) | + Math.min(Math.max(0, b), 255); + } + + /** + * Returns the average of the two colors. Doesn't look at alpha values. */ + public static function average(c1:uint, c2:uint):uint { + var r:uint = Math.round((getRed(c1) + getRed(c2)) / 2); + var g:uint = Math.round((getGreen(c1) + getGreen(c2)) / 2); + var b:uint = Math.round((getBlue(c1) + getBlue(c2)) / 2); + return combine(r, g, b); + } + + public static function getRed(rgb:uint):uint { + return ((rgb >> 16) & 0xFF); + } + + public static function getGreen(rgb:uint):uint { + return ((rgb >> 8) & 0xFF); + } + + public static function getBlue(rgb:uint):uint { + return (rgb & 0xFF); + } + + } + +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/TwoPagePlugin.as b/docviewerflex.backup/src/com/devaldi/controls/TwoPagePlugin.as new file mode 100644 index 0000000..0f7c281 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/TwoPagePlugin.as @@ -0,0 +1,261 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls +{ + import com.devaldi.controls.flexpaper.FitModeEnum; + import com.devaldi.controls.flexpaper.IFlexPaperViewModePlugin; + import com.devaldi.controls.flexpaper.ShapeMarker; + import com.devaldi.controls.flexpaper.Viewer; + import com.devaldi.controls.flexpaper.utils.StreamUtil; + import com.devaldi.events.CurrentPageChangedEvent; + import com.devaldi.events.PageLoadingEvent; + import com.devaldi.streaming.DupLoader; + import flash.net.URLRequest; + + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.EventDispatcher; + import flash.events.IEventDispatcher; + import flash.events.MouseEvent; + import flash.utils.setTimeout; + + import mx.containers.HBox; + import mx.core.Container; + import mx.core.UIComponent; + + public class TwoPagePlugin implements IFlexPaperViewModePlugin, IEventDispatcher{ + private var dispatcher:IEventDispatcher = new EventDispatcher(); + private var viewer:Viewer; + private var _saveScale:Number = 1; + private var _hasinitialized:Boolean = false; + + public function TwoPagePlugin(){ + + } + + public function get Name():String{ + return "TwoPage"; + } + + public function get SaveScale():Number{ + return _saveScale; + } + + public function set SaveScale(n:Number):void{ + _saveScale = n; + } + + public function setViewMode(s:String):void{ + } + + public function addChild(i:int,o:DisplayObject):void{ + if(i==0 || i==1){ + viewer.DisplayContainer.addChild(o); + } + } + + public function renderPage(i:Number):void{ + var rp:int = 0; + rp = (i % 2 == 0)?0:1; + var uloaderidx:int = (i % 2 == 0)?0:1; + + if(i==viewer.PageList.length-1 && viewer.PageList.length % 2 == 1) + viewer.DisplayContainer.getChildAt(1).visible = false; + else + viewer.DisplayContainer.getChildAt(1).visible = true; + + if(((!viewer.BusyLoading||viewer.DocLoader.IsSplit)&&(!viewer.DocLoader.LoaderList[uloaderidx].loading)) && viewer.DocLoader.LoaderList!=null && viewer.DocLoader.LoaderList.length>0){ + if( viewer.libMC!=null&& + (viewer.numPagesLoaded>=viewer.PageList[i].dupIndex || viewer.DocLoader.IsSplit) && + (viewer.DocLoader.LoaderList[uloaderidx] != null) && + (viewer.DocLoader.LoaderList[uloaderidx].content==null) || + (viewer.DocLoader.LoaderList[uloaderidx].content!=null&&viewer.DocLoader.IsSplit && viewer.DocLoader.LoaderList[uloaderidx].pageStartIndex != i+1 && !viewer.DocLoader.LoaderList[uloaderidx].loading) || + (viewer.DocLoader.LoaderList[uloaderidx].content!=null&&(viewer.DocLoader.LoaderList[uloaderidx].content.framesLoaded1){viewer.gotoPage(viewer.currPage-2,0);} + } + + public function mvNext():void{ + if(viewer.currPage+2<=viewer.numPages){viewer.gotoPage(viewer.currPage+2,0);} + } + + public function handleDoubleClick(event:MouseEvent):void{ + viewer.FitMode = FitModeEnum.FITHEIGHT; + } + + public function handleMouseDown(event:MouseEvent):void{ + if(Number(viewer.Scale) <= viewer.getFitHeightFactor()){ + viewer.Zoom(viewer.MaxZoomSize/3); + }else{ + viewer.FitMode = FitModeEnum.FITHEIGHT; + } + } + + public function hasEventListener(type:String):Boolean { + return dispatcher.hasEventListener(type); + } + + public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { + dispatcher.removeEventListener(type, listener, useCapture); + } + + public function willTrigger(type:String):Boolean { + return dispatcher.willTrigger(type); + } + + public function initComponent(v:Viewer):Boolean{ + viewer = v; + viewer.DisplayContainer = new HBox(); + viewer.DisplayContainer.setStyle("horizontalAlign", "center"); + viewer.DisplayContainer.setStyle("horizontalGap",1); + viewer.PaperContainer.childrenDoDrag = true; + viewer.PaperContainer.addChild(viewer.DisplayContainer); + viewer.PaperContainer.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true,0,true); + viewer.FitPageOnLoad = true; + viewer.DisplayContainer.visible = false; + viewer.DisplayContainer.addEventListener(Event.RENDER,doRender,false,0,true); + + _hasinitialized = false; + return true; + } + + private function mouseMoveHandler(evt:MouseEvent):void{ + if(evt.target is DupLoader && viewer.FitMode != FitModeEnum.FITHEIGHT){ + viewer.PaperContainer.verticalScrollPosition = viewer.PaperContainer.maxVerticalScrollPosition * (viewer.PaperContainer.mouseY/viewer.PaperContainer.height); + viewer.PaperContainer.horizontalScrollPosition = viewer.PaperContainer.maxHorizontalScrollPosition * (viewer.PaperContainer.mouseX/viewer.PaperContainer.width); + } + } + + private function doRender(e:Event):void{ + if(!_hasinitialized){ + viewer.FitMode = FitModeEnum.FITHEIGHT; + _hasinitialized = true; + } + } + + public function initOnLoading():void{ + viewer.BusyLoading = true; + viewer.DocLoader.LoaderList[0].pageStartIndex = 1; + viewer.DocLoader.LoaderList[0].loadBytes(viewer.libMC.loaderInfo.bytes,StreamUtil.getExecutionContext()); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/ZoomCanvas.as b/docviewerflex.backup/src/com/devaldi/controls/ZoomCanvas.as new file mode 100644 index 0000000..eb22767 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/ZoomCanvas.as @@ -0,0 +1,167 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls +{ +import flash.geom.*; +import flash.utils.getDefinitionByName; +import mx.containers.Canvas; +import flash.events.Event; +import flash.events.MouseEvent; + +/** + * ZoomCanvas; Provides basic center zooming functionality. + * Use CenteringEnabled(true/false) to turn on and off. + */ +public class ZoomCanvas extends Canvas { + + public var CenteringEnabled:Boolean = false; + private var rX:Number; + private var rY:Number; + private var lVscrollPos:Number; + private var lHscrollPos:Number; + private var _childrenDoDrag:Boolean = true; + + public function ZoomCanvas() { + super(); + } + + override protected function createChildren():void { + super.createChildren(); + + this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging); + } + + public function get childrenDoDrag():Boolean { + return this._childrenDoDrag; + } + + public function set childrenDoDrag(value:Boolean):void { + this._childrenDoDrag = value; + } + + protected function startDragging(event:MouseEvent):void + { + if(event.target.parent == this.verticalScrollBar || + event.target.parent == this.horizontalScrollBar) { + return; + } + + if(_childrenDoDrag || event.target == this) { + rX = event.stageX; + rY = event.stageY; + + lVscrollPos = this.verticalScrollPosition; + lHscrollPos = this.horizontalScrollPosition; + + systemManager.addEventListener( + MouseEvent.MOUSE_MOVE, systemManager_mouseMoveHandler, true); + + systemManager.addEventListener( + MouseEvent.MOUSE_UP, systemManager_mouseUpHandler, true); + + systemManager.stage.addEventListener( + Event.MOUSE_LEAVE, stage_mouseLeaveHandler); + + systemManager.stage.addEventListener( + MouseEvent.ROLL_OVER, stage_mouseOverHandler); + + systemManager.stage.addEventListener( + MouseEvent.ROLL_OUT, stage_mouseOutHandler); + + } + } + + private function systemManager_mouseMoveHandler(event:MouseEvent):void + { + event.stopImmediatePropagation(); + + this.verticalScrollPosition = lVscrollPos - (event.stageY - rY); + this.horizontalScrollPosition = lHscrollPos - (event.stageX - rX); + } + + private function systemManager_mouseUpHandler(event:MouseEvent):void + { + if (!isNaN(rX)) + stopDragging(); + } + + private function stage_mouseLeaveHandler(event:Event):void + { + if (!isNaN(rX)) + stopDragging(); + } + + private function stage_mouseOverHandler(event:Event):void{ + } + + private function stage_mouseOutHandler(event:Event):void{ + } + + protected function stopDragging():void + { + systemManager.removeEventListener( + MouseEvent.MOUSE_MOVE, systemManager_mouseMoveHandler, true); + + systemManager.removeEventListener( + MouseEvent.MOUSE_UP, systemManager_mouseUpHandler, true); + + systemManager.stage.removeEventListener( + Event.MOUSE_LEAVE, stage_mouseLeaveHandler); + + rX = NaN; + rY = NaN; + } + + override public function validateDisplayList():void{ + + var centerPercentX:Number = 0; + var centerPercentY:Number = 0; + + if (maxHorizontalScrollPosition > 0) { + centerPercentX = horizontalScrollPosition / maxHorizontalScrollPosition; + } else { + centerPercentX = 0.5; + } + + if (maxVerticalScrollPosition > 0) { + centerPercentY = verticalScrollPosition / maxVerticalScrollPosition; + } else { + centerPercentY = 0.5; + } + + super.validateDisplayList(); + if(CenteringEnabled){ + + if (maxHorizontalScrollPosition > 0) { + var newHScrollPosition:Number = maxHorizontalScrollPosition * centerPercentX; + newHScrollPosition = newHScrollPosition > 0 ? newHScrollPosition : 0; + newHScrollPosition = newHScrollPosition < maxHorizontalScrollPosition ? newHScrollPosition : maxHorizontalScrollPosition; + horizontalScrollPosition = newHScrollPosition; + } + + if (maxVerticalScrollPosition > 0) { + var newVScrollPosition:Number = maxVerticalScrollPosition * centerPercentY; + newVScrollPosition = newVScrollPosition > 0 ? newVScrollPosition : 0; + newVScrollPosition = newVScrollPosition < maxVerticalScrollPosition ? newVScrollPosition : maxVerticalScrollPosition; + verticalScrollPosition = newVScrollPosition; + } + } + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/About.mxml b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/About.mxml new file mode 100644 index 0000000..c8c3b23 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/About.mxml @@ -0,0 +1,46 @@ + + + + [ResourceBundle("FlexPaper")] + + + + + + + + + + + + + diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FitModeEnum.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FitModeEnum.as new file mode 100644 index 0000000..6dba0bf --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FitModeEnum.as @@ -0,0 +1,27 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls.flexpaper +{ + public final class FitModeEnum + { + public static const FITNONE:String = "Fit None"; + public static const FITWIDTH:String = "Fit Width"; + public static const FITHEIGHT:String = "Fit Height"; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml new file mode 100644 index 0000000..39cfa9b --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml @@ -0,0 +1,291 @@ + + + + [ResourceBundle("FlexPaper")] + [Event(name="onDocumentLoaded", type="com.devaldi.events.DocumentLoadedEvent")] + [Event(name="onLoadingProgress", type="flash.events.ProgressEvent")] + [Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] + [Event(name="onCurrPageChanged", type="com.devaldi.events.CurrentPageChangedEvent")] + [Event(name="onDocumentLoading", type="flash.events.Event")] + [Event(name="onExternalLinkClicked", type="com.devaldi.events.ExternalLinkClickedEvent")] + [Event(name="onDocumentPrinted", type="com.devaldi.events.DocumentPrintedEvent")] + [Event(name="onPageLoaded", type="com.devaldi.events.PageLoadedEvent")] + [Event(name="onPageLoading", type="com.devaldi.events.PageLoadingEvent")] + [Event(name="onErrorLoadingPage", type="com.devaldi.events.ErrorLoadingPageEvent")] + + + 1 && !isNaN(Number(txtPct.text.replace("%", "")))) { + paper.Zoom(new Number(txtPct.text.replace("%", "")) / 100); + } + } + + private function txtSearchKeyDown(event:KeyboardEvent):void { + if (event != null && event.keyCode == Keyboard.ENTER && txtSearch.text.length > 0) { + paper.searchText(txtSearch.text); + } + } + + private function txtPageNumKeyDown(event:KeyboardEvent):void { + if (event.keyCode == Keyboard.ENTER && txtPage.text.length > 0 && !isNaN(Number(txtPage.text))) { + paper.gotoPage(new Number(txtPage.text)); + } + } + + protected override function onDocumentLoadingProgressHandler(event:ProgressEvent):void { + lblProgress.text = String(Math.round(event.bytesLoaded / event.bytesTotal * 100)); + super.onDocumentLoadingProgressHandler(event); + } + + private function onScaleChanged(event:Event):void { + txtPct.text = formatPct(paper.Scale); + _sliderUserChange = false; + slidPctScale.value = Number(paper.Scale); + } + + public override function loadSwf(s:String):void { + bttnInfo.visible = false; + spin1.visible = true; + lblProgress.text = ""; + lblProgress.visible = true; + super.loadSwf(s); + } + + protected override function onViewModeChanged(event:ViewModeChangedEvent):void { + txtPage.text = formatPageNumber(viewer.currPage); + super.onViewModeChanged(event); + } + + protected function formatPageNumber(n:Number):String { + if (viewer.ViewMode == ViewModeEnum.TWOPAGE) + return viewer.currPage.toString() + "-" + (viewer.currPage + 1).toString(); + else + return n.toString(); + } + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml new file mode 100644 index 0000000..96957b8 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml @@ -0,0 +1,451 @@ + + + + 10){ +// var cmi_about:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "About")+' FlexPaper'); +// cmi_about.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, showInfo); +// contextMenu.customItems.push(cmi_about); +// } + + if (!ReadOnly) { + var cmi_print:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "Print") + " ..."); + cmi_print.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, printPaper); + contextMenu.customItems.push(cmi_print); + } + } + + public function setViewerFocus():void { + viewer.setPaperFocus(); + } + + public function getCurrPage():Number { + return viewer.currPage; + } + + public function getTotalPages():Number { + return viewer.numPages; + } + + public function nextPage():void { + viewer.mvNext(); + } + + public function prevPage():void { + return viewer.mvPrev(); + } + + public function get PluginList():Array { + return viewer.PluginList; + } + + public function set PluginList(p:Array):void { + viewer.PluginList = p; + } + + // public function showInfo(e:Event):void { + // var vabout:About = new About(); + // PopUpManager.addPopUp(vabout, this, true); + // PopUpManager.centerPopUp(vabout); + // } + + private function setFocusTo(e:MouseEvent):void { + stage.stageFocusRect = false; + stage.focus = e.target as InteractiveObject; + } + + public function printPaper(e:Event):void { + if (!ReadOnly) { + if (PrintDialogEnabled) { + prd = new PrintRangeDialog(); + PopUpManager.addPopUp(prd, this, true); + PopUpManager.centerPopUp(prd); + prd["bttnPrint"].addEventListener("click", printHandler); + } else { + viewer.printPaper(); + } + } + } + + protected function printHandler(event:Event):void { + if (prd.PrintRange != "" && prd.validated) { + viewer.printPaperRange(prd.PrintRange); + } else if (prd.validated) { + viewer.printPaper(); + } + } + + private function fullScreenRedraw(event:FullScreenEvent):void { + if (!event.fullScreen && _fixedWidth > 0) { + viewer.setActualSize(_fixedWidth, _fixedHeight); + } + + if (viewer.FitMode == FitModeEnum.FITWIDTH) { + flash.utils.setTimeout(viewer.fitWidth, 200); + } else if (viewer.FitMode == FitModeEnum.FITHEIGHT) { + flash.utils.setTimeout(viewer.fitHeight, 200); + } else { + viewer.PaperVisible = true; + } + + TrueFullScreenActive = event.fullScreen && !FullScreenAsMaxWindow; + } + + private function viewerKeyDown(event:KeyboardEvent):void { + if (event.keyCode == Keyboard.SPACE && !(event.target is mx.core.UITextField)) { + viewer.mvNext(); + } + } + + private function copyHandler(e:Event):void { + if (!ReadOnly) { + try { + Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, viewer.CurrentlySelectedText); + } catch (e:*) { + } + } + } + + protected function toggleFullScreen():void { + try { + if (!FullScreenAsMaxWindow) { + viewer.PaperVisible = false; // to avoid flickering and let it redraw properly + + if (this.stage.displayState == StageDisplayState.NORMAL) { + _fixedWidth = viewer.width; + _fixedHeight = viewer.height; + } + + switch (this.stage.displayState) { + case StageDisplayState.FULL_SCREEN: + this.stage.displayState = StageDisplayState.NORMAL; + break; + default: + this.stage.displayState = StageDisplayState.FULL_SCREEN; + break; + } + } else { + var ur:URLRequest = new URLRequest(this.stage.loaderInfo.url); + var uv:URLVariables = new URLVariables(); + uv.Scale = Scale; + uv.SecretKey = SecretKey; + uv.SwfFile = SwfFile; + uv.ZoomTransition = ZoomTransition; + uv.ZoomTime = ZoomTime; + uv.ZoomInterval = ZoomInterval; + uv.FitPageOnLoad = viewer.FitMode == FitModeEnum.FITHEIGHT; + uv.FitWidthOnLoad = viewer.FitMode == FitModeEnum.FITWIDTH; + uv.ViewModeToolsVisible = ViewModeToolsVisible; + uv.ZoomToolsVisible = ZoomToolsVisible; + uv.NavToolsVisible = NavToolsVisible; + uv.CursorToolsVisible = CursorToolsVisible; + uv.SearchToolsVisible = SearchToolsVisible; + uv.ProgressiveLoading = ProgressiveLoading; + uv.FullScreenAsMaxWindow = FullScreenAsMaxWindow; + uv.localeChain = resourceManager.localeChain; + uv.ReadOnly = ReadOnly; + ur.data = uv; + navigateToURL(ur, "FlexPaperFullScreen"); + } + } catch (err:SecurityError) { + + } + } + + public function fitWidth():void { + viewer.fitWidth(); + } + + public function fitHeight():void { + viewer.fitHeight(); + } + + public function gotoPage(p:Number):void { + viewer.gotoPage(p); + } + + protected function documentLoadedErrorHandler(event:Event):void { + dispatchEvent(event); + } + + protected function onFitModeChanged(event:FitModeChangedEvent):void { + dispatchEvent(event); + } + + protected function onViewModeChanged(event:ViewModeChangedEvent):void { + dispatchEvent(event); + } + + protected function onCurrPageChanged(event:CurrentPageChangedEvent):void { + dispatchEvent(event); + } + + protected function onCursorModeChanged(event:CursorModeChangedEvent):void { + dispatchEvent(event); + } + + protected function onExternalLinkClickedHandler(event:ExternalLinkClickedEvent):void { + dispatchEvent(event); + } + + protected function onDocumentLoadingProgressHandler(event:ProgressEvent):void { + dispatchEvent(event); + } + + protected function papersLoadingHandler(event:Event):void { + dispatchEvent(event); + } + + protected function pageLoadingEventHandler(event:Event):void { + dispatchEvent(event); + } + + protected function documentPrintedHandler(event:DocumentPrintedEvent):void { + dispatchEvent(event); + } + + protected function documentLoadedHandler(event:Event):void { + dispatchEvent(event); + } + + protected function pageLoadedEventHandler(event:Event):void { + dispatchEvent(event); + } + + protected function errorLoadingPageEventHandler(event:ErrorLoadingPageEvent):void { + dispatchEvent(event); + } + + public function Zoom(factor:Number):void { + viewer.Zoom(factor); + } + + public function searchText(text:String):void { + viewer.searchText(text); + } + + public function prevSearchMatch():void { + viewer.prevSearchMatch(); + } + + public function nextSearchMatch(text:String):void { + viewer.nextSearchMatch(text); + } + + public function switchMode(mode:String = null):void { + viewer.switchMode(mode); + } + + public function setCurrentCursor(cursor:String):void { + if (cursor == "TextSelectorCursor") { + viewer.TextSelectEnabled = true; + } else if (cursor == "ArrowCursor") { + viewer.TextSelectEnabled = false; + } + } + + protected function formatPct(item:Object):String { + var spct:String = (Math.round(Number(item) * 100)) + "%"; + return spct; + } + + public function loadSwf(s:String):void { + viewer.SwfFile = s; + } + + public function loadFromBytes(b:ByteArray):void { + viewer.loadFromBytes(b); + } + + override protected function createChildren():void { + super.createChildren(); + + if (viewer == null) + return; + + _browserManager = BrowserManager.getInstance(); + + try { + //if(LicenseKey.validate(_browserManager.url,VersionHandler.version(),Key,true)){ + + + if (StreamUtil.DocLoader == null) { + viewer.DocLoader = new AVM2Loader(StreamUtil.getExecutionContext(), StreamUtil.ProgressiveLoading); + } else { + viewer.DocLoader = StreamUtil.DocLoader; + } + //} + + viewer.DocLoader.addEventListener("onDocumentLoadedError", onLoadedError); + } catch(e:Error) { + Alert.show(e.message, "Error"); + } + } + + protected function onLoadedError(event:ErrorEvent):void { + dispatchEvent(event); + } + + public function highlight(url:String):void { + viewer.highlight(url); + } + + public function postSnapshot(url:String):void { + var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(viewer); + var imageByteArray:ByteArray = imageSnap.data as ByteArray; + + var request:URLRequest = new URLRequest(url); + var loader:URLLoader = new URLLoader(); + request.contentType = 'application/octet-stream'; + request.method = URLRequestMethod.POST; + request.data = imageByteArray; + loader.load(request); + } + + public function getSecretKey():String { + return SecretKey; + } + + public function setSecretKey(value:String):void { + SecretKey = value; + } + ]]> + + diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPlugin.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPlugin.as new file mode 100644 index 0000000..43b3c46 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPlugin.as @@ -0,0 +1,16 @@ +package com.devaldi.controls.flexpaper +{ + import com.devaldi.streaming.DupImage; + import flash.display.MovieClip; + + [Event(name="onPageNavigate", type="flash.events.Event")] + + public interface IFlexPaperPlugin + { + function drawSelf(pageIndex:int, drawingObject:Object,scale:Number):void; + function init():void; + function registerCallbackMethods():void; + function clear():void; + function bindPaperEventHandler(d:DupImage):void; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as new file mode 100644 index 0000000..c62a428 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as @@ -0,0 +1,8 @@ +package com.devaldi.controls.flexpaper +{ + public interface IFlexPaperPluginControl + { + function get isInitialized():Boolean; + function set isInitialized(b:Boolean):void; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperViewModePlugin.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperViewModePlugin.as new file mode 100644 index 0000000..b1d32b9 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/IFlexPaperViewModePlugin.as @@ -0,0 +1,33 @@ +package com.devaldi.controls.flexpaper +{ + import flash.display.DisplayObject; + import flash.events.MouseEvent; + + import mx.core.UIComponent; + + public interface IFlexPaperViewModePlugin + { + function get Name():String; + function get doZoom():Boolean; + function get doFitHeight():Boolean; + function get doFitWidth():Boolean; + function get supportsTextSelect():Boolean; + function initComponent(v:Viewer):Boolean; + function initOnLoading():void; + function setViewMode(s:String):void; + function gotoPage(page:Number,adjGotoPage:int=0):void; + function get currentPage():int; + function renderPage(page:Number):void; + function renderSelection(page:int,marker:ShapeMarker):void; + function checkIsVisible(page:int):Boolean; + function handleDoubleClick(event:MouseEvent):void; + function handleMouseDown(event:MouseEvent):void; + function get loaderListLength():int; + function addChild(childindex:int,o:DisplayObject):void; + function get SaveScale():Number; + function set SaveScale(n:Number):void; + function mvNext():void; + function mvPrev():void; + function renderMark(sm:UIComponent,pageIndex:int):void; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/PrintRangeDialog.mxml b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/PrintRangeDialog.mxml new file mode 100644 index 0000000..527ce3f --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/PrintRangeDialog.mxml @@ -0,0 +1,78 @@ + + + + + [ResourceBundle("FlexPaper")] + + + -1 && range_exp.test(pageList[i].toString())) || (numb_exp.test(pageList[i].toString())); + if(!validated){break;} + } + + if(validated){ + PrintRange=txtPrintRange.text; + }else{ + valmsg = resourceManager.getString("FlexPaper", "Incorrectrangespecified"); + } + } + if(bttnPrintAll.selected){PrintRange = "";} + + if(validated){ + PopUpManager.removePopUp(this); + }else{ + Alert.show(valmsg,resourceManager.getString("FlexPaper", "IncorrectRange"),mx.controls.Alert.OK,this); + } + } + ]]> + + + + + + + + + + diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ShapeMarker.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ShapeMarker.as new file mode 100644 index 0000000..a96ae79 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ShapeMarker.as @@ -0,0 +1,32 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls.flexpaper +{ + import flash.display.Sprite; + + public class ShapeMarker extends Sprite + { + public var PageIndex:int = -1; + public var data:Object = null; + + public function ShapeMarker() + { + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ViewModeEnum.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ViewModeEnum.as new file mode 100644 index 0000000..0f5168d --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/ViewModeEnum.as @@ -0,0 +1,9 @@ +package com.devaldi.controls.flexpaper +{ + public final class ViewModeEnum + { + public static const PORTRAIT:String = "Portrait"; + public static const TILE:String = "Tile"; + public static const TWOPAGE:String = "TwoPage"; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/Viewer.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/Viewer.as new file mode 100644 index 0000000..a1ae796 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/Viewer.as @@ -0,0 +1,2932 @@ +/* + Copyright 2009 Erik Engström + + This file is part of FlexPaper. + + FlexPaper 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, version 3 of the License. + + FlexPaper 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 FlexPaper. If not, see . + */ + +package com.devaldi.controls.flexpaper { +import caurina.transitions.Tweener; + +import com.devaldi.controls.FlowBox; +import com.devaldi.controls.FlowVBox; +import com.devaldi.controls.ZoomCanvas; +import com.devaldi.controls.flexpaper.resources.MenuIcons; +import com.devaldi.controls.flexpaper.utils.StreamUtil; +import com.devaldi.controls.flexpaper.utils.TextMapUtil; +import com.devaldi.events.CurrentPageChangedEvent; +import com.devaldi.events.CursorModeChangedEvent; +import com.devaldi.events.DocumentLoadedEvent; +import com.devaldi.events.DocumentPrintedEvent; +import com.devaldi.events.ErrorLoadingPageEvent; +import com.devaldi.events.ExternalLinkClickedEvent; +import com.devaldi.events.FitModeChangedEvent; +import com.devaldi.events.PageLoadedEvent; +import com.devaldi.events.PageLoadingEvent; +import com.devaldi.events.ScaleChangedEvent; +import com.devaldi.events.SelectionCreatedEvent; +import com.devaldi.events.SwfLoadedEvent; +import com.devaldi.events.ViewModeChangedEvent; +import com.devaldi.streaming.DupImage; +import com.devaldi.streaming.DupLoader; +import com.devaldi.streaming.IDocumentLoader; +import com.devaldi.streaming.IGenericDocument; +import com.devaldi.streaming.SwfDocument; +import com.log4ic.utils.security.Security; +import com.sinitek.log4ic.utils.security.Security; + +import flash.display.AVM1Movie; +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.display.DisplayObject; +import flash.display.InteractiveObject; +import flash.display.Loader; +import flash.display.MovieClip; +import flash.display.SimpleButton; +import flash.display.Sprite; +import flash.events.Event; +import flash.events.IOErrorEvent; +import flash.events.KeyboardEvent; +import flash.events.MouseEvent; +import flash.events.ProgressEvent; +import flash.filters.DropShadowFilter; +import flash.geom.Matrix; +import flash.net.URLRequest; +import flash.printing.PrintJob; +import flash.printing.PrintJobOptions; +import flash.system.System; +import flash.text.TextSnapshot; +import flash.ui.Keyboard; +import flash.utils.ByteArray; +import flash.utils.Timer; +import flash.utils.setTimeout; + +import mx.containers.Canvas; +import mx.controls.Alert; +import mx.controls.Image; +import mx.core.Container; +import mx.core.UIComponent; +import mx.events.FlexEvent; +import mx.managers.CursorManager; +import mx.resources.ResourceManager; +import mx.rpc.events.FaultEvent; +import mx.rpc.events.ResultEvent; +import mx.rpc.http.HTTPService; + +[Event(name="onDocumentLoaded", type="com.devaldi.events.DocumentLoadedEvent")] +[Event(name="onPageLoaded", type="com.devaldi.events.PageLoadedEvent")] +[Event(name="onPageLoading", type="com.devaldi.events.PageLoadingEvent")] +[Event(name="onDocumentLoading", type="flash.events.Event")] +[Event(name="onNoMoreSearchResults", type="flash.events.Event")] +[Event(name="onLoadingProgress", type="flash.events.ProgressEvent")] +[Event(name="onScaleChanged", type="com.devaldi.events.ScaleChangedEvent")] +[Event(name="onExternalLinkClicked", type="com.devaldi.events.ExternalLinkClickedEvent")] +[Event(name="onCurrPageChanged", type="com.devaldi.events.CurrentPageChangedEvent")] +[Event(name="onViewModeChanged", type="com.devaldi.events.ViewModeChangedEvent")] +[Event(name="onFitModeChanged", type="com.devaldi.events.FitModeChangedEvent")] +[Event(name="onCursorModeChanged", type="com.devaldi.events.CursorModeChangedEvent")] +[Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] +//[Event(name="onLogoClicked", type="flash.events.Event")] +[Event(name="onSelectionCreated", type="com.devaldi.events.SelectionCreatedEvent")] +[Event(name="onDocumentPrinted", type="com.devaldi.events.DocumentPrintedEvent")] +[Event(name="onErrorLoadingPage", type="com.devaldi.events.ErrorLoadingPageEvent")] + +public class Viewer extends Canvas { + private var _secretKey:String = null; + private var _swfFile:String = ""; + private var _swfFileChanged:Boolean = false; + private var _initialized:Boolean = false; + private var _loaderptr:Loader; + private var _libMC:IGenericDocument; + private var _displayContainer:Container; + private var _paperContainer:ZoomCanvas; + private var _swfContainer:Canvas; + private var _scale:Number = 1; + private var _pscale:Number = 1; + private var _swfLoaded:Boolean = false; + private var _pageList:Array; + private var _viewMode:String = Viewer.InitViewMode; + private var _fitMode:String = FitModeEnum.FITNONE; + public static var InitViewMode:String = ViewModeEnum.PORTRAIT; + private var _scrollToPage:Number = 0; + private var _numPages:Number = 0; + private var _currPage:Number = 0; + private var _tweencount:Number = 0; + private var _bbusyloading:Boolean = true; + private var _zoomtransition:String = "easeOut"; + private var _zoomtime:Number = 0.6; + private var _fitPageOnLoad:Boolean = false; + private var _fitWidthOnLoad:Boolean = false; + private var _dupImageClicked:Boolean = false; + private var _docLoader:IDocumentLoader; + private var _progressiveLoading:Boolean = false; + private var _repaintTimer:Timer; + private var _loadTimer:Timer; + private var _frameLoadCount:int = 0; + private var _adjGotoPage:int = 0; + private var _zoomInterval:Number = 0; + private var _inputBytes:ByteArray; + private var _textSelectEnabled:Boolean = false; + private var _cursorsEnabled:Boolean = true; + private var _grabCursorID:Number = 0; + private var _grabbingCursorID:Number = 0; + private var _pluginList:Array; + public static var ViewModeExtList:Array; + private var _currentExtViewMode:IFlexPaperViewModePlugin; + private var _minZoomSize:Number = 0.3; + private var _maxZoomSize:Number = 5; + private var _searchMatchAll:Boolean = false; + private var _searchServiceUrl:String = ""; + private var _performSearchOnPageLoad:Boolean = false; + private var _pendingSearchPage:int = -1; + private var _skinImg:Bitmap = new MenuIcons.SMALL_TRANSPARENT(); + private var _skinImgc:Bitmap = new MenuIcons.SMALL_TRANSPARENT_COLOR(); + + +// private var _skinImgDo:Image; + + public function Viewer() { + super(); + } + + public function get BusyLoading():Boolean { + return _bbusyloading; + } + + public function set BusyLoading(b:Boolean):void { + _bbusyloading = b; + } + + public function get libMC():IGenericDocument { + return _libMC; + } + + public function get IsInitialized():Boolean { + return _initialized; + } + + public function get SwfLoaded():Boolean { + return _swfLoaded; + } + + public function get DisplayContainer():Container { + return _displayContainer; + } + + public function set DisplayContainer(c:Container):void { + _displayContainer = c; + } + + public function get PaperContainer():ZoomCanvas { + return _paperContainer; + } + + public function get PageList():Array { + return _pageList; + } + + public function get DocLoader():IDocumentLoader { + return _docLoader; + } + + public function set DocLoader(d:IDocumentLoader):void { + _docLoader = d; + } + + [Bindable] + public function get ViewMode():String { + return _viewMode; + } + + [Bindable] + public function get FitMode():String { + return _fitMode; + } + + public function set ViewMode(s:String):void { + if (s != _viewMode) { + for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList) { + if (s == vme.Name) { + _currentExtViewMode = vme; + } + } + + if (s == ViewModeEnum.TILE && ViewMode == ViewModeEnum.PORTRAIT) { + _pscale = _scale; + _scale = 0.23; + _paperContainer.verticalScrollPosition = 0; + _fitMode = FitModeEnum.FITNONE; + } else { + _scale = _pscale; + } + _paperContainer.x = (s == ViewModeEnum.PORTRAIT || s == ViewModeEnum.TILE) ? 2.5 : 0; + + _viewMode = s; + if (_initialized && _swfLoaded) { + createDisplayContainer(); + if (this._progressiveLoading) { + this.addInLoadedPages(true); + } else { + reCreateAllPages(); + } + _displayContainer.visible = true; + } + FitMode = FitModeEnum.FITNONE; + + if (UsingExtViewMode) { + CurrExtViewMode.setViewMode(s); + _viewMode = s; + } + + dispatchEvent(new ViewModeChangedEvent(ViewModeChangedEvent.VIEWMODE_CHANGED, _viewMode)); + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); + dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED, _fitMode)); + } + } + + public function set FitMode(s:String):void { + if (_viewMode == ViewModeEnum.TILE) { + _fitMode = FitModeEnum.FITNONE; + return + } + + if (s != _fitMode) { + _fitMode = s; + + switch (s) { + case FitModeEnum.FITWIDTH: + fitWidth(); + break; + + case FitModeEnum.FITHEIGHT: + fitHeight(); + break; + } + + dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED, _fitMode)); + } + } + + public function set ProgressiveLoading(b1:Boolean):void { + _progressiveLoading = b1; + } + + [Bindable] + public function get ProgressiveLoading():Boolean { + return _progressiveLoading; + } + + public function set TextSelectEnabled(b1:Boolean):void { + _textSelectEnabled = b1; + + if (_textSelectEnabled && CursorsEnabled) + dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED, "TextSelectorCursor")); + else + dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED, "ArrowCursor")); + } + + [Bindable] + public function get TextSelectEnabled():Boolean { + return _textSelectEnabled; + } + + [Bindable] + public function get CursorsEnabled():Boolean { + return _cursorsEnabled; + } + + public function set CursorsEnabled(b:Boolean):void { + _cursorsEnabled = b; + } + + public function setPaperFocus():void { + _paperContainer.setFocus(); + } + + public function get ZoomTransition():String { + return _zoomtransition; + } + + public function set ZoomTransition(s:String):void { + _zoomtransition = s; + } + + public function get ZoomTime():Number { + return _zoomtime; + } + + public function set ZoomTime(n:Number):void { + _zoomtime = n; + } + + public function get MinZoomSize():Number { + return _minZoomSize; + } + + public function set MinZoomSize(n:Number):void { + _minZoomSize = n; + } + + public function get MaxZoomSize():Number { + return _maxZoomSize; + } + + public function set MaxZoomSize(n:Number):void { + _maxZoomSize = n; + } + + public function get PluginList():Array { + return _pluginList; + } + + public function set PluginList(p:Array):void { + _pluginList = p; + } + + public function get CurrExtViewMode():IFlexPaperViewModePlugin { + if (_currentExtViewMode != null && _currentExtViewMode.Name == ViewMode) + return _currentExtViewMode; + else { + for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList) { + if (ViewMode == vme.Name) { + _currentExtViewMode = vme; + } + } + } + + return _currentExtViewMode; + } + + public function get UsingExtViewMode():Boolean { + if (ViewMode == ViewModeEnum.PORTRAIT || ViewMode == ViewModeEnum.TILE) + return false; + else + return (CurrExtViewMode != null && ViewMode == CurrExtViewMode.Name); + } + + public function get ZoomInterval():Number { + return _zoomInterval; + } + + public function set ZoomInterval(n:Number):void { + _zoomInterval = n; + } + + [Bindable] + public function get numPages():Number { + return _numPages; + } + + public function set numPages(n:Number):void { + _numPages = n; + } + + [Bindable] + public function get numPagesLoaded():Number { + return (_libMC != null) ? _libMC.framesLoaded : 0; + } + + public function set numPagesLoaded(n:Number):void { + + } + + [Bindable] + public function get currPage():Number { + return _currPage; + } + + public function set currPage(n:Number):void { + _currPage = n; + } + + [Bindable] + public function get SearchMatchAll():Boolean { + if (SearchServiceUrl != null && SearchServiceUrl.length > 0) + return false; + else + return _searchMatchAll; + } + + public function set SearchMatchAll(b1:Boolean):void { + _searchMatchAll = b1; + } + + [Bindable] + public function get SearchServiceUrl():String { + return _searchServiceUrl; + } + + public function set SearchServiceUrl(s1:String):void { + _searchServiceUrl = unescape(s1); + } + + public function get FitWidthOnLoad():Boolean { + return _fitWidthOnLoad; + } + + public function set FitWidthOnLoad(b1:Boolean):void { + _fitWidthOnLoad = b1; + } + + public function get FitPageOnLoad():Boolean { + return _fitPageOnLoad; + } + + public function set FitPageOnLoad(b2:Boolean):void { + _fitPageOnLoad = b2; + } + + public function gotoPage(p:Number, adjGotoPage:int = 0):void { + if (adjGotoPage != 0) { + _adjGotoPage = adjGotoPage; + } + + if (p < 1 || p - 1 > _pageList.length) + return; + else { + if (ViewMode == ViewModeEnum.PORTRAIT) { + _paperContainer.verticalScrollPosition = _pageList[p - 1].y + 3 + _adjGotoPage; + } + + if (UsingExtViewMode) + CurrExtViewMode.gotoPage(p, adjGotoPage); + + // retry if y is not set + if (!UsingExtViewMode && p > 1 && _pageList[p - 1].y == 0) { + flash.utils.setTimeout(gotoPage, 200, p); + } + else + _adjGotoPage = 0; + + repaint(); + } + } + + public function mvNext(extmode:Boolean = true):void { + if (UsingExtViewMode && extmode) + CurrExtViewMode.mvNext(); + else + if (currPage < numPages) { + gotoPage(currPage + 1); + } + } + + public function mvPrev(extmode:Boolean = true):void { + if (UsingExtViewMode && extmode) + CurrExtViewMode.mvPrev(); + else { + if (currPage > 1) { + gotoPage(currPage - 1); + } + } + } + + public function switchMode(mode:String = null):void { + if (mode == null) { // no mode passed, just + if (ViewMode == ViewModeEnum.PORTRAIT) { + ViewMode = ViewModeEnum.TILE; + } + else if (ViewMode == ViewModeEnum.TILE) { + _scale = _pscale; + ViewMode = ViewModeEnum.PORTRAIT; + } + } else { + if (ViewMode == mode && ViewMode != ViewModeEnum.PORTRAIT) { + ViewMode = ViewModeEnum.PORTRAIT; + } + else + ViewMode = mode; + } + } + + public function get PaperVisible():Boolean { + return _paperContainer.visible; + } + + public function set PaperVisible(b:Boolean):void { + _paperContainer.visible = b; + } + + public function get SwfFile():String { + return _swfFile; + } + + public function getSwfFilePerPage(swfFile:String, page:int):String { + var fileName:String = swfFile; + var map:String = (fileName.substr(fileName.indexOf("[*,"), fileName.indexOf("]") - fileName.indexOf("[*,") + 1)); + var padding:int = parseInt(map.substr(map.indexOf(",") + 1, map.indexOf("]") - 2)); + fileName = TextMapUtil.StringReplaceAll(fileName, map, padString(page.toString(), padding, "0")); + + return encodeURI(fileName); + } + + public function loadFromBytes(bytes:ByteArray):void { + clearPlugins(); + deleteDisplayContainer(); + deletePageList(); + deleteLoaderPtr(); + deleteLoaderList(); + deleteFLoader(); + deleteSelectionMarker(); + TextMapUtil.totalFragments = ""; + deleteLibMC(); + + _swfFileChanged = true; + _frameLoadCount = 0; + + ViewMode = Viewer.InitViewMode; + + try { + new flash.net.LocalConnection().connect('devaldiGCdummy'); + new flash.net.LocalConnection().connect('devaldiGCdummy'); + } catch (e:*) { + } + + try { + flash.system.System.gc(); + } catch (e:*) { + } + + if (_docLoader != null && !_docLoader.hasEventListener(SwfLoadedEvent.SWFLOADED)) { + _docLoader.addEventListener("onDocumentLoadedError", onDocumentLoadedErrorHandler, false, 0, true); + _docLoader.addEventListener(SwfLoadedEvent.SWFLOADED, swfComplete, false, 0, true); + } + + if (_docLoader != null) { + _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); + _docLoader.stream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress, false, 0, true); + } + + _docLoader.loadFromBytes(bytes); + + _paperContainer.verticalScrollPosition = 0; + createDisplayContainer(); + + // Changing the SWF file causes the component to invalidate. + invalidateProperties(); + invalidateSize(); + invalidateDisplayList(); + } + + public function set SwfFile(s:String):void { + var pagesSplit:Boolean = false; + s = unescape(s); + + if (s.length != 0) { + + if (s.indexOf("{") >= 0 && s.indexOf("}") > 0) { + numPages = parseInt(s.substr(s.lastIndexOf(",") + 1, s.indexOf("}") - s.lastIndexOf(",") - 1)); + s = TextMapUtil.StringReplaceAll(s, "{", ""); + s = TextMapUtil.StringReplaceAll(s, "," + numPages.toString() + "}", ""); + pagesSplit = true; + } + + clearPlugins(); + deleteDisplayContainer(); + deletePageList(); + deleteLoaderPtr(); + deleteLoaderList(); + deleteFLoader(); + deleteSelectionMarker(); + TextMapUtil.totalFragments = ""; + + if (s != _swfFile) + deleteLibMC(); + + _swfFileChanged = true; + _frameLoadCount = 0; + + if (!pagesSplit) + _swfFile = encodeURI(s); + else + _swfFile = s; + + ViewMode = Viewer.InitViewMode; + + try { + new flash.net.LocalConnection().connect('devaldiGCdummy'); + new flash.net.LocalConnection().connect('devaldiGCdummy'); + } catch (e:*) { + } + + try { + flash.system.System.gc(); + } catch (e:*) { + } + + if (_docLoader != null && !_docLoader.hasEventListener(SwfLoadedEvent.SWFLOADED)) { + _docLoader.IsSplit = pagesSplit; + _docLoader.addEventListener("onDocumentLoadedError", onDocumentLoadedErrorHandler, false, 0, true); + _docLoader.addEventListener(SwfLoadedEvent.SWFLOADED, swfComplete, false, 0, true); + } + + if (_docLoader != null) { + _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); + _docLoader.stream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress, false, 0, true); + } + + _paperContainer.verticalScrollPosition = 0; + createDisplayContainer(); + + // Changing the SWF file causes the component to invalidate. + invalidateProperties(); + invalidateSize(); + invalidateDisplayList(); + + var _request:URLRequest; + + if (_swfFile.length > 0 && pagesSplit) { + _loadTimer = new Timer(100); + _loadTimer.addEventListener("timer", loadtimer); + _request = new URLRequest(getSwfFilePerPage(_swfFile, 1)); + } + else if (_swfFile.length > 0 && !pagesSplit) { + _request = new URLRequest(_swfFile); + } + + Security.loadEncryptedFile(_request, _secretKey, function(e:Event):void { + _docLoader.loadFromBytes(_secretKey ? e.target.decryptedData : e.target.data); + }, onLoadProgress); + } + } + + [Bindable] + public function get Scale():String { + return _scale.toString(); + } + + public function get CurrentlySelectedText():String { + return _currentlySelectedText; + } + + public function Zoom(factor:Number):void { + if (factor < _minZoomSize || factor > _maxZoomSize || factor == _scale) + return; + + if ((!UsingExtViewMode && _viewMode != ViewModeEnum.PORTRAIT) || (UsingExtViewMode && !CurrExtViewMode.doZoom)) { + return; + } + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.width > 0); + + _tweencount = _displayContainer.numChildren; + + for (var i:int = 0; i < _displayContainer.numChildren; i++) { + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX: factor, scaleY: factor, time: _zoomtime, transition: _zoomtransition, onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITNONE; + _scale = factor; + + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); + } + + // rotate not finished. + public function rotate():void { + var counter:int = 0; + //Tweener.addTween(_displayContainer.getChildAt(currPage-1), {x:_displayContainer.getChildAt(currPage-1).parent.width/2+_displayContainer.getChildAt(currPage-1).height/2, y:((_displayContainer.getChildAt(currPage-1).height/2)-_displayContainer.getChildAt(currPage-1).width/2),rotation:90, time: 0.3, transition: 'easenone', onComplete: tweenComplete}); + } + + public function getFitWidthFactor():Number { + _libMC.gotoAndStop(1); + return (_paperContainer.width / _libMC.width) - 0.032; //- 0.03; + } + + public function getFitHeightFactor():Number { + _libMC.gotoAndStop(1); + return (_paperContainer.height / _libMC.height); + } + + public function fitWidth():Boolean { + if (_displayContainer.numChildren == 0) { + return false; + } + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.width > 0); + var factor:Number = getFitWidthFactor(); + _scale = factor; + _tweencount = _displayContainer.numChildren; + + for (var i:int = 0; i < _displayContainer.numChildren; i++) { + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITWIDTH; + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); + + _paperContainer.horizontalScrollPosition = _paperContainer.maxHorizontalScrollPosition / 2; + _paperContainer.validateDisplayList(); + + return factor > 0; + } + + public function fitHeight():Boolean { + if (_displayContainer.numChildren == 0) { + return false; + } + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.height > 0); + var factor:Number = getFitHeightFactor(); + _scale = factor; + _tweencount = _displayContainer.numChildren; + + for (var i:int = 0; i < _displayContainer.numChildren; i++) { + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITHEIGHT; + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); + + return factor > 0; + } + + private function tweenComplete():void { + _tweencount--; + + if (_tweencount == 0) { + + if (_loadTimer != null) + _loadTimer.start(); + + repositionPapers(); + } + + if (_tweencount < numPagesLoaded - 2 || _tweencount == 0) { + PaperVisible = true; + } + } + + private function reScaleComplete():void { + _tweencount--; + + if (_tweencount == 0) { + if (_displayContainer.numChildren > 0) { + _paperContainer.verticalScrollPosition = 0; + + if (_loadTimer != null) + _loadTimer.start(); + + repositionPapers(); + } + + if (_tweencount < numPagesLoaded - 2 || _tweencount == 0) { + PaperVisible = true; + } + } + } + + public function set Scale(s:String):void { + var diff:Number = _scale - new Number(s); + _scale = new Number(s); + } + + override protected function createChildren():void { + // Call the createChildren() method of the superclass. + super.createChildren(); + this.styleName = "viewerBackground"; + + // Bind events + //_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete); + addEventListener(Event.RESIZE, sizeChanged, false, 0, true); + systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler, false, 0, true); + + // Create a visible container for the swf + _swfContainer = new Canvas(); + _swfContainer.visible = false; + this.addChild(_swfContainer); + + // Create a timer to use for repainting + _repaintTimer = new Timer(5, 0); + _repaintTimer.addEventListener("timer", repaintHandler); + + createDisplayContainer(); + } + + private function onframeenter(event:Event):void { + if (!_dupImageClicked) { + return; + } + + if (_docLoader != null && _docLoader.IsSplit) + return; + + if (event.target.content != null) { + if (event.target.parent is DupImage && + event.target.content.currentFrame != (event.target.parent as DupImage).dupIndex + && _dupImageClicked) { + var np:int = event.target.content.currentFrame; + event.target.content.gotoAndStop((event.target.parent as DupImage).dupIndex); + gotoPage(np); + } + } + } + + private function updComplete(event:Event):void { + if (_scrollToPage > 0) { + _paperContainer.verticalScrollPosition = _pageList[_scrollToPage - 1].y; + //_paperContainer.horizontalScrollPosition = 0; + _scrollToPage = 0; + } + + repaint(); + //repositionPapers(); + } + + private function repaintHandler(e:Event):void { + if (_loadTimer != null) { + _loadTimer.reset(); + _loadTimer.start(); + } + + repositionPapers(); + _repaintTimer.stop(); + _repaintTimer.delay = 5; + } + + private function loadtimer(e:Event):void { + if (_loadTimer != null) + _loadTimer.stop(); + + repositionPapers(); + } + + private function bytesLoaded(event:Event):void { + event.target.loader.loaded = true; + + var bFound:Boolean = false; + + // Split up approach + if (_docLoader != null && _docLoader.IsSplit) { + event.target.loader.loading = false; + + if (event.target.loader.content != null && event.target.loader.content is MovieClip) { + event.target.loader.content.stop(); + } + + for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { + if (_docLoader.LoaderList[i].loading) { + bFound = true; + break; + } + } + + _frameLoadCount = numPages; + _bbusyloading = false; + _displayContainer.visible = true; + + if (!bFound) { + dispatchEvent(new PageLoadedEvent(PageLoadedEvent.PAGE_LOADED, event.target.loader.pageStartIndex)); + + if (_fitPageOnLoad && ((_paperContainer.height / _libMC.height) > 0)) { + FitMode = FitModeEnum.FITHEIGHT; + _fitPageOnLoad = false; + _scrollToPage = 1; + _pscale = _scale; + } + if (_fitWidthOnLoad && ((_paperContainer.width / _libMC.width) > 0)) { + FitMode = FitModeEnum.FITWIDTH; + _fitWidthOnLoad = false; + _scrollToPage = 1; + _pscale = _scale; + } + } + + repaint(); + } else { // normal file approach + if (event.target.loader.content != null) { + event.target.loader.content.stop(); + } + + if (!ProgressiveLoading || (ProgressiveLoading && _libMC.framesLoaded == _libMC.totalFrames)) { + for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { + if (!_docLoader.LoaderList[i].loaded && !(_docLoader.LoaderList[i].parent is DupImage)) { + _docLoader.LoaderList[i].unloadAndStop(true); + _docLoader.LoaderList[i].loadBytes(_inputBytes, StreamUtil.getExecutionContext()); + bFound = true; + break; + } + } + } + + if (!bFound) { + _bbusyloading = false; + if (_fitPageOnLoad) { + FitMode = FitModeEnum.FITHEIGHT; + _fitPageOnLoad = false; + _scrollToPage = 1; + _pscale = _scale; + } + if (_fitWidthOnLoad) { + FitMode = FitModeEnum.FITWIDTH; + _fitWidthOnLoad = false; + _scrollToPage = 1; + _pscale = _scale; + } + _displayContainer.visible = true; + + if (_libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded) { + dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED, numPages)); + _frameLoadCount = _libMC.framesLoaded; + } + } + } + } + + public function repositionPapers():void { + if (_docLoader == null) { + return; + } + + if (_docLoader.LoaderList == null || numPagesLoaded == 0) { + return; + } + + { + var loaderidx:int = 0; + var bFoundFirst:Boolean = false; + var _thumb:Bitmap; + var _thumbData:BitmapData; + var uloaderidx:int = 0; + var p:int = -1; + var pl:int = 0; + + for (var i:int = 0; i < _pageList.length; i++) { + if (ViewMode == ViewModeEnum.TILE) { + if (!bFoundFirst && ((i) * (_pageList[i].height + 6)) >= _paperContainer.verticalScrollPosition) { + bFoundFirst = true; + p = i + 1; + } + } + else if (ViewMode == ViewModeEnum.PORTRAIT) { + if (!bFoundFirst) { + var perH:int = 0; + if (_pageList.length > 1) { + var nowpH:Number = 0; + var nowP:Number = 0; + + while (_paperContainer.verticalScrollPosition + 1 > nowpH && nowP - 1 < _pageList.length) { + nowP++; + + if (nowP < _pageList.length) + nowpH += _pageList[nowP].y - _pageList[nowP - 1].y; + else if (nowP >= _pageList.length) + nowpH += _pageList[_pageList.length - 1].y - _pageList[_pageList.length - 2].y; + } + + if (0 < nowP < 0.5) + p = 1; + else if (nowP >= (_pageList.length - 0.5)) + p = _pageList.length; + else { + p = Math.round(nowP); + if (_pageList.length > p - 1 && _paperContainer.verticalScrollPosition < _pageList[p - 1].y && p != _pageList.length) { + p -= 1; + } + } + bFoundFirst = true; + } + else { + bFoundFirst = true; + p = 1; + } + } + } + + if (p > numPages) + return; + + if (UsingExtViewMode) { + if (currPage != CurrExtViewMode.currentPage) + dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED, CurrExtViewMode.currentPage)); + + p = CurrExtViewMode.currentPage; + currPage = p; + } + + if (p > 0 && p != _currPage) { + currPage = p; + dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED, p)); + } + + if (_libMC != null && checkIsVisible(i)) { + if (_pageList[i].numChildren < 4) { + if (ViewMode == ViewModeEnum.PORTRAIT) { + + if (_docLoader.IsSplit) + uloaderidx = finduloaderIdx(_pageList[i].dupIndex); + + if (!_docLoader.IsSplit || uloaderidx == -1) + uloaderidx = (i == _pageList.length - 1 && loaderidx + 3 < _docLoader.LoaderList.length) ? loaderidx + 3 : (loaderidx < _docLoader.LoaderList.length) ? loaderidx : 0; + + if (!_docLoader.IsSplit) { + if (!_bbusyloading && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0) { + if (numPagesLoaded >= _pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content == null || (_docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].content.framesLoaded < _pageList[i].dupIndex)) { + _bbusyloading = true; + _docLoader.LoaderList[uloaderidx].unloadAndStop(true); + _docLoader.LoaderList[uloaderidx].loadBytes(_inputBytes, StreamUtil.getExecutionContext()); + flash.utils.setTimeout(repositionPapers, 200); + } + } + + if ((i < 2 || _pageList[i].numChildren == 0 || _pageList[i].loadedIndex != _pageList[i].dupIndex || (_pageList[i] != null && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].content.currentFrame != _pageList[i].dupIndex)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null) { + if (numPagesLoaded >= _pageList[i].dupIndex) { + _docLoader.LoaderList[uloaderidx].content.gotoAndStop(_pageList[i].dupIndex); + _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); + _pageList[i].loadedIndex = _pageList[i].dupIndex; + /* + if(_libMC.width*_scale>0&&_libMC.height*_scale>0){ + _libMC.gotoAndStop(_pageList[i].dupIndex); + _thumbData = new BitmapData(_libMC.width*_scale, _libMC.height*_scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _thumbData.draw(_libMC,new Matrix(_scale, 0, 0, _scale),null,null,null,true); + } */ + } + } + } + + if (_docLoader.IsSplit) { + if (!_bbusyloading && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0) { + if (_docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].pageStartIndex != _pageList[i].dupIndex && !_loadTimer.running && !_docLoader.LoaderList[uloaderidx].loading) { + dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING, _pageList[i].dupIndex)); + _pageList[i].resetPage(_libMC.width, _libMC.height, _scale, true); + _docLoader.LoaderList[uloaderidx].unloadAndStop(true); + _docLoader.LoaderList[uloaderidx].loaded = false; + _docLoader.LoaderList[uloaderidx].loading = true; + + Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _pageList[i].dupIndex)), _secretKey, function(e:Event):void { + + try { + _docLoader.LoaderList[uloaderidx].loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); + } catch(err:IOErrorEvent) { + } + + }, onLoadProgress); + + + _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; + repaint(); + + } + } + + if ((_pageList[i].numChildren == 0 || (_pageList[i] != null && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].loaded && _docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex) { + if (numPagesLoaded >= _pageList[i].dupIndex || true) { + if (_docLoader.LoaderList[uloaderidx].parent != null) + _docLoader.LoaderList[uloaderidx].parent.removeChild(_docLoader.LoaderList[uloaderidx]); + + _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); + _pageList[i].loadedIndex = _pageList[i].dupIndex; + + if ((_performSearchOnPageLoad && _pendingSearchPage == _pageList[i].dupIndex) || (SearchMatchAll && prevSearchText.length > 0)) { + _performSearchOnPageLoad = false; + searchTextByService(prevSearchText) + } + } + } + } + + } else if (ViewMode == ViewModeEnum.TILE && _pageList[i].source == null && (numPagesLoaded >= _pageList[i].dupIndex || _docLoader.IsSplit)) { + if (!_docLoader.IsSplit) { + _libMC.gotoAndStop(_pageList[i].dupIndex); + _thumbData = new BitmapData(_libMC.width * _scale, _libMC.height * _scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _thumbData.draw(_libMC.getDocument(), new Matrix(_scale, 0, 0, _scale), null, null, null, true); + } else { + + if (!_bbusyloading && !_loadTimer.running && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0 && !_docLoader.LoaderList[uloaderidx].loading) { + dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING, _pageList[i].dupIndex)); + _docLoader.LoaderList[uloaderidx].loaded = false; + _docLoader.LoaderList[uloaderidx].loading = true; + _pageList[i].resetPage(_libMC.width, _libMC.height, _scale, true); + + Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _pageList[i].dupIndex)), _secretKey, function(e:Event):void { + try { + _docLoader.LoaderList[uloaderidx].loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); + } catch(err:IOErrorEvent) { + } + }, onLoadProgress); + + _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; + repaint(); + + } + + if (_docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex && _pageList[i].loadedIndex != _pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx].content != null) { + _thumbData = new BitmapData(_docLoader.LoaderList[uloaderidx].width * _scale, _docLoader.LoaderList[uloaderidx].height * _scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _pageList[i].loadedIndex = _pageList[i].dupIndex; + _thumbData.draw(_docLoader.LoaderList[uloaderidx], new Matrix(_scale, 0, 0, _scale), null, null, null, true); + } + } + + if (_pluginList != null) { + for (pl = 0; pl < _pluginList.length; pl++) { + _pluginList[pl].drawSelf(i, _thumbData, _scale); + } + } + } + } + + if (UsingExtViewMode) { + CurrExtViewMode.renderPage(i); + CurrExtViewMode.renderSelection(i, _selectionMarker); + } + + if ((_viewMode == ViewModeEnum.PORTRAIT) && _selectionMarker != null) { + if (i + 1 == searchPageIndex && _selectionMarker.parent != _pageList[i]) { + _pageList[i].addChildAt(_selectionMarker, _pageList[i].numChildren); + } else if (i + 1 == searchPageIndex && _selectionMarker.parent == _pageList[i]) { + _pageList[i].setChildIndex(_selectionMarker, _pageList[i].numChildren - 1); + } + } + + if (_viewMode != ViewModeEnum.TILE) { + if (_pluginList != null) { + for (pl = 0; pl < _pluginList.length; pl++) { + _pluginList[pl].drawSelf(i, _pageList[i], _scale); + } + } + } + + if (_viewMode != ViewModeEnum.TILE && !UsingExtViewMode && _markList[i] != null) { + if (_markList[i].parent != _pageList[i]) { + _pageList[i].addChildAt(_markList[i], _pageList[i].numChildren); + } else { + _pageList[i].setChildIndex(_markList[i], _pageList[i].numChildren - 1); + } + } + + if (UsingExtViewMode && _markList[i] != null) { + CurrExtViewMode.renderMark(_markList[i], i); + } + + loaderidx++; + } else { + if (_pageList[i].numChildren > 0 || _pageList[i].source != null) { + _pageList[i].source = null; + + if (_tweencount == 0) + _pageList[i].resetPage(_libMC.width, _libMC.height, _scale); + else + _pageList[i].removeAllChildren(); + + _pageList[i].loadedIndex = -1; + } + } + } + } + } + + private function padString(_str:String, _n:Number, _pStr:String):String { + var _rtn:String = _str; + if ((_pStr == null) || (_pStr.length < 1)) { + _pStr = " "; + } + + if (_str.length < _n) { + var _s:String = ""; + for (var i:Number = 0; i < (_n - _str.length); i++) { + _s += _pStr; + } + _rtn = _s + _str; + } + + return _rtn; + } + + private function finduloaderIdx(idx:int):int { + for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { + if (_docLoader.LoaderList[i].pageStartIndex == idx) + return i; + } + for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { + if (!checkIsVisible(_docLoader.LoaderList[i].pageStartIndex)) + return i; + } + return -1; + } + + public function repaint():void { + _repaintTimer.reset(); + _repaintTimer.start(); + } + + private function checkIsVisible(pageIndex:int):Boolean { + try { + if (ViewMode == ViewModeEnum.TILE) { + return _pageList[pageIndex].parent.y + _pageList[pageIndex].height >= _paperContainer.verticalScrollPosition && + (_pageList[pageIndex].parent.y - _pageList[pageIndex].height) < (_paperContainer.verticalScrollPosition + _paperContainer.height); + } + else if (!UsingExtViewMode) { + if (_paperContainer.height <= 0) + return false; + + return (_pageList[pageIndex].y + (_pageList[pageIndex].getScaledHeight() + 6)) >= _paperContainer.verticalScrollPosition && + (_pageList[pageIndex].y - (_pageList[pageIndex].getScaledHeight() + 6)) < (_paperContainer.verticalScrollPosition + _paperContainer.height); + } + + if (UsingExtViewMode) + return CurrExtViewMode.checkIsVisible(pageIndex); + + } catch(e:Error) { + return false; + } + return false; + } + + public function createDisplayContainer():void { + + +// if (_skinImgDo != null && _skinImgDo.parent == this) { +// removeChild(_skinImgDo); +// _skinImgDo.removeEventListener(MouseEvent.MOUSE_OVER, skinMouseOver); +// _skinImgDo.removeEventListener(MouseEvent.MOUSE_OUT, skinMouseOut); +// _skinImgDo.removeEventListener(MouseEvent.MOUSE_DOWN, skinMouseDown); +// } + +// _skinImgDo = new Image(); +// _skinImgDo.source = _skinImg; +// _skinImgDo.x = this.width - _skinImg.width - 27; +// _skinImgDo.y = this.height - _skinImg.height - 10; +// _skinImgDo.addEventListener(MouseEvent.MOUSE_OVER, skinMouseOver, false, 0, true); +// _skinImgDo.addEventListener(MouseEvent.MOUSE_OUT, skinMouseOut, false, 0, true); +// _skinImgDo.addEventListener(MouseEvent.MOUSE_DOWN, skinMouseDown, false, 0, true); +// _skinImgDo.buttonMode = true; +// addChild(_skinImgDo); + + // Add the swf to the invisible container. + _swfContainer.removeAllChildren(); + var uic:UIComponent = new UIComponent(); + _swfContainer.addChild(uic); + + if (_docLoader != null && _docLoader.DocumentContainer != null) + uic.addChild(_docLoader.DocumentContainer); + + if (_paperContainer != null && _paperContainer.parent == this) { + removeChild(_paperContainer); + _paperContainer.removeEventListener(FlexEvent.UPDATE_COMPLETE, updComplete); + + _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); + } + + _paperContainer = new ZoomCanvas(); + _paperContainer.percentHeight = 100; + _paperContainer.percentWidth = 100; + _paperContainer.addEventListener(FlexEvent.UPDATE_COMPLETE, updComplete, false, 0, true); + _paperContainer.x = (ViewMode == ViewModeEnum.PORTRAIT || ViewMode == ViewModeEnum.TILE) ? 2.5 : 0; + _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler, false, 0, true); + _paperContainer.setStyle("horizontalGap", 1); + _paperContainer.setStyle("verticalGap", 0); + + //addChildAt(_paperContainer, getChildIndex(_skinImgDo) - 1); + addChild(_paperContainer); + try { + new flash.net.LocalConnection().connect('devaldiGCdummy'); + new flash.net.LocalConnection().connect('devaldiGCdummy'); + } catch (e:*) { + } + + try { + flash.system.System.gc(); + } catch (e:*) { + } + + if (_paperContainer.numChildren > 0) { + _paperContainer.removeAllChildren(); + } + + deleteDisplayContainer(); + + if (_viewMode == ViewModeEnum.TILE) { + _displayContainer = new FlowBox(); + _displayContainer.setStyle("horizontalAlign", "left"); + _paperContainer.horizontalScrollPolicy = "off"; + _scale = 0.243; + _paperContainer.addChild(_displayContainer); + _paperContainer.childrenDoDrag = true; + _initialized = true; + } + else if (UsingExtViewMode) { + _initialized = CurrExtViewMode.initComponent(this); + } + else { + _displayContainer = new FlowVBox(); + _displayContainer.setStyle("horizontalAlign", "center"); + _paperContainer.addChild(_displayContainer); + _paperContainer.childrenDoDrag = true; + _initialized = true; + } + + _displayContainer.verticalScrollPolicy = "off"; + _displayContainer.horizontalScrollPolicy = "off"; + _displayContainer.setStyle("verticalAlign", "center"); + _displayContainer.percentHeight = 100; + _displayContainer.percentWidth = (ViewMode == ViewModeEnum.PORTRAIT) ? 96 : 100; + _displayContainer.useHandCursor = true; + _displayContainer.addEventListener(MouseEvent.ROLL_OVER, displayContainerrolloverHandler, false, 0, true); + _displayContainer.addEventListener(MouseEvent.ROLL_OUT, displayContainerrolloutHandler, false, 0, true); + _displayContainer.addEventListener(MouseEvent.MOUSE_DOWN, displayContainerMouseDownHandler, false, 0, true); + _displayContainer.addEventListener(MouseEvent.MOUSE_UP, displayContainerMouseUpHandler, false, 0, true); + _displayContainer.addEventListener(MouseEvent.DOUBLE_CLICK, displayContainerDoubleClickHandler, false, 0, true); + //_displayContainer.mouseChildren = false; + _displayContainer.doubleClickEnabled = true; + } + + private function displayContainerrolloverHandler(event:MouseEvent):void { + + if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { + if (TextSelectEnabled && CursorsEnabled) { + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + } else if (CursorsEnabled) { + resetCursor(); + } + } + } + + private function displayContainerMouseUpHandler(event:MouseEvent):void { + if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { + + if (CursorsEnabled) + CursorManager.removeCursor(_grabbingCursorID); + + if (TextSelectEnabled && CursorsEnabled) { + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + } else if (CursorsEnabled && !(event.target is IFlexPaperPluginControl) || (event.target.parent != null && event.target.parent.parent != null && event.target.parent.parent is IFlexPaperPluginControl)) { + resetCursor(); + } + } + } + + private function displayContainerDoubleClickHandler(event:MouseEvent):void { + if (TextSelectEnabled) { + return; + } + if (ViewMode == ViewModeEnum.PORTRAIT) + FitMode = (FitMode == FitModeEnum.FITWIDTH) ? FitModeEnum.FITHEIGHT : FitModeEnum.FITWIDTH; + + if (UsingExtViewMode) + CurrExtViewMode.handleDoubleClick(event); + } + + private function displayContainerMouseDownHandler(event:MouseEvent):void { + if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { + + if (CursorsEnabled) + CursorManager.removeCursor(_grabCursorID); + + if (TextSelectEnabled && CursorsEnabled) { + _grabbingCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + } else if (CursorsEnabled) { + _grabbingCursorID = CursorManager.setCursor(MenuIcons.GRABBING); + } + } + + if (UsingExtViewMode) + CurrExtViewMode.handleMouseDown(event); + } + + private function displayContainerrolloutHandler(event:Event):void { + if (CursorsEnabled) + CursorManager.removeAllCursors(); + } + + private function wheelHandler(evt:MouseEvent):void { + _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); + + var t:Timer = new Timer(1, 1); + t.addEventListener("timer", addMouseScrollListener, false, 0, true); + t.start(); + + _paperContainer.dispatchEvent(evt.clone()); + } + + private function addMouseScrollListener(e:Event):void { + _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler, false, 0, true); + } + + private function keyboardHandler(event:KeyboardEvent):void { + if (event.keyCode == Keyboard.DOWN) { + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 10; + } + if (event.keyCode == Keyboard.UP) { + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 10; + } + if (event.keyCode == Keyboard.PAGE_DOWN) { + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 300; + } + if (event.keyCode == Keyboard.PAGE_UP) { + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 300; + } + if (event.keyCode == Keyboard.HOME) { + _paperContainer.verticalScrollPosition = 0; + } + if (event.keyCode == Keyboard.END) { + _paperContainer.verticalScrollPosition = _paperContainer.maxVerticalScrollPosition; + } + } + + private function sizeChanged(evt:Event):void { +// _skinImgDo.source = _skinImg; +// _skinImgDo.x = this.width - _skinImg.width - 27; +// _skinImgDo.y = this.height - _skinImg.height - 10; + } + + private function skinMouseOver(evt:MouseEvent):void { +// _skinImgDo.addChild(_skinImgc); + } + + private function skinMouseOut(evt:MouseEvent):void { +// if (_skinImgc.parent == _skinImgDo) { +// _skinImgDo.removeChild(_skinImgc); +// } + } + + private function skinMouseDown(evt:MouseEvent):void { + //dispatchEvent(new Event("onLogoClicked")); + } + + override protected function commitProperties():void { + super.commitProperties(); + + if (_swfFileChanged && _swfFile != null && _swfFile.length > 0) { // handler for when the Swf file has changed. + + dispatchEvent(new Event("onDocumentLoading")); + + _swfFileChanged = false; + } + } + + private function resizeMc(mc:MovieClip, maxW:Number, maxH:Number = 0, constrainProportions:Boolean = true):void { + maxH = maxH == 0 ? maxW : maxH; + mc.width = maxW; + mc.height = maxH; + if (constrainProportions) { + mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; + } + } + + private function onLoadProgress(event:ProgressEvent):void { + var e:ProgressEvent = new ProgressEvent("onLoadingProgress") + e.bytesTotal = event.bytesTotal; + e.bytesLoaded = event.bytesLoaded; + dispatchEvent(e); + } + + private function onDocumentLoadedErrorHandler(event:Event):void { + dispatchEvent(event); + } + + + private function swfComplete(event:SwfLoadedEvent):void { + if (!ProgressiveLoading) { + + try { + if (event.swfObject.content != null && (event.swfObject.content is MovieClip || event.swfObject.content is Bitmap)) { + _libMC = new SwfDocument(event.swfObject.content as DisplayObject); + } + DupImage.paperSource = _libMC.getDocument(); + } catch(e:Error) { + + if (!_docLoader.Resigned) { + _docLoader.signFileHeader(_docLoader.InputBytes); + return; + } + } + + if (!_secretKey && (_libMC == null || (event.swfObject != null && event.swfObject.content != null && event.swfObject.content is AVM1Movie)) && !_docLoader.Resigned) { + + _docLoader.signFileHeader(_docLoader.InputBytes); + + return; + } + + _inputBytes = _docLoader.InputBytes; + + if (_libMC.height > 0 && _docLoader.LoaderList == null) { + createLoaderList(); + } + + if (!_docLoader.IsSplit) + numPages = _libMC.totalFrames; + + _swfLoaded = true + _libMC.getDocument().cacheAsBitmap = true; + _libMC.getDocument().opaqueBackground = 0xFFFFFF; + reCreateAllPages(); + + _bbusyloading = false; + repositionPapers(); + //dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED,numPages)); + } else { + if (event.swfObject.content != null) { + var mobj:Object = event.swfObject.content; + var firstLoad:Boolean = false; + + if (mobj is AVM1Movie || _loaderptr != null) { + _inputBytes = _docLoader.InputBytes; + + if (_loaderptr == null) { + _docLoader.postProcessBytes(_inputBytes); + _loaderptr = new Loader(); + _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete, false, 0, true); + } + + _docLoader.signFileHeader(_inputBytes, _loaderptr); + _loaderptr.unloadAndStop(true); + _loaderptr.loadBytes(_inputBytes, StreamUtil.getExecutionContext()); + } + + if (mobj is MovieClip) { + _libMC = new SwfDocument(mobj as MovieClip); + _libMC.getDocument().cacheAsBitmap = true; + _libMC.getDocument().opaqueBackground = 0xFFFFFF; + + if (_libMC.height > 0 && _docLoader.LoaderList == null) { + createLoaderList(); + } + DupImage.paperSource = _libMC.getDocument(); + + if (!_docLoader.IsSplit) + numPages = _libMC.totalFrames; + + firstLoad = _pageList == null || (_pageList.length == 0 && numPages > 0); + + if (_loaderptr == null) { + _inputBytes = _docLoader.InputBytes; + } else { + _inputBytes = _loaderptr.contentLoaderInfo.bytes; + } + + if (_libMC.framesLoaded > 0) + addInLoadedPages(); + + flash.utils.setTimeout(function():void { + try { + var bDocLoaded:Boolean = (_libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded); + + if (_libMC.framesLoaded > _frameLoadCount) { + repositionPapers(); + if (_docLoader.LoaderList.length > 0 && _viewMode == ViewModeEnum.PORTRAIT) { + _bbusyloading = true; + _docLoader.LoaderList[_docLoader.LoaderList.length - 1].unloadAndStop(true); + _docLoader.LoaderList[_docLoader.LoaderList.length - 1].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); + } + _frameLoadCount = _libMC.framesLoaded; + } + + if (bDocLoaded) + dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED, numPages)); + } catch (e:*) { + } + }, 500); + + + _bbusyloading = false; + _swfLoaded = true + } + } + } + } + + private function deleteDisplayContainer():void { + if (_displayContainer != null) { + _displayContainer.removeAllChildren(); + _displayContainer.removeEventListener(MouseEvent.ROLL_OVER, displayContainerrolloverHandler); + _displayContainer.removeEventListener(MouseEvent.ROLL_OUT, displayContainerrolloutHandler); + _displayContainer.removeEventListener(MouseEvent.MOUSE_DOWN, displayContainerMouseDownHandler); + _displayContainer.removeEventListener(MouseEvent.MOUSE_UP, displayContainerMouseUpHandler); + _displayContainer.removeEventListener(MouseEvent.DOUBLE_CLICK, displayContainerDoubleClickHandler); + } + } + + private function deleteLoaderList():void { + if (_docLoader == null) { + return; + } + if (_docLoader.LoaderList != null) { + for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { + if (_docLoader.LoaderList[i].parent != null) { + _docLoader.LoaderList[i].parent.removeChild(_docLoader.LoaderList[i]); + } + + if (_docLoader.LoaderList[i].contentLoaderInfo != null) { + _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(Event.COMPLETE, bytesLoaded); + _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, docLoaderIOErrorListener); + } + + _docLoader.LoaderList[i].removeEventListener(Event.ENTER_FRAME, onframeenter); + _docLoader.LoaderList[i].unloadAndStop(true); + + delete(_docLoader.LoaderList[i]); + _docLoader.LoaderList[i] = null; + } + } + + _docLoader.LoaderList = null; + } + + public function deleteSelectionMarker():void { + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + + _selectionMarker = null; + } + } + + private function deleteLibMC():void { + if (_libMC != null) { + if (_libMC.parent != null && _libMC.parent is Loader) { + (_libMC.parent as Loader).unloadAndStop(true); + } + + _libMC = null; + } + } + + private function deleteLoaderPtr():void { + if (_loaderptr != null) { + if (_loaderptr.parent != null) { + _loaderptr.removeChild(_loaderptr); + } + + if (_loaderptr.contentLoaderInfo != null) { + _loaderptr.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); + } + + _loaderptr.unloadAndStop(true); + _loaderptr = null; + } + } + + private function clearPlugins():void { + if (_pluginList == null) { + return; + } + + for (var pl:int = 0; pl < _pluginList.length; pl++) { + _pluginList[pl].clear(); + } + } + + private function deletePageList():void { + if (_pageList != null) { + for (var pl:int = 0; pl < _pageList.length; pl++) { + + _pageList[pl].removeEventListener(MouseEvent.MOUSE_OVER, dupImageMoverHandler); + _pageList[pl].removeEventListener(MouseEvent.MOUSE_OUT, dupImageMoutHandler); + _pageList[pl].removeEventListener(MouseEvent.CLICK, dupImageClickHandler); + _pageList[pl].removeEventListener(MouseEvent.MOUSE_DOWN, textSelectorMouseDownHandler); + + if (_pageList[pl].parent != null) { + _pageList[pl].removeAllChildren(); + _pageList[pl].source = null; + _pageList[pl].parent.removeChild(_pageList[pl]); + } + + delete(_pageList[pl]); + _pageList[pl] = null; + } + } + + DupImage.paperSource = null; + + _pageList = null; + } + + private function deleteFLoader():void { + if (_docLoader != null) { + _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); + _docLoader.resetURLStream(); + } + + /*if(_loader!=null){ + _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); + _loader.unloadAndStop(true); + _loader = null; + }*/ + + //_docLoader = null; + + /*_loader = new Loader(); + if(!_loader.contentLoaderInfo.hasEventListener(Event.COMPLETE)) + _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete,false,0,true);*/ + } + + public function addInLoadedPages(recreate:Boolean = false):void { + if (recreate) { + _displayContainer.removeAllChildren(); + deletePageList(); + } + + if (_pageList == null || (_pageList != null && _pageList.length != numPages)) { + _pageList = new Array(numPages); + if (_markList == null) { + _markList = new Array(numPages); + } + + _displayContainer.visible = false; + _libMC.stop(); + + var w:Number = 0; + var h:Number = 0; + _libMC.gotoAndStop(1); + w = _libMC.width; + h = _libMC.height; + + for (var i:int = 0; i < numPages; i++) { + _libMC.gotoAndStop(i + 1); + createPaper(i + 1, (_libMC.width > 0) ? _libMC.width : w, (_libMC.height > 0) ? _libMC.height : h); + } + + addPages(); + + if (_pluginList != null) { + for (var p:int = 0; p < _pluginList.length; p++) { + _pluginList[p].init(); + } + } + + //if(_fitWidthOnLoad){_scale = getFitWidthFactor();} + //if(_fitPageOnLoad){_scale = getFitHeightFactor();} + } + + flash.utils.setTimeout(repositionPapers, 500); + } + + public function reCreateAllPages():void { + if (!_swfLoaded) { + return; + } + + _displayContainer.visible = false; + _displayContainer.removeAllChildren(); + + deletePageList(); + _pageList = new Array(numPages); + if (_markList == null) { + _markList = new Array(numPages); + } + + if (_pluginList != null) { + for (var p:int = 0; p < _pluginList.length; p++) { + _pluginList[p].init(); + } + } + + _libMC.stop(); + + var w:Number = 0; + var h:Number = 0; + _libMC.gotoAndStop(1); + w = _libMC.width; + h = _libMC.height; + + for (var i:int = 0; i < numPages; i++) { + _libMC.gotoAndStop(i + 1); + createPaper(i + 1, (_libMC.width > 0) ? _libMC.width : w, (_libMC.height > 0) ? _libMC.height : h); + } + + addPages(); + + // kick off the first page to load + if (!_docLoader.IsSplit) { + if (_docLoader.LoaderList.length > 0) { + _bbusyloading = true; + _docLoader.LoaderList[0].unloadAndStop(true); + _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); + } + } else { + if (_docLoader.LoaderList.length > 0 && (_viewMode == ViewModeEnum.PORTRAIT) && _libMC.loaderInfo != null && _libMC.loaderInfo.bytes != null) { + _bbusyloading = true; + _docLoader.LoaderList[0].pageStartIndex = 1; + _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); + } + } + + if (_docLoader.LoaderList.length > 0 && UsingExtViewMode) { + CurrExtViewMode.initOnLoading(); + } + } + + private function createLoaderList():void { + _docLoader.LoaderList = new Array(Math.round(getCalculatedHeight(_paperContainer) / (_libMC.height * _minZoomSize)) + (_docLoader.IsSplit) ? 5 : 1); + + if (UsingExtViewMode && CurrExtViewMode.loaderListLength > _docLoader.LoaderList.length) + _docLoader.LoaderList = new Array(CurrExtViewMode.loaderListLength); + + { + for (var li:int = 0; li < _docLoader.LoaderList.length; li++) { + _docLoader.LoaderList[li] = new DupLoader(); + _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(Event.COMPLETE, bytesLoaded, false, 0, true); + _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, docLoaderIOErrorListener); + _docLoader.LoaderList[li].addEventListener(Event.ENTER_FRAME, onframeenter, false, 0, true); + } + } + } + + private function docLoaderIOErrorListener(e:IOErrorEvent):void { + if (_docLoader != null && _docLoader.IsSplit) { + dispatchEvent(new ErrorLoadingPageEvent(ErrorLoadingPageEvent.ERROR_LOADING_PAGE, e.target.pageStartIndex)); + } + } + + private function getCalculatedHeight(obj:DisplayObject):Number { + var pHeight:Number = 0; + var oPercHeight:Number = 0; + + pHeight = obj.height; + if (pHeight > 0) { + return pHeight; + } + if ((obj as Container).percentHeight > 0) { + oPercHeight = (obj as Container).percentHeight; + } + + while (obj.parent != null) { + if (obj.parent.height > 0) { + pHeight = obj.parent.height * (oPercHeight / 100); + break; + } + obj = obj.parent; + } + + return pHeight; + } + + public var snap:TextSnapshot; + private var searchIndex:int = -1; + private var searchPageIndex:int = -1; + private var _selectionMarker:ShapeMarker; + private var prevSearchText:String = ""; + private var prevYsave:Number = -1; + private var _markList:Array; + private var prevSearchIndexList:Array; + + public function get SearchPageIndex():int { + return searchPageIndex; + } + + public function set SearchPageIndex(s:int):void { + searchPageIndex = s; + } + + private var _searchExtracts:Array; + + public function searchTextByService(text:String):void { + if (prevSearchText != text) { + _searchExtracts = new Array(numPages); + searchPageIndex = -1; + prevSearchText = text; + searchIndex = -1; + prevSearchIndexList = new Array(); + } + + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + } + + if (searchPageIndex == -1) { + searchPageIndex = currPage; + } + + if (_searchExtracts[searchPageIndex - 1] == null && searchPageIndex != currPage) { + var serve:HTTPService = new HTTPService(); + var url = SearchServiceUrl; + url = TextMapUtil.StringReplaceAll(url, "[page]", searchPageIndex.toString()) + url = TextMapUtil.StringReplaceAll(url, "[searchterm]", text) + url = encodeURI(url); + + serve.method = "GET"; + serve.url = url; + serve.resultFormat = "text"; + serve.addEventListener("result", searchByServiceResult); + serve.addEventListener(FaultEvent.FAULT, searchByServiceFault); + serve.send(); + } else { // perform actual search + if ((_searchExtracts[searchPageIndex - 1] != null && _searchExtracts[searchPageIndex - 1].length > 0 && Number(_searchExtracts[searchPageIndex - 1]) >= 0) || searchPageIndex == currPage) { + if (searchPageIndex != currPage) { + _performSearchOnPageLoad = true; + _pendingSearchPage = searchPageIndex; + gotoPage(searchPageIndex); + } + else { + snap = _pageList[searchPageIndex - 1].textSnapshot; + searchIndex = snap.findText((searchIndex == -1 ? 0 : searchIndex), adjustSearchTerm(text), false); + var tri:Array; + + if (searchIndex > 0) { // found a new match + _selectionMarker = new ShapeMarker(); + _selectionMarker.graphics.beginFill(0x0095f7, 0.3); + + tri = snap.getTextRunInfo(searchIndex, searchIndex + text.length - 1); + if (tri.length > 0) { + prevYsave = tri[0].matrix_ty; + drawCurrentSelection(0x0095f7, _selectionMarker, tri); + } + + if (prevYsave > 0) { + _selectionMarker.graphics.endFill(); + _adjGotoPage = (ViewMode == ViewModeEnum.PORTRAIT) ? (prevYsave) * _scale - 50 : 0; + gotoPage(searchPageIndex); + } + + searchIndex = searchIndex + text.length; + } else { + if (searchPageIndex + 1 <= numPages) { + searchPageIndex++; + searchIndex = -1; + + searchTextByService(prevSearchText); + } else { + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + } + } else { + if (searchPageIndex + 1 <= numPages) { + searchPageIndex++; + searchIndex = -1; + + searchTextByService(prevSearchText); + } else { + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + } + } + + private function searchByServiceResult(evt:ResultEvent):void { + var textExtract:String = evt.result.toString(); + _searchExtracts[searchPageIndex - 1] = textExtract; + + searchTextByService(prevSearchText); + } + + private function searchByServiceFault(evt:FaultEvent):void { + dispatchEvent(new Event("onNoMoreSearchResults")); + } + + public function searchText(text:String, clearmarklist:Boolean = true):void { + if (text == null) { + return; + } + + if (text.length == 0) { + return; + } + text = text.toLowerCase(); + + if (_docLoader.IsSplit && SearchServiceUrl != null && SearchServiceUrl.length > 0) + return searchTextByService(text); + + var tri:Array; + + if (prevSearchText != text) { + searchIndex = -1; + prevSearchIndexList = new Array(); + prevSearchText = text; + + if (SearchMatchAll) { + var spi:int = 1; + var si:int = -1; + + if (clearmarklist) { + if (_markList != null) { + for (var i:int = 0; i < _markList.length; i++) { + if (_markList[i] != null && _markList[i].parent != null) { + _markList[i].parent.removeChild(_markList[i]); + } + } + } + + _markList = new Array(numPages); + } + + if (text.indexOf("|") > 0) { + var phrases:Array = text.split("|"); + for (var sf:int = 0; sf < phrases.length; sf++) { + searchText(phrases[sf], false); + } + + return; + } + + while ((spi - 1) < _libMC.framesLoaded) { + _libMC.gotoAndStop(spi); + snap = _libMC.textSnapshot; + si = snap.findText((si == -1 ? 0 : si), adjustSearchTerm(text), false); + //si = snap.getText(0,snap.charCount).toLowerCase().indexOf(text,(si==-1?0:si)); + //si = searchString(snap.getText(0,snap.charCount),text,si); + + if (si > 0) { + var sm:ShapeMarker = new ShapeMarker(); + sm.PageIndex = spi; + + tri = snap.getTextRunInfo(si, si + text.length - 1); + drawCurrentSelection(0x0095f7, sm, tri, false, 0.25); + + + if (_markList[spi - 1] == null) { + _markList[spi - 1] = new UIComponent(); + } + + _markList[spi - 1].addChild(sm); + + } + + if (si == -1) + spi++; + else + si++; + } + } + } + + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + } + + // start searching from the current page + if (searchPageIndex == -1) { + searchPageIndex = currPage; + } else { + var sio:Object = new Object(); + sio.searchIndex = searchIndex; + sio.searchPageIndex = searchPageIndex; + + prevSearchIndexList.push(sio); + searchIndex = searchIndex + text.length; + } + + _libMC.gotoAndStop(searchPageIndex); + + while ((searchPageIndex - 1) < numPagesLoaded) { + snap = _libMC.textSnapshot; + searchIndex = snap.findText((searchIndex == -1 ? 0 : searchIndex), adjustSearchTerm(text), false); + //searchIndex = TextMapUtil.checkUnicodeIntegrity(snap.getText(0,snap.charCount),text,_libMC).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); + //searchIndex = snap.getText(0,snap.charCount).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); + //searchIndex = searchString(snap.getText(0,snap.charCount),text,searchIndex); + + if (searchIndex > 0) { // found a new match + _selectionMarker = new ShapeMarker(); + _selectionMarker.graphics.beginFill(0x0095f7, 0.3); + + tri = snap.getTextRunInfo(searchIndex, searchIndex + text.length - 1); + if (tri.length > 0) { + prevYsave = tri[0].matrix_ty; + drawCurrentSelection(0x0095f7, _selectionMarker, tri); + } + + if (prevYsave > 0) { + _selectionMarker.graphics.endFill(); + _adjGotoPage = (ViewMode == ViewModeEnum.PORTRAIT) ? (prevYsave) * _scale - 50 : 0; + gotoPage(searchPageIndex); + break; + } + + } + + searchPageIndex++; + searchIndex = -1; + _libMC.gotoAndStop(searchPageIndex); + } + + if (searchIndex == -1) { // searched the end of the doc. + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + + public function nextSearchMatch(s:String):void { + if (s != prevSearchText) { + searchText(s); + } else { + searchIndex = searchIndex + prevSearchText.length; + searchText(prevSearchText); + } + } + + public function prevSearchMatch():void { + if (prevSearchText != null && prevSearchText.length > 0) { + prevSearchIndexList.pop(); + + var sio:Object = prevSearchIndexList.pop(); + if (sio != null) { + searchIndex = sio.searchIndex - 1; + searchPageIndex = sio.searchPageIndex; + searchText(prevSearchText); + } else { + searchIndex = 0; + searchPageIndex = 1; + searchText(prevSearchText); + } + } + } + + private function adjustSearchTerm(searchtxt:String):String { + if (ResourceManager.getInstance().localeChain[0] == 'he_IL') { + searchtxt = reverseString(searchtxt); + } + + return searchtxt; + } + + private function reverseString(string:String):String { + var reversed:String = new String(); + for (var i:int = string.length - 1; i >= 0; i--) + reversed += string.charAt(i); + return reversed; + } + + public function highlight(url:String):void { + var serve:HTTPService = new HTTPService(); + serve.method = "GET"; + serve.url = url; + serve.resultFormat = "e4x" + serve.addEventListener("result", highlightResult); + serve.send(); + } + + private function highlightResult(evt:ResultEvent):void { + try { + + for (var i:int = 0; i < _markList.length; i++) { + if (_markList[i] != null && _markList[i].parent != null) { + _markList[i].parent.removeChild(_markList[i]); + } + } + + _markList = new Array(numPages); + + var highlightXML:XML = new XML(evt.result); + var pg:Number = 0; + var pos:Number = -1; + var len:Number = -1; + var tri:Array; + var color:uint = 0x0095f7; + var text:String; + color = uint("0x" + String(highlightXML.Body.@color).substring(1, String(highlightXML.Body.@color).length)); + + for each (var item:XML in highlightXML.Body.Highlight.loc) { + pg = Number(item.@pg); + pos = Number(item.@pos); + len = Number(item.@len); + + _libMC.gotoAndStop(pg + 1); + snap = _libMC.textSnapshot; + + var sm:ShapeMarker = new ShapeMarker(); + sm.PageIndex = pg + 1; + + text = snap.getText(0, pos, false); + + for (var ci:int = 0; ci < text.length; ci++) { + if (text.charCodeAt(ci) > 10000) { + pos = pos - 1; + } + } + + tri = snap.getTextRunInfo(pos, pos + len); + + drawCurrentSelection(color, sm, tri, false, 0.25); + + if (_markList[pg] == null) { + _markList[pg] = new UIComponent(); + } + + _markList[pg].addChild(sm); + } + + repositionPapers(); + + } catch (e:*) { + } + } + + private function createPaper(index:int, w:Number, h:Number):void { + var di:DupImage = new DupImage(); + di.scaleX = di.scaleY = _scale; + di.dupIndex = index; + di.width = w; + di.height = h; + di.init(); + di.NeedsFitting = DocLoader.IsSplit; + di.RoleModelHeight = _libMC.height; + di.RoleModelWidth = _libMC.width; + //di.mouseChildren = false; + di.addEventListener(MouseEvent.MOUSE_OVER, dupImageMoverHandler, false, 0, true); + di.addEventListener(MouseEvent.MOUSE_OUT, dupImageMoutHandler, false, 0, true); + di.addEventListener(MouseEvent.CLICK, dupImageClickHandler, false, 0, true); + di.addEventListener(MouseEvent.MOUSE_DOWN, textSelectorMouseDownHandler, false, 0, true); + + if (_pluginList != null) + for (var pl:int = 0; pl < _pluginList.length; pl++) + _pluginList[pl].bindPaperEventHandler(di); + + _pageList[index - 1] = di; + _pageList[index - 1].resetPage(w, h, _scale); + } + + private function textSelectorMouseDownHandler(event:MouseEvent):void { + if (!TextSelectEnabled) { + return; + } + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + _selectionMarker = null; + } + + try { + if (!(event.target.content is MovieClip)) { + if (!(event.target is MovieClip)) { + return; + } else { + _selectionMc = (event.target as MovieClip); + } + } else { + _selectionMc = (event.target.content as MovieClip); + } + } catch (e:*) { + return; + } + + _currentlySelectedText = ""; + _firstHitIndex = -1; + _lastHitIndex = -1; + _currentSelectionPage = -1; + snap = _selectionMc.textSnapshot; + + systemManager.addEventListener( + MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true, 0, true); + + systemManager.addEventListener( + MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true, 0, true); + + systemManager.stage.removeEventListener( + Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); + } + + private var _firstHitIndex:int = -1; + private var _lastHitIndex:int = -1; + private var _currentlySelectedText:String = ""; + private var _tri:Array; + private var _currentSelectionPage:int = -1; + private var _selectionMc:MovieClip + private var _selecting:Boolean = false; + public static var DefaultMarkerColor:uint = 0xb5deff; + private var _markerColor:uint = 0xb5deff; + public static var DefaultSelectionColor:uint = 0x0095f7; + private var _selectionColor:uint = 0x0095f7; + + public function get MarkerColor():uint { + return _markerColor; + } + + public function set MarkerColor(c:uint):void { + _markerColor = c; + } + + public function get SelectionColor():uint { + return _selectionColor; + } + + public function set SelectionColor(c:uint):void { + _selectionColor = c; + } + + public function get CurrentSelectionPage():int { + return _currentSelectionPage; + } + + public function get FirstHitIndex():int { + return _firstHitIndex; + } + + public function get LastHitIndex():int { + return _lastHitIndex; + } + + public function get TextRunInfo():Array { + return _tri; + } + + public function set TextRunInfo(a:Array):void { + _tri = a; + } + + private function textSelectorMoveHandler(event:MouseEvent):void { + event.stopImmediatePropagation(); + + var hitIndex:int = snap.hitTestTextNearPos(event.target.parent.mouseX, event.target.parent.mouseY, 10) + ((_firstHitIndex == -1) ? 0 : 1); + + if (hitIndex == _lastHitIndex || hitIndex < 0) { + return; + } + if (!(event.target is DupLoader)) { + return; + } + + if (_firstHitIndex == -1) { + _firstHitIndex = hitIndex; + } + + if (_docLoader.IsSplit) + _currentSelectionPage = (_selectionMc.parent as DupLoader).pageStartIndex; + else + _currentSelectionPage = _selectionMc.currentFrame; + + snap.setSelectColor(_markerColor); + snap.setSelected(0, snap.charCount, false); + + if (_firstHitIndex <= hitIndex) { + snap.setSelected(_firstHitIndex, hitIndex, true); + } else { + snap.setSelected(hitIndex, _firstHitIndex, true); + } + + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + } + + if (_docLoader.IsSplit) + searchPageIndex = (_selectionMc.parent as DupLoader).pageStartIndex; + else + searchPageIndex = _selectionMc.currentFrame; + + _lastHitIndex = hitIndex; + } + + public function drawCurrentSelection(color:uint, shape:Sprite, tri:Array, strikeout:Boolean = false, alpha:Number = 0.3):void { + var ly:Number = -1; + var li:int; + var lx:int; + var miny:int = -1; + var minx:int = -1; + var maxy:int = -1; + var maxx:int = -1; + snap.setSelected(1, snap.charCount, false); + + shape.graphics.beginFill(color, (strikeout) ? 0.5 : alpha); + var rect_commands:Vector.; + rect_commands = new Vector.((tri.length) * 5, true); + + var rect_coords:Vector.; + rect_coords = new Vector.((tri.length) * 10, true); + + for (var i:int = 0; i < tri.length - 1; i++) { + if (miny == -1 || miny > tri[i].corner1y) { + miny = tri[i].corner1y; + } + if (minx == -1 || minx > tri[li].corner3x) { + minx = tri[li].corner3x; + } + if (maxy == -1 || maxy < tri[i].corner3y) { + maxy = tri[i].corner3y; + } + if (maxx == -1 || maxx < tri[i].corner1x) { + maxx = tri[i].corner1x; + } + + if (ly == -1) { + ly = tri[i].corner1y; + li = 0; + } + + rect_commands[i * 5] = 1; + rect_commands[i * 5 + 1] = 2; + rect_commands[i * 5 + 2] = 2; + rect_commands[i * 5 + 3] = 2; + rect_commands[i * 5 + 4] = 2; + + rect_coords[i * 10] = tri[li].corner3x; + rect_coords[i * 10 + 1] = tri[i].corner1y + (strikeout ? (tri[i].corner3y - tri[i].corner1y) / 3 : 0); + + rect_coords[i * 10 + 5] = rect_coords[i * 10 + 1] + (tri[i].corner3y - tri[i].corner1y) / ((strikeout) ? 5 : 1); //h + + if (i != tri.length - 2 && tri[i].corner1x > tri[li].corner3x) + rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[i].corner1x - tri[li].corner3x; + else if (i == tri.length - 2 && tri[i + 1].corner1x > tri[li].corner3x) + rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[i + 1].corner1x - tri[li].corner3x; + else if (i == tri.length - 2 && tri[i + 1].corner1x < tri[li].corner3x) { + rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[li].corner1x - tri[li].corner3x; + rect_coords[i * 10] = tri[li].corner3x; + + /* add an extra struct for the last char*/ + rect_commands[(i + 1) * 5] = 1; + rect_commands[(i + 1) * 5 + 1] = 2; + rect_commands[(i + 1) * 5 + 2] = 2; + rect_commands[(i + 1) * 5 + 3] = 2; + rect_commands[(i + 1) * 5 + 4] = 2; + + rect_coords[(i + 1) * 10] = tri[(i + 1)].corner3x; + rect_coords[(i + 1) * 10 + 1] = tri[(i + 1)].corner1y; + rect_coords[(i + 1) * 10 + 2] = rect_coords[(i + 1) * 10] + tri[i + 1].corner1x - tri[i + 1].corner3x; + rect_coords[(i + 1) * 10 + 3] = rect_coords[(i + 1) * 10 + 1]; + rect_coords[(i + 1) * 10 + 4] = rect_coords[(i + 1) * 10 + 2]; + rect_coords[(i + 1) * 10 + 5] = rect_coords[(i + 1) * 10 + 1] + tri[i + 1].corner3y - tri[i + 1].corner1y; + rect_coords[(i + 1) * 10 + 6] = rect_coords[(i + 1) * 10]; + rect_coords[(i + 1) * 10 + 7] = rect_coords[(i + 1) * 10 + 5]; + rect_coords[(i + 1) * 10 + 8] = rect_coords[(i + 1) * 10]; + rect_coords[(i + 1) * 10 + 9] = rect_coords[(i + 1) * 10 + 1]; + } + + rect_coords[i * 10 + 3] = rect_coords[i * 10 + 1]; + rect_coords[i * 10 + 4] = rect_coords[i * 10 + 2]; + rect_coords[i * 10 + 6] = rect_coords[i * 10]; + rect_coords[i * 10 + 7] = rect_coords[i * 10 + 5]; + rect_coords[i * 10 + 8] = rect_coords[i * 10]; + rect_coords[i * 10 + 9] = rect_coords[i * 10 + 1]; + + ly = tri[i + 1].corner1y; + lx = tri[i + 1].corner3x; + li = i + 1; + } + shape.graphics.drawPath(rect_commands, rect_coords, "nonZero"); + shape.graphics.endFill(); + + // draw a transparent box covering the whole area to increase hitTest accuracy on mousedown + shape.graphics.beginFill(0xffffff, 0); + shape.graphics.drawRect(minx, miny, maxx - minx, maxy - miny); + shape.graphics.endFill(); + } + + private function textSelectorMouseUpHandler(event:MouseEvent):void { + stopSelecting(); + } + + private function textSelectorMouseLeaveHandler(event:MouseEvent):void { + stopSelecting(); + } + + private function stopSelecting():void { + systemManager.removeEventListener( + MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true); + + systemManager.removeEventListener( + MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true); + + systemManager.stage.removeEventListener( + Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); + + var rev:int; + if (_firstHitIndex > _lastHitIndex) { + rev = _firstHitIndex; + _firstHitIndex = _lastHitIndex; + _lastHitIndex = rev; + } + + //var totaltext:String = snap.getText(0,snap.charCount,false); + + if (_firstHitIndex >= 0 && _lastHitIndex > 0) + _currentlySelectedText = snap.getText(_firstHitIndex, _lastHitIndex - 1, false); + else + _currentlySelectedText = ""; + + + if (_currentlySelectedText.length == 0 && _firstHitIndex >= 0 && _lastHitIndex > 0) { + _currentlySelectedText = snap.getText(_firstHitIndex, _lastHitIndex - 1, true); + } + + _currentlySelectedText = TextMapUtil.checkUnicodeIntegrity(_currentlySelectedText, null, _libMC); + + /* trace(_currentlySelectedText.charCodeAt(0)+"|"); + trace(_currentlySelectedText.charCodeAt(1)+"|"); + trace(_currentlySelectedText.charCodeAt(2)+"|"); + trace(_currentlySelectedText.charCodeAt(3)+"|"); + */ + + + _tri = snap.getTextRunInfo(_firstHitIndex, _lastHitIndex - 1); + + if (_currentSelectionPage > 0) { + if (_selectionMarker != null && _selectionMarker.parent != null) { + _selectionMarker.parent.removeChild(_selectionMarker); + } + + _selectionMarker = new ShapeMarker(); + _selectionMarker.PageIndex = _currentSelectionPage; + drawCurrentSelection(_selectionColor, _selectionMarker, _tri); + snap.setSelected(_firstHitIndex, _lastHitIndex, false); + _pageList[_currentSelectionPage - 1].addChildAt(_selectionMarker, _pageList[_selectionMc.currentFrame - 1].numChildren); + } + + dispatchEvent(new SelectionCreatedEvent(SelectionCreatedEvent.SELECTION_CREATED, _currentlySelectedText)); + + _selectionMc = null; + } + + private function dupImageClickHandler(event:MouseEvent):void { + stage.stageFocusRect = false; + stage.focus = event.target as InteractiveObject; + + if ((_viewMode == ViewModeEnum.TILE) && event.target != null && event.target is DupImage) { + ViewMode = 'Portrait'; + _scrollToPage = (event.target as DupImage).dupIndex; + } else { + _dupImageClicked = true; + var t:Timer = new Timer(100, 1); + t.addEventListener("timer", resetClickHandler, false, 0, true); + t.start(); + + if (event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("http") >= 0) { + dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, + (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("http")))); + } else if (event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("url:") >= 0) { + dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, + (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("url:")))); + } + + } + } + + private function resetClickHandler(e:Event):void { + _dupImageClicked = false; + } + + private function dupImageMoverHandler(event:MouseEvent):void { + + if (_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage) { + addGlowFilter(event.target as DupImage); + } else { + if (event.target is flash.display.SimpleButton || event.target is mx.core.SpriteAsset || (event.target is IFlexPaperPluginControl) || (event.target.parent != null && event.target.parent.parent != null && event.target.parent.parent is IFlexPaperPluginControl)) { + CursorManager.removeAllCursors(); + } else { + if (TextSelectEnabled && CursorsEnabled) { + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + } else if (CursorsEnabled) { + resetCursor(); + } + } + } + } + + public function resetCursor():void { + if (CursorsEnabled) + _grabCursorID = CursorManager.setCursor(MenuIcons.GRAB); + } + + private function dupImageMoutHandler(event:MouseEvent):void { + if (_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage) { + (event.target as DupImage).filters = null; + (event.target as DupImage).addDropShadow(); + } + } + + private function addPages():void { + for (var pi:int = 0; pi < _pageList.length; pi++) { + if (!UsingExtViewMode) + _displayContainer.addChild(_pageList[pi]); + else + CurrExtViewMode.addChild(pi, _pageList[pi]); + } + } + + private var _splitpj:PrintJob; + private var _splitpjoptions:PrintJobOptions = new PrintJobOptions(); + private var _splitpjloading:Boolean = false; + private var _splitpjprinted:int = 0; + private var _splitpageNumList:Array; + + private function printSplitPaper(start:Boolean = false, range:String = ""):void { + if (start) { + _splitpj = new PrintJob(); + _loaderptr = new Loader(); + _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, printSplitPaperLoaded, false, 0, true); + + if (range.length > 0) { + if (range == "Current") { + _splitpageNumList = new Array(); + _splitpageNumList[currPage] = true; + } + else { + _splitpageNumList = range.split(","); + for (var i:int = 0; i < _splitpageNumList.length; i++) { + if (_splitpageNumList[i].toString().indexOf("-") > -1) { + var rs:int = Number(_splitpageNumList[i].toString().substr(0, _splitpageNumList[i].toString().indexOf("-"))); + var re:int = Number(_splitpageNumList[i].toString().substr(_splitpageNumList[i].toString().indexOf("-") + 1)); + for (var irs:int = rs; irs < re + 1; irs++) { + _splitpageNumList[irs] = true; + } + } else { + _splitpageNumList[int(Number(_splitpageNumList[i].toString()))] = true; + } + } + } + } + + _splitpj.start(); + } + + while (_splitpjprinted < numPages) { + if (!_splitpjloading) { + if (_splitpageNumList == null || (_splitpageNumList != null && _splitpageNumList[_splitpjprinted + 1] != null)) { + _splitpjloading = true; + Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _splitpjprinted + 1)), _secretKey, function(e:Event):void { + _loaderptr.loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); + }, function(e:ProgressEvent):void { + }); + return; + } else + _splitpjprinted++; + } + else { + setTimeout(printSplitPaper, 200); + return; + } + } + + _splitpj.send(); + } + + private function printSplitPaperLoaded(event:Event):void { + var pageToPrint:MovieClip = event.target.content as MovieClip; + + if ((_splitpj.pageHeight / pageToPrint.height) < 1 && (_splitpj.pageHeight / pageToPrint.height) < (_splitpj.pageWidth / pageToPrint.width)) + pageToPrint.scaleX = pageToPrint.scaleY = (_splitpj.pageHeight / pageToPrint.height); + else if ((_splitpj.pageWidth / pageToPrint.width) < 1) + pageToPrint.scaleX = pageToPrint.scaleY = (_splitpj.pageWidth / pageToPrint.width); + + if ((_swfContainer.getChildAt(0) as UIComponent).numChildren > 0) + (_swfContainer.getChildAt(0) as UIComponent).removeChildAt(0); + + (_swfContainer.getChildAt(0) as UIComponent).addChild(pageToPrint); + + _splitpj.addPage(_swfContainer, null, _splitpjoptions); + _splitpjloading = false; + _splitpjprinted++; + printSplitPaper(); + } + + public function printPaper():void { + if (_docLoader.IsSplit) + return printSplitPaper(true); + + if (_libMC.parent is DupImage) { + (_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument()); + } + _libMC.alpha = 1; + + var pj:PrintJob = new PrintJob(); + var pjlist:Array = new Array(); + + if (!(_pluginList != null && _pluginList.length > 0)) { + if (pj.start()) { + _libMC.stop(); + + //if(pj.orientation == "landscape"){ + + //} + + if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) + _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); + else if ((pj.pageWidth / _libMC.width) < 1) + _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); + + var options:PrintJobOptions = new PrintJobOptions(); + //options.printAsBitmap = true; + + var i:int = 0; + _libMC.gotoAndStop(i + 1); + + while (_libMC.totalFrames > _libMC.currentFrame) { + if (_libMC.currentFrame == i + 1) { + pj.addPage(_swfContainer, null, options); + + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame + 1); + } + + pj.addPage(_swfContainer, null, options); + pj.send(); + } + } + + // printing with plug-ins uses a bitmap approach + if (_pluginList != null && _pluginList.length > 0) { + var di:DupImage; + var i:int = 0; + _libMC.gotoAndStop(i + 1); + + if (pj.start()) { + _libMC.stop(); + + if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) + _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); + else if ((pj.pageWidth / _libMC.width) < 1) + _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); + + var options:PrintJobOptions = new PrintJobOptions(); + + while (_libMC.totalFrames > _libMC.currentFrame) { + if (_libMC.currentFrame == i + 1) { + di = preparePrintBitmap(i); + pjlist[i] = preparePrintBitmap(i); + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame + 1); + } + + di = preparePrintBitmap(_libMC.totalFrames); + pjlist[_libMC.totalFrames - 1] = preparePrintBitmap(_libMC.totalFrames - 1); + + for (var ipjlist:int = 0; ipjlist < pjlist.length; ipjlist++) { + pj.addPage(pjlist[ipjlist], null, options); + } + + pj.send(); + } + } + + _libMC.scaleX = _libMC.scaleY = 1; + _libMC.alpha = 0; + dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); + } + + private function preparePrintBitmap(pageIndex:int):DupImage { + var di:DupImage = new DupImage(); + di.removeAllChildren(); + + var bmd:BitmapData = new BitmapData(_libMC.width, _libMC.height); + var bm:Bitmap = new Bitmap(bmd); + + bmd = new BitmapData(_libMC.width, _libMC.height); + bm = new Bitmap(bmd); + bmd.draw(_libMC.getDocument(), new Matrix(1, 0, 0, 1), null, null, null, true); + + if (_pluginList != null) { + for (var pl = 0; pl < _pluginList.length; pl++) { + _pluginList[pl].drawSelf(pageIndex, bmd, 1); + } + } + + di.addChild(bm); + + return di; + } + + public function printPaperRange(range:String):void { + if (_docLoader.IsSplit) + return printSplitPaper(true, range); + + if (_libMC.parent is DupImage) { + (_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument()); + } + _libMC.alpha = 1; + + var pageNumList:Array = new Array(); + var pjlist:Array = new Array(); + + if (range == "Current") { + pageNumList[currPage] = true; + } else { + var splitPageNumList:Array = range.split(","); + for (var i:int = 0; i < splitPageNumList.length; i++) { + if (splitPageNumList[i].toString().indexOf("-") > -1) { + var rs:int = Number(splitPageNumList[i].toString().substr(0, splitPageNumList[i].toString().indexOf("-"))); + var re:int = Number(splitPageNumList[i].toString().substr(splitPageNumList[i].toString().indexOf("-") + 1)); + for (var irs:int = rs; irs < re + 1; irs++) { + pageNumList[irs] = true; + } + } else { + pageNumList[int(Number(splitPageNumList[i].toString()))] = true; + } + } + } + + var pj:PrintJob = new PrintJob(); + var options:PrintJobOptions = new PrintJobOptions(); + //options.printAsBitmap = true; + + if (!(_pluginList != null && _pluginList.length > 0)) { + if (pj.start()) { + _libMC.stop(); + + if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) + _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); + else if ((pj.pageWidth / _libMC.width) < 1) + _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); + + var i:int = 0; + _libMC.gotoAndStop(i + 1); + while (_libMC.totalFrames > _libMC.currentFrame) { + if (_libMC.currentFrame == i + 1) { + if (pageNumList[i + 1] != null) { + pj.addPage(_swfContainer, null, options); + } + + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame + 1); + } + + if (pageNumList[_libMC.totalFrames] != null) { + pj.addPage(_swfContainer, null, options); + } + + pj.send(); + } + } + + // printing with plug-ins uses a bitmap approach + if (_pluginList != null && _pluginList.length > 0) { + var di:DupImage; + var i:int = 0; + if (pj.start()) { + _libMC.stop(); + + if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) + _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); + else if ((pj.pageWidth / _libMC.width) < 1) + _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); + + var i:int = 0; + _libMC.gotoAndStop(i + 1); + while (_libMC.totalFrames > _libMC.currentFrame) { + if (_libMC.currentFrame == i + 1) { + if (pageNumList[i + 1] != null) { + di = preparePrintBitmap(i); + pjlist[i] = preparePrintBitmap(i); + } + + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame + 1); + } + + if (pageNumList[_libMC.totalFrames] != null) { + di = preparePrintBitmap(_libMC.totalFrames); + pjlist[_libMC.totalFrames - 1] = preparePrintBitmap(_libMC.totalFrames - 1); + } + + for (var ipjlist:int = 0; ipjlist < pjlist.length; ipjlist++) { + pj.addPage(pjlist[ipjlist], null, options); + } + + pj.send(); + } + } + + + _libMC.scaleX = _libMC.scaleY = 1; + _libMC.alpha = 0; + + dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); + } + + private function addGlowFilter(img:Image):void { + var filter:flash.filters.GlowFilter = new flash.filters.GlowFilter(0x111111, 1, 5, 5, 2, 1, false, false); + img.filters = [ filter ]; + } + + private function addDropShadow(img:Image):void { + var filter:DropShadowFilter = new DropShadowFilter(); + filter.blurX = 4; + filter.blurY = 4; + filter.quality = 2; + filter.alpha = 0.5; + filter.angle = 45; + filter.color = 0x202020; + filter.distance = 6; + filter.inner = false; + img.filters = [ filter ]; + } + + public function get SecretKey():String { + return _secretKey; + } + + public function set SecretKey(value:String):void { + _secretKey = value; + } +} +} diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/styles/default.css b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/styles/default.css new file mode 100644 index 0000000..3c1c5ba --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/styles/default.css @@ -0,0 +1,45 @@ + .toolbarBackground { + backgroundImage: ClassReference("com.devaldi.skinning.GradientBackground"); + backgroundSize: "100%"; + fillColors: #e6e6e6, #fdfdfd; + fillAlphas: 1, 1; + borderColor: #8a8a8a; + } + + .viewerBackground { + backgroundImage: ClassReference("com.devaldi.skinning.GradientBackground"); + backgroundSize: "100%"; + fillColors: #aab3b3, #d5dddd; + fillAlphas: 1, 1; + borderColor: #8a8a8a; + } + + .toolbttn{ + skin: ClassReference("mx.skins.ProgrammaticSkin"); + overSkin:ClassReference("mx.skins.halo.ButtonBarButtonSkin"); + downSkin:ClassReference("mx.skins.halo.ButtonBarButtonSkin"); + selectedUpSkin:ClassReference("mx.skins.RectangularBorder"); + } + + .sliderbttn{ + skin: ClassReference("mx.skins.ProgrammaticSkin"); + overSkin:ClassReference("mx.skins.halo.SliderHighlightSkin"); + downSkin:ClassReference("mx.skins.halo.SliderHighlightSkin"); + } + + + .gradientlines { + spinner-type: gradientlines; + spinner-color: #ffffff; + spinner-highlight-color: #000000; + } + + .circles { + spinner-type: circles; + } + + .lines { + spinner-type: lines; + spinner-highlight-color: #000000; + spinner-color: #808080; + } diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/FullscreenHandler.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/FullscreenHandler.as new file mode 100644 index 0000000..79ba053 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/FullscreenHandler.as @@ -0,0 +1,9 @@ +package com.devaldi.controls.flexpaper.utils +{ + public class FullscreenHandler + { + public function FullscreenHandler() + { + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/MacMouseWheelHandler.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/MacMouseWheelHandler.as new file mode 100644 index 0000000..9fcb44f --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/MacMouseWheelHandler.as @@ -0,0 +1,187 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls.flexpaper.utils +{ + import flash.display.Stage; + import flash.events.MouseEvent; + import flash.display.InteractiveObject; + import flash.external.ExternalInterface; + + public class MacMouseWheelHandler + { + static private var _init : Boolean = false; + static private var _currItem : InteractiveObject; + static private var _clonedEvent : MouseEvent; + + static public function init(stage:Stage):void + { + if(!_init) + { + _init = true; + stage.addEventListener(MouseEvent.MOUSE_MOVE, function(e:MouseEvent):void + { + _currItem = InteractiveObject(e.target); + _clonedEvent = MouseEvent(e); + }); + + // send in the callbacks + if(ExternalInterface.available) + { + var id:String = 'eb_' + Math.floor(Math.random()*1000000); + ExternalInterface.addCallback(id, function(){}); + ExternalInterface.call(c_jscode); + ExternalInterface.call("eb.InitMacMouseWheel", id); + ExternalInterface.addCallback('externalMouseEvent', _externalMouseEvent); + } + } + } + + static private function _externalMouseEvent(delta:Number):void + { + if(_currItem && _clonedEvent) + _currItem.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_WHEEL, true, false, + _clonedEvent.localX, _clonedEvent.localY, _clonedEvent.relatedObject, + _clonedEvent.ctrlKey, _clonedEvent.altKey, _clonedEvent.shiftKey, _clonedEvent.buttonDown, + int(delta))); + } + + // javascript mouse handling code + static private const c_jscode : XML = + ; + } + +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/StreamUtil.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/StreamUtil.as new file mode 100644 index 0000000..f4365bb --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/StreamUtil.as @@ -0,0 +1,31 @@ +package com.devaldi.controls.flexpaper.utils +{ + import com.devaldi.streaming.IDocumentLoader; + + import flash.system.ApplicationDomain; + import flash.system.LoaderContext; + + public class StreamUtil + { + private static var loaderCtx:LoaderContext; + public static var DocLoader:IDocumentLoader; + public static var ProgressiveLoading:Boolean; + + public static function getExecutionContext():LoaderContext{ + if(loaderCtx == null){ + loaderCtx = new LoaderContext(); + loaderCtx.applicationDomain = ApplicationDomain.currentDomain; + + if(loaderCtx.hasOwnProperty("allowCodeImport")){ + loaderCtx["allowCodeImport"] = true; + } + + if(loaderCtx.hasOwnProperty("allowLoadBytesCodeExecution")){ + loaderCtx["allowLoadBytesCodeExecution"] = true; + } + + } + return loaderCtx; + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/TextMapUtil.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/TextMapUtil.as new file mode 100644 index 0000000..54a62e8 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/TextMapUtil.as @@ -0,0 +1,185 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls.flexpaper.utils +{ + import com.devaldi.streaming.IGenericDocument; + import com.devaldi.streaming.SwfDocument; + + import flash.display.MovieClip; + + public class TextMapUtil + { + public static var langMap:Array; + public static var totalFragments:String = ""; + + public static function alw(word:String,replacement:String,len:int=1):void{ + var idx:int = langMap.length; + langMap[idx] = new Array(3); langMap[idx][0] = word;langMap[idx][1] = replacement;langMap[idx][2] = len; + } + + public static function initLangMap(mc:IGenericDocument):void{ + if(totalFragments.length == 0){ + for(var i:int=0;i0 && totalFragments.indexOf(StringReplaceAll(langMap[li][0],"*",s.charAt(pos)))>0){ + return li; + }else if(langMap[li][2]==2&&langMap[li].length>0 && totalFragments.indexOf(StringReplaceAll(langMap[li][0],"*",s.charAt(pos)+s.charAt(pos+1)))>0){ + return li; + }else if(langMap[li][2]==3&&langMap[li].length>0 && totalFragments.indexOf(StringReplaceAll(langMap[li][0],"*",s.charAt(pos)+s.charAt(pos+1)+s.charAt(pos+2)))>0){ + return li; + } + + } + + return -1; + } + + public static function checkUnicodeIntegrity(s:String, search:String=null, mc:IGenericDocument=null):String{ + TextMapUtil.initLangMap(mc); + + var lmi:int = -1; + var bContainsErr:Boolean=false; + + for(var ci:int=0;ci 10000){ + bContainsErr = true; + lmi = TextMapUtil.findLangMapMatch(s,ci); + if(lmi!=-1){ + if(langMap[lmi][2]==1) + s = StringReplaceAll(s,s.charAt(ci),langMap[lmi][1]); + else + s = StringReplaceAll(s,s.charAt(ci)+langMap[lmi][1].substring(1),langMap[lmi][1]); + }else{ // default to 'f' + s = StringReplaceAll(s,s.charAt(ci),"f"); + } + } + } + + if(bContainsErr){ + s = ((search!=null&&search.indexOf("fl")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57394),"fl"):s; + s = ((search!=null&&search.indexOf("fi")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57345),"fi"):s; + s = ((search!=null&&search.indexOf("fi")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57393),"fi"):s; + s = ((search!=null&&search.indexOf("fi")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57370),"fi"):s; + s = ((search!=null&&search.indexOf("f")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57385),"f"):s; + s = ((search!=null&&search.indexOf("f")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57374),"f"):s; + s = ((search!=null&&search.indexOf("f")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57396),"f"):s; + s = ((search!=null&&search.indexOf("f")>=0)||search==null)?StringReplaceAll(s,String.fromCharCode(57398),"f"):s; + s = StringReplaceAll(s," ol "," of "); + s = StringReplaceAll(s," lor "," for "); + s = StringReplaceAll(s," lound "," found "); + s = StringReplaceAll(s," lrom "," from "); + s = StringReplaceAll(s," worfd "," world "); + s = StringReplaceAll(s," whife "," while "); + s = StringReplaceAll(s," Whife "," while "); + s = StringReplaceAll(s," gfobaf "," global "); + s = StringReplaceAll(s," ofers "," offers "); + s = StringReplaceAll(s," ofer "," offer "); + s = StringReplaceAll(s," commonfy "," commonly "); + s = StringReplaceAll(s," afong "," along "); + s = StringReplaceAll(s,"incfud","includ"); + } + return s; + } + + public static function StringReplaceAll( source:String, find:String, replacement:String ) : String + { + return source.split( find ).join( replacement ); + } + + } +} diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/utils/VersionHandler.as b/docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/VersionHandler.as similarity index 100% rename from docviewerflex/src/com/devaldi/controls/flexpaper/utils/VersionHandler.as rename to docviewerflex.backup/src/com/devaldi/controls/flexpaper/utils/VersionHandler.as diff --git a/docviewerflex.backup/src/com/devaldi/events/CurrentPageChangedEvent.as b/docviewerflex.backup/src/com/devaldi/events/CurrentPageChangedEvent.as new file mode 100644 index 0000000..88ecad8 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/CurrentPageChangedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class CurrentPageChangedEvent extends Event + { + public static const PAGE_CHANGED:String = "onCurrPageChanged"; + public var pageNum:Number; + + public function CurrentPageChangedEvent(type:String,p:Number){ + super(type); + pageNum=p; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new CurrentPageChangedEvent(type, pageNum); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/CursorModeChangedEvent.as b/docviewerflex.backup/src/com/devaldi/events/CursorModeChangedEvent.as new file mode 100644 index 0000000..71285c8 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/CursorModeChangedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class CursorModeChangedEvent extends Event + { + public static const CURSORMODE_CHANGED:String = "onCursorModeChanged"; + public var cursorMode:String; + + public function CursorModeChangedEvent(type:String,cursormode:String) + { + super(type); + cursorMode = cursormode; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new CursorModeChangedEvent(type, cursorMode); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/DocumentLoadedEvent.as b/docviewerflex.backup/src/com/devaldi/events/DocumentLoadedEvent.as new file mode 100644 index 0000000..5fae016 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/DocumentLoadedEvent.as @@ -0,0 +1,40 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class DocumentLoadedEvent extends Event + { + public static const DOCUMENT_LOADED:String = "onDocumentLoaded"; + + public var totalPages:Number; + + public function DocumentLoadedEvent(type:String,p:Number){ + super(type); + totalPages=p; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new DocumentLoadedEvent(type, totalPages); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/DocumentPrintedEvent.as b/docviewerflex.backup/src/com/devaldi/events/DocumentPrintedEvent.as new file mode 100644 index 0000000..506e43e --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/DocumentPrintedEvent.as @@ -0,0 +1,36 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class DocumentPrintedEvent extends Event + { + public static const DOCUMENT_PRINTED:String = "onDocumentPrinted"; + + public function DocumentPrintedEvent(type:String){ + super(type); + } + + // Override the inherited clone() method. + override public function clone():Event { + return new DocumentPrintedEvent(type); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/ErrorLoadingPageEvent.as b/docviewerflex.backup/src/com/devaldi/events/ErrorLoadingPageEvent.as new file mode 100644 index 0000000..5c18ef2 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/ErrorLoadingPageEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.events +{ + import flash.events.Event; + + public class ErrorLoadingPageEvent extends Event + { + public static const ERROR_LOADING_PAGE:String = "onErrorLoadingPage"; + + public var pageNumber:Number; + + public function ErrorLoadingPageEvent(type:String,p:Number){ + super(type); + pageNumber=p; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new ErrorLoadingPageEvent(type, pageNumber); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/ExternalLinkClickedEvent.as b/docviewerflex.backup/src/com/devaldi/events/ExternalLinkClickedEvent.as new file mode 100644 index 0000000..ac55589 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/ExternalLinkClickedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class ExternalLinkClickedEvent extends Event + { + public var link:String; + public static const EXTERNALLINK_CLICKED:String = "onExternalLinkClicked"; + + public function ExternalLinkClickedEvent(type:String,llink:String) + { + super(type); + link=llink; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new ExternalLinkClickedEvent(type, link); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/FitModeChangedEvent.as b/docviewerflex.backup/src/com/devaldi/events/FitModeChangedEvent.as new file mode 100644 index 0000000..4742b56 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/FitModeChangedEvent.as @@ -0,0 +1,41 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import com.devaldi.controls.flexpaper.FitModeEnum; + + import flash.events.Event; + + public class FitModeChangedEvent extends Event + { + public static const FITMODE_CHANGED:String = "onFitModeChanged"; + public var fitMode:String; + + public function FitModeChangedEvent(type:String,fitmode:String) + { + super(type); + fitMode = fitmode; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new FitModeChangedEvent(type, fitMode); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/PageLoadedEvent.as b/docviewerflex.backup/src/com/devaldi/events/PageLoadedEvent.as new file mode 100644 index 0000000..a53427a --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/PageLoadedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.events +{ + import flash.events.Event; + + public class PageLoadedEvent extends Event + { + public static const PAGE_LOADED:String = "onPageLoaded"; + + public var pageNumber:Number; + + public function PageLoadedEvent(type:String,p:Number){ + super(type); + pageNumber=p; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new PageLoadedEvent(type, pageNumber); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/PageLoadingEvent.as b/docviewerflex.backup/src/com/devaldi/events/PageLoadingEvent.as new file mode 100644 index 0000000..fe05541 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/PageLoadingEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.events +{ + import flash.events.Event; + + public class PageLoadingEvent extends Event + { + public static const PAGE_LOADING:String = "onPageLoading"; + + public var pageNumber:Number; + + public function PageLoadingEvent(type:String,p:Number){ + super(type); + pageNumber=p; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new PageLoadingEvent(type, pageNumber); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/ScaleChangedEvent.as b/docviewerflex.backup/src/com/devaldi/events/ScaleChangedEvent.as new file mode 100644 index 0000000..b189b46 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/ScaleChangedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class ScaleChangedEvent extends Event + { + public static const SCALE_CHANGED:String = "onScaleChanged"; + public var scale:Number; + + public function ScaleChangedEvent(type:String,s:Number){ + super(type); + scale=s; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new ScaleChangedEvent(type, scale); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/SelectionCreatedEvent.as b/docviewerflex.backup/src/com/devaldi/events/SelectionCreatedEvent.as new file mode 100644 index 0000000..a6767fc --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/SelectionCreatedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class SelectionCreatedEvent extends Event + { + public static const SELECTION_CREATED:String = "onSelectionCreated"; + public var text:String; + + public function SelectionCreatedEvent(type:String,s:String){ + super(type); + text=s; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new SelectionCreatedEvent(type, text); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/SwfLoadedEvent.as b/docviewerflex.backup/src/com/devaldi/events/SwfLoadedEvent.as new file mode 100644 index 0000000..300993f --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/SwfLoadedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class SwfLoadedEvent extends Event + { + public static const SWFLOADED:String = "onSwfLoadedEvent"; + public var swfObject:Object; + + public function SwfLoadedEvent(type:String,target:Object){ + super(type); + swfObject=target; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new SwfLoadedEvent(type, swfObject); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/events/ViewModeChangedEvent.as b/docviewerflex.backup/src/com/devaldi/events/ViewModeChangedEvent.as new file mode 100644 index 0000000..8372ad7 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/events/ViewModeChangedEvent.as @@ -0,0 +1,39 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.events +{ + import flash.events.Event; + + public class ViewModeChangedEvent extends Event + { + public static const VIEWMODE_CHANGED:String = "onViewModeChanged"; + public var viewMode:String; + + public function ViewModeChangedEvent(type:String,viewmode:String) + { + super(type); + viewMode = viewmode; + } + + // Override the inherited clone() method. + override public function clone():Event { + return new ViewModeChangedEvent(type, viewMode); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/skinning/GradientBackground.as b/docviewerflex.backup/src/com/devaldi/skinning/GradientBackground.as new file mode 100644 index 0000000..b8cca09 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/skinning/GradientBackground.as @@ -0,0 +1,83 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.skinning +{ +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.display.IBitmapDrawable; +import flash.display.Sprite; +import flash.geom.Matrix; +import flash.geom.Point; +import flash.geom.Rectangle; + +import mx.skins.ProgrammaticSkin; + + public class GradientBackground extends ProgrammaticSkin + { + + public function GradientBackground() + { + } + + override public function get measuredWidth():Number + { + return 20; + } + + override public function get measuredHeight():Number + { + return 20; + } + + override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void + { + + var fillColors:Array = getStyle("fillColors"); + var fillAlphas:Array = getStyle("fillAlphas"); + var cornerRadius:int = getStyle("cornerRadius"); + var gradientType:String = getStyle("gradientType"); + var angle:Number = getStyle("angle"); + var focalPointRatio:Number = getStyle("focalPointRatio"); + + // Default values, if styles aren't defined + if (fillColors == null) + fillColors = [0xEEEEEE, 0x999999]; + + if (fillAlphas == null) + fillAlphas = [1, 1]; + + if (gradientType == "" || gradientType == null) + gradientType = "linear"; + + if (isNaN(angle)) + angle = 90; + + if (isNaN(focalPointRatio)) + focalPointRatio = 0.5; + + var matrix:Matrix = new Matrix(); + matrix.createGradientBox(unscaledWidth, unscaledHeight, angle * Math.PI / 180); + + graphics.beginGradientFill(gradientType, fillColors, fillAlphas, [0, 255] , matrix, "pad", "rgb", focalPointRatio); + //graphics.drawRect(0, 0, unscaledWidth, unscaledHeight); + graphics.drawRoundRect(0, 0, unscaledWidth, unscaledHeight, cornerRadius*.5, cornerRadius*.5); + graphics.endFill(); + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/skinning/GradientHSlider.as b/docviewerflex.backup/src/com/devaldi/skinning/GradientHSlider.as new file mode 100644 index 0000000..37e0603 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/skinning/GradientHSlider.as @@ -0,0 +1,65 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.skinning +{ + import flash.events.Event; + import flash.filters.*; + + import mx.controls.HSlider; + import mx.events.*; + + public class GradientHSlider extends mx.controls.HSlider + { + public function GradientHSlider() + { + super(); + } + + override public function set enabled(value:Boolean):void{ + super.enabled = value; + enableHandler(null); + } + + private function enableHandler(event:Event):void + { + // define the color filter + var matrix:Array = new Array(); + + if (!enabled) + { + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // red + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // green + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 0.3, 0]); // alpha + } + else + { + matrix = matrix.concat([1, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 1, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 1, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + } + + var filter:BitmapFilter = new ColorMatrixFilter(matrix); + + // apply color filter + filters = new Array(filter) ; + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/skinning/GradientImageButton.as b/docviewerflex.backup/src/com/devaldi/skinning/GradientImageButton.as new file mode 100644 index 0000000..31a179f --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/skinning/GradientImageButton.as @@ -0,0 +1,85 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.skinning +{ + import flash.events.Event; + import flash.filters.*; + import flash.display.GradientType; + import mx.controls.Button; + import mx.events.*; + import flash.geom.Matrix; + + public class GradientImageButton extends Button + { + public function GradientImageButton() + { + super(); + + addEventListener("enabledChanged",enableHandler); + } + + override protected function updateDisplayList(w:Number, h:Number):void { + if(selected){ + graphics.clear(); + + var gradientBoxMatrix:Matrix = new Matrix(); + gradientBoxMatrix.createGradientBox(w, h, 0, 0, 0); + + graphics.beginGradientFill(GradientType.LINEAR,[0x009dff, 0x0079db, 0x0055b7],[0.22, 0.22, 0.22],[0, 128, 255],gradientBoxMatrix); + //graphics.beginGradientFill(GradientType.LINEAR,[0xdddddd, 0xcccccc, 0xdedede],[1, 1, 1],[100, 200, 255],gradientBoxMatrix); + + graphics.drawRect(0, 0, width, height); + }else{ + graphics.clear(); + } + + super.updateDisplayList(w,h); + } + + private function enableHandler(event:Event):void + { + // define the color filter + var matrix:Array = new Array(); + + if (!enabled) + { + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // red + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // green + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 0.3, 0]); // alpha + selected = false; + } + else + { + matrix = matrix.concat([1, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 1, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 1, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + } + + var filter:BitmapFilter = new ColorMatrixFilter(matrix); + + // apply color filter + filters = new Array(filter) ; + + // activate or disacivate the button mode + buttonMode = enabled ; + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/skinning/GradientLabel.as b/docviewerflex.backup/src/com/devaldi/skinning/GradientLabel.as new file mode 100644 index 0000000..156d848 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/skinning/GradientLabel.as @@ -0,0 +1,32 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.skinning +{ + import mx.controls.Label; + + public class GradientLabel extends Label + { + protected override function updateDisplayList(unscaledWidth:Number, + unscaledHeight:Number):void + { + super.updateDisplayList(unscaledWidth, unscaledHeight); + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/skinning/GradientTextInput.as b/docviewerflex.backup/src/com/devaldi/skinning/GradientTextInput.as new file mode 100644 index 0000000..5be8f86 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/skinning/GradientTextInput.as @@ -0,0 +1,66 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.skinning +{ + import flash.events.Event; + import flash.filters.*; + + import mx.controls.TextInput; + import mx.events.*; + + public class GradientTextInput extends mx.controls.TextInput + { + public function GradientTextInput() + { + super(); + } + + override public function set enabled(value:Boolean):void{ + super.enabled = value; + enableHandler(null); + } + + private function enableHandler(event:Event):void + { + // define the color filter + var matrix:Array = new Array(); + + if (!enabled) + { + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // red + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // green + matrix = matrix.concat([0.31, 0.61, 0.08, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 0.3, 0]); // alpha + } + else + { + matrix = matrix.concat([1, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 1, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 1, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + } + + var filter:BitmapFilter = new ColorMatrixFilter(matrix); + + // apply color filter + filters = new Array(filter) ; + } + + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/AVM2Loader.as b/docviewerflex.backup/src/com/devaldi/streaming/AVM2Loader.as new file mode 100644 index 0000000..a71427a --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/AVM2Loader.as @@ -0,0 +1,409 @@ +/* + Copyright 2009 Erik Engström + + This file is part of FlexPaper. + + FlexPaper 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, version 3 of the License. + + FlexPaper 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 FlexPaper. If not, see . + + Inspired by the ForcibleLoader class by + BeInteractive! (www.be-interactive.org) + */ + +package com.devaldi.streaming { + +import com.devaldi.events.SwfLoadedEvent; + +import flash.display.DisplayObject; +import flash.display.Loader; +import flash.errors.EOFError; +import flash.events.ErrorEvent; +import flash.events.Event; +import flash.events.EventDispatcher; +import flash.events.IEventDispatcher; +import flash.events.IOErrorEvent; +import flash.events.ProgressEvent; +import flash.events.SecurityErrorEvent; +import flash.net.URLRequest; +import flash.net.URLStream; +import flash.system.LoaderContext; +import flash.utils.ByteArray; +import flash.utils.Endian; + + +/** + * Usage: + *
+ * var loader:Loader = Loader(addChild(new Loader()));
+ * var fLoader:ForcibleLoader = new ForcibleLoader(loader);
+ * fLoader.load(new URLRequest('swf7.swf'));
+ * 
+ */ + +[Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] +[Event(name="onLoadersLoaded", type="flash.events.Event")] +[Event(name="onSwfLoaded", type="com.devaldi.events.SwfLoadedEvent")] + +public class AVM2Loader implements IDocumentLoader { + private var dispatcher:IEventDispatcher = new EventDispatcher(); + private var _loader:Loader = new Loader(); + private var _stream:URLStream; + private var _inputBytes:ByteArray; + private var _loaderCtx:LoaderContext; + private var _resigned:Boolean = false; + private var _bytesPending:uint = 0; + private var _prevLength:uint = 0; + private var _attempts:Number = 0; + private var _doretry:Boolean = true; + private var _request:URLRequest; + public var version:uint = 0; + private var _progressive:Boolean = false; + private var _loaderList:Array; + private var _pagesSplit:Boolean = false; + + public function AVM2Loader(loaderCtx:LoaderContext, progressive:Boolean) { + _loaderCtx = loaderCtx; + _progressive = progressive; + resetURLStream(); + } + + public function resetURLStream():void { + + if (_stream != null) { + try { + if (stream.connected) { + _stream.close(); + } + } catch(e:Error) { + } + + if (!_progressive) { + _stream.removeEventListener(Event.COMPLETE, completeHandler); + _stream.removeEventListener(ProgressEvent.PROGRESS, nonProgressiveProgress); + } else { + _stream.removeEventListener(ProgressEvent.PROGRESS, streamProgressHandler); + _stream.removeEventListener(Event.COMPLETE, streamCompleteHandler); + } + + _stream.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + + _loader.unloadAndStop(true); + _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderComplete); + _loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + _loader = new Loader(); + + } + + _stream = new URLStream(); + + if (!_progressive) { + _stream.addEventListener(Event.COMPLETE, completeHandler, false, 0, true); + _stream.addEventListener(ProgressEvent.PROGRESS, nonProgressiveProgress, false, 0, true); + } else { + _stream.addEventListener(ProgressEvent.PROGRESS, streamProgressHandler, false, 0, true); + _stream.addEventListener(Event.COMPLETE, streamCompleteHandler, false, 0, true); + } + + _stream.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + _stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + + _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete); + _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function loaderComplete(event:Event):void { + dispatchEvent(new SwfLoadedEvent(SwfLoadedEvent.SWFLOADED, event.currentTarget)); + } + + public function get IsSplit():Boolean { + return _pagesSplit; + } + + public function set IsSplit(b:Boolean):void { + _pagesSplit = b; + } + + public function get LoaderList():Array { + return _loaderList; + } + + public function set LoaderList(v:Array):void { + _loaderList = v; + } + + public function get Resigned():Boolean { + return _resigned; + } + + public function get DocumentContainer():DisplayObject { + return _loader; + } + + public function get InputBytes():ByteArray { + return _inputBytes; + } + + public function set InputBytes(b:ByteArray):void { + _inputBytes = b; + } + + public function get stream():URLStream { + return _stream; + } + + public function get loader():Loader { + return _loader; + } + + public function set loader(value:Loader):void { + _loader = value; + } + + public function loadFromBytes(bytes:ByteArray):void { + _inputBytes = bytes; + + confirmBytesLoaded(); + } + + public function load(request:URLRequest, loaderCtx:LoaderContext):void { + //resetURLStream(); + + _attempts++; + _request = request; + _stream.load(request); + _inputBytes = new ByteArray(); + + // wait with this one.. seems a bit dodgy + //flash.utils.setTimeout(retry,7000); + } + + private function retry():void { + if (_attempts < 4 && _doretry) { + _attempts++; + _stream.load(_request); + flash.utils.setTimeout(retry, 7000); + } + } + + private function streamCompleteHandler(event:Event):void { + flash.utils.setTimeout(confirmBytesLoaded, 500); + _stream.close(); + } + + private function confirmBytesLoaded():void { + try { + _stream.readBytes(_inputBytes, _inputBytes.length); + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes, _loaderCtx); + } + catch(e:Error) { // on error try again, version 9 of flash player sometimes fails. + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes, _loaderCtx); + } + } + + private function nonProgressiveProgress(event:ProgressEvent):void { + _doretry = (_loader.contentLoaderInfo == null || _loader.contentLoaderInfo.bytesLoaded < 2000); + } + + private function streamProgressHandler(event:ProgressEvent):void { + //if there are no bytes do nothing + _stream.readBytes(_inputBytes, _inputBytes.length); + _bytesPending = _inputBytes.length - _prevLength; + + if (_inputBytes.length > 4) { + version = uint(_inputBytes[3]); + + if (version <= 9) { + updateVersion(9, _inputBytes); + } + } + + if (_bytesPending > (event.bytesTotal / 10) || (_loader.contentLoaderInfo != null && event.bytesTotal == _bytesPending + _loader.contentLoaderInfo.bytesLoaded)) { + _bytesPending = 0; + _prevLength = _inputBytes.length; + try { + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes, _loaderCtx); + } + catch(e:Error) { // on error try again, version 9 of flash player sometimes fails. + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes, _loaderCtx); + } + } + + _doretry = (_loader.contentLoaderInfo == null || _loader.contentLoaderInfo.bytesLoaded < 2000); + } + + private function completeHandler(event:Event):void { + _inputBytes = new ByteArray(); + _stream.readBytes(_inputBytes); + _stream.close(); + _inputBytes.endian = Endian.LITTLE_ENDIAN; + + if (isCompressed(_inputBytes)) { + uncompress(_inputBytes); + } + + version = uint(_inputBytes[3]); + + if (version <= 9) { + if (version == 8 || version == 9) { + flagSWF9Bit(_inputBytes); + } else if (version <= 7) { + insertFileAttributesTag(_inputBytes); + } + updateVersion(9, _inputBytes); + } + + loader.unloadAndStop(true); + loader.loadBytes(_inputBytes, _loaderCtx); + } + + public function isCompressed(bytes:ByteArray):Boolean { + return bytes[0] == 0x43; + } + + private function uncompress(bytes:ByteArray):void { + var cBytes:ByteArray = new ByteArray(); + cBytes.writeBytes(bytes, 8); + bytes.length = 8; + bytes.position = 8; + cBytes.uncompress(); + bytes.writeBytes(cBytes); + bytes[0] = 0x46; + cBytes.length = 0; + } + + private function getBodyPosition(bytes:ByteArray):uint { + var result:uint = 0; + + result += 3; // FWS/CWS + result += 1; // version(byte) + result += 4; // length(32bit-uint) + + var rectNBits:uint = bytes[result] >>> 3; + result += (5 + rectNBits * 4) / 8; // stage(rect) + + result += 2; + + result += 1; // frameRate(byte) + result += 2; // totalFrames(16bit-uint) + + return result; + } + + private function findFileAttributesPosition(offset:uint, bytes:ByteArray):int { + bytes.position = offset; + + try { + for (; ;) { + var byte:uint = bytes.readShort(); + var tag:uint = byte >>> 6; + if (tag == 69) { + return bytes.position - 2; + } + var length:uint = byte & 0x3f; + if (length == 0x3f) { + length = bytes.readInt(); + } + bytes.position += length; + } + } + catch (e:EOFError) { + } + + return -1; + } + + public function postProcessBytes(bytes:ByteArray):void { + flagSWF9Bit(bytes); + } + + public function flagSWF9Bit(bytes:ByteArray):void { + var pos:int = findFileAttributesPosition(getBodyPosition(bytes), bytes); + + if (pos != -1) { + bytes[pos + 2] |= 0x08; + } + else { + insertFileAttributesTag(bytes); + } + } + + public function signFileHeader(bytes:ByteArray, ldr:Loader = null):void { + _resigned = true; + insertFileAttributesTag(bytes); + + if (ldr != null) { + ldr.unloadAndStop(true); + ldr.loadBytes(bytes, _loaderCtx); + } + else { + _loader.unloadAndStop(true); + _loader.loadBytes(bytes, _loaderCtx); + } + } + + private function insertFileAttributesTag(bytes:ByteArray):void { + var pos:uint = getBodyPosition(bytes); + var afterBytes:ByteArray = new ByteArray(); + afterBytes.writeBytes(bytes, pos); + bytes.length = pos; + bytes.position = pos; + bytes.writeByte(0x44); + bytes.writeByte(0x11); + bytes.writeByte(0x08); + bytes.writeByte(0x00); + bytes.writeByte(0x00); + bytes.writeByte(0x00); + bytes.writeBytes(afterBytes); + afterBytes.length = 0; + } + + public function updateVersion(version:uint, b:ByteArray):void { + b[3] = version; + } + + public function dispatchEvent(event:Event):Boolean { + return dispatcher.dispatchEvent(event); + } + + public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { + dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); + } + + public function hasEventListener(type:String):Boolean { + return dispatcher.hasEventListener(type); + } + + public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { + dispatcher.removeEventListener(type, listener, useCapture); + } + + public function willTrigger(type:String):Boolean { + return dispatcher.willTrigger(type); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); + evt.text = event.text; + dispatchEvent(evt); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); + evt.text = event.text; + dispatchEvent(evt); + } +} +} diff --git a/docviewerflex.backup/src/com/devaldi/streaming/DupImage.as b/docviewerflex.backup/src/com/devaldi/streaming/DupImage.as new file mode 100644 index 0000000..f913d28 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/DupImage.as @@ -0,0 +1,229 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.streaming +{ + import com.devaldi.controls.Spinner; + import com.devaldi.controls.flexpaper.resources.MenuIcons; + + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.DisplayObject; + import flash.display.MovieClip; + import flash.events.MouseEvent; + import flash.filters.DropShadowFilter; + import flash.filters.GlowFilter; + import flash.text.TextSnapshot; + import flash.utils.setTimeout; + + import mx.controls.Image; + + public class DupImage extends Image + { + public var dupIndex:int = 0; + //public var dupScale:Number = 0; + //public var scaleWidth:int; + //public var scaleHeight:int; + public var loadedIndex:int = -1; + public var _paperRotation:int = 0; + public var doAddDropShadow:Boolean = true; + public var doAddGlowFilter:Boolean = false; + public var glowFilterColor:uint = 0x000000; + public var NeedsFitting:Boolean = false; + public var RoleModelWidth:Number = 0; + public var RoleModelHeight:Number = 0; + public static var paperSource:DisplayObject; + //private var _skinImgl:Bitmap = new MenuIcons.LOGO_SMALL(); + private var loadImg:Bitmap; + private var loadSpinner:Spinner; + + public function DupImage(){} + + public function init():void{ + loadImg = new Bitmap(); + //loadImg.bitmapData = _skinImgl.bitmapData; + loadImg.smoothing = true; + + loadSpinner = new Spinner(50,50); + loadSpinner.setStyle("spinnerType","gradientcircle"); + loadSpinner.setStyle("spinnerThickness","7"); + loadSpinner.styleName = "gradientlines"; + } + + public function get paperRotation():Number { + return _paperRotation; + } + + public function set paperRotation(n:Number):void { + if(n==90){ + var w:int = width; + width = height; + height = w; + } + + _paperRotation = n; + } + + override public function get textSnapshot():TextSnapshot{ + if(getChildAt(0) is DupLoader && (getChildAt(0) as DupLoader).content!=null && (getChildAt(0) as DupLoader).content is MovieClip){ + return ((getChildAt(0) as DupLoader).content as MovieClip).textSnapshot; + }else + return super.textSnapshot; + } + + override public function set source(value:Object):void{ + if(this.source != null && this.source is Bitmap && this.source.bitmapData != null){ + this.source.bitmapData.dispose(); + } + + super.source = value; + + if(value!=null && doAddDropShadow){ + if(this.filters.length==0){addDropShadow();} + } + + if(value!=null && doAddGlowFilter){ + if(this.filters.length==0){addGlowFilter();} + } + + if(value == null && hasEventListener(MouseEvent.ROLL_OVER)){ + removeEventListener(MouseEvent.ROLL_OVER,dupImageMoverHandler); + }else{ + if(!hasEventListener(MouseEvent.ROLL_OVER)) + addEventListener(MouseEvent.ROLL_OVER,dupImageMoverHandler,false,0,true); + } + } + + override protected function createChildren():void { + super.createChildren(); + } + + private function dupImageMoverHandler(event:MouseEvent):void{ // depricated.. only used when using bitmaps to render + /* if(!contains(paperSource)){ + paperSource.gotoAndStop(dupIndex); + paperSource.alpha = 0; + addChild(paperSource); + } */ + } + + public function addGlowFilter():void{ + if(this.filters.length==0){ + this.filters = null; + var filter : GlowFilter = new GlowFilter(glowFilterColor, 1, 3, 3, 5, 1, true, false); + this.filters = [ filter ]; + } + } + + public function addDropShadow():void + { + if(this.filters.length==0){ + this.filters = null; + var filter : DropShadowFilter = new DropShadowFilter(); + filter.blurX = 4; + filter.blurY = 4; + filter.quality = 2; + filter.alpha = 0.5; + filter.angle = 45; + filter.color = 0x202020; + filter.distance = 4; + filter.inner = false; + this.filters = [ filter ]; + } + } + + public function removeAllChildren():void{ + while(numChildren > 0) + delete(removeChildAt(0)); + + this.filters = null; + } + + override public function addChild(child:DisplayObject):DisplayObject{ + //flash.utils.setTimeout(addDropShadow,200); + super.addChildAt(child,0); + + if(child is DupLoader && NeedsFitting){ + if((child as DupLoader).content!=null && ((child as DupLoader).content.width != RoleModelWidth || (child as DupLoader).content.height != RoleModelHeight)){ + this.width = (child as DupLoader).content.width * scaleX; + this.height = (child as DupLoader).content.height * scaleY; + } + NeedsFitting = false; + } + + while(numChildren >= 2) + delete(removeChildAt(1)); + + return super.getChildAt(0); + } + + override public function addChildAt(child:DisplayObject,index:int):DisplayObject{ + return super.addChildAt(child,index); + } + + public function addBlankChildAt(child:DisplayObject,index:int):DisplayObject{ + return super.addChildAt(child,index); + } + + override protected function updateDisplayList(w:Number, h:Number):void { + if(w>0&&h>0){ + try{ + + if(_paperRotation!=90||_paperRotation==180){ + graphics.beginFill(0xffffff,1); + graphics.drawRect(0,0,w,h); + }else{ + graphics.clear(); + } + + super.updateDisplayList(w,h);}catch (e:*) {}} + + } + + public function addGlowShadow():void + { + + } + + public function getScaledHeight():Number + { + return scaleX>0? unscaledHeight * this.scaleX:height; + } + + public function resetPage(width:Number,height:Number,scale:Number,showSpinner:Boolean=false):void{ + loadedIndex = -1; + + if(loadImg.parent != this) + { + removeAllChildren(); + + loadImg.x = width/2 - 80; + loadImg.y = height/2 - 50; + scaleX = scaleY = scale; + addBlankChildAt(loadImg,numChildren); + } + + if(loadSpinner.parent != this && showSpinner){ + loadSpinner.x = width/2-25; + loadSpinner.y = height/2-125; + loadSpinner.start(); + scaleX = scaleY = scale; + addBlankChildAt(loadSpinner,numChildren); + } + } + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/DupLoader.as b/docviewerflex.backup/src/com/devaldi/streaming/DupLoader.as new file mode 100644 index 0000000..db999a7 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/DupLoader.as @@ -0,0 +1,30 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.streaming +{ + import flash.display.Loader; + + public class DupLoader extends flash.display.Loader + { + public var loaded:Boolean = false; + public var loadingFrames:int = 0; + public var pageStartIndex:int = 0; + public var loading:Boolean = false; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/IDocumentLoader.as b/docviewerflex.backup/src/com/devaldi/streaming/IDocumentLoader.as new file mode 100644 index 0000000..9573418 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/IDocumentLoader.as @@ -0,0 +1,45 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.streaming +{ + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.events.IEventDispatcher; + import flash.net.URLRequest; + import flash.net.URLStream; + import flash.system.LoaderContext; + import flash.utils.ByteArray; + + public interface IDocumentLoader extends IEventDispatcher + { + function get DocumentContainer():DisplayObject; + function get LoaderList():Array; + function set LoaderList(v:Array):void; + function postProcessBytes(b:ByteArray):void; + function load(request:URLRequest, loaderCtx:LoaderContext):void; + function loadFromBytes(bytes:ByteArray):void; + function resetURLStream():void; + function signFileHeader(bytes:ByteArray, ldr:Loader=null):void; + function get InputBytes():ByteArray; + function set InputBytes(b:ByteArray):void; + function get Resigned():Boolean; + function get stream():URLStream; + function get IsSplit():Boolean; + function set IsSplit(b:Boolean):void; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/IGenericDocument.as b/docviewerflex.backup/src/com/devaldi/streaming/IGenericDocument.as new file mode 100644 index 0000000..8cb7c42 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/IGenericDocument.as @@ -0,0 +1,42 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.streaming +{ + import flash.display.DisplayObject; + import flash.display.LoaderInfo; + import flash.display.MovieClip; + import flash.text.TextSnapshot; + + public interface IGenericDocument + { + function gotoAndStop(pagNumber:int):void; + function stop():void; + function getDocument():DisplayObject; + function get parent():DisplayObject; + function get totalFrames():int; + function get framesLoaded():int; + function get textSnapshot():TextSnapshot; + function set alpha(value:Number):void; + function get currentFrame():int; + function get height():Number; + function get width():Number; + function get loaderInfo():LoaderInfo; + function set scaleX(n:Number):void; + function set scaleY(n:Number):void; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/IGenericMovieClip.as b/docviewerflex.backup/src/com/devaldi/streaming/IGenericMovieClip.as new file mode 100644 index 0000000..d025560 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/IGenericMovieClip.as @@ -0,0 +1,27 @@ +/* +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.streaming +{ + public interface IGenericMovieClip + { + function gotoAndStop(frame:int):void; + function stop():void; + function get width():Number; + function get height():Number; + } +} \ No newline at end of file diff --git a/docviewerflex.backup/src/com/devaldi/streaming/SwfDocument.as b/docviewerflex.backup/src/com/devaldi/streaming/SwfDocument.as new file mode 100644 index 0000000..a0a9b53 --- /dev/null +++ b/docviewerflex.backup/src/com/devaldi/streaming/SwfDocument.as @@ -0,0 +1,94 @@ +/* + Copyright 2009 Erik Engström + + This file is part of FlexPaper. + + FlexPaper 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, version 3 of the License. + + FlexPaper 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 FlexPaper. If not, see . + */ +package com.devaldi.streaming { +import flash.display.Bitmap; +import flash.display.DisplayObject; +import flash.display.LoaderInfo; +import flash.display.MovieClip; +import flash.text.TextSnapshot; + + +public class SwfDocument implements IGenericDocument { + private var _mc:MovieClip; + + public function SwfDocument(mc:DisplayObject) { + if (mc is MovieClip) + _mc = mc as MovieClip; + else if (mc is Bitmap) { + _mc = new MovieClip(); + _mc.addChild(mc); + } + } + + public function gotoAndStop(pagNumber:int):void { + _mc.gotoAndStop(pagNumber); + } + + public function stop():void { + _mc.stop(); + } + + public function getDocument():DisplayObject { + return _mc; + } + + public function get parent():DisplayObject { + return _mc.parent; + } + + public function get totalFrames():int { + return _mc.totalFrames; + } + + public function get framesLoaded():int { + return _mc.framesLoaded; + } + + public function get textSnapshot():TextSnapshot { + return _mc.textSnapshot; + } + + public function set alpha(value:Number):void { + _mc.alpha = value; + } + + public function get currentFrame():int { + return _mc.currentFrame; + } + + public function get height():Number { + return _mc.height; + } + + public function get width():Number { + return _mc.width; + } + + public function get loaderInfo():LoaderInfo { + return _mc.loaderInfo; + } + + public function set scaleX(n:Number):void { + _mc.scaleX = n; + } + + public function set scaleY(n:Number):void { + _mc.scaleY = n; + } +} +} \ No newline at end of file diff --git a/docviewerflex/src/com/sinitek/log4ic/streaming/EncryptedLoader.as b/docviewerflex.backup/src/com/log4ic/streaming/EncryptedLoader.as similarity index 96% rename from docviewerflex/src/com/sinitek/log4ic/streaming/EncryptedLoader.as rename to docviewerflex.backup/src/com/log4ic/streaming/EncryptedLoader.as index 4f61b55..29e9715 100644 --- a/docviewerflex/src/com/sinitek/log4ic/streaming/EncryptedLoader.as +++ b/docviewerflex.backup/src/com/log4ic/streaming/EncryptedLoader.as @@ -2,7 +2,7 @@ * @author: 张立鑫 * @version: 1 */ -package com.sinitek.log4ic.streaming { +package com.log4ic.streaming { import com.sinitek.log4ic.utils.security.XXTEA; import flash.events.Event; diff --git a/docviewerflex/src/com/sinitek/log4ic/utils/StringUtils.as b/docviewerflex.backup/src/com/log4ic/utils/StringUtils.as similarity index 99% rename from docviewerflex/src/com/sinitek/log4ic/utils/StringUtils.as rename to docviewerflex.backup/src/com/log4ic/utils/StringUtils.as index 8cdb1be..e6bb299 100644 --- a/docviewerflex/src/com/sinitek/log4ic/utils/StringUtils.as +++ b/docviewerflex.backup/src/com/log4ic/utils/StringUtils.as @@ -2,7 +2,7 @@ * @author: 张立鑫 * @version: 1 */ -package com.sinitek.log4ic.utils { +package com.log4ic.utils { public class StringUtils { //忽略大小字母比较字符是否相等; public static function equalsIgnoreCase(char1:String, char2:String):Boolean { diff --git a/docviewerflex.backup/src/com/log4ic/utils/security/Security.as b/docviewerflex.backup/src/com/log4ic/utils/security/Security.as new file mode 100644 index 0000000..37a6c05 --- /dev/null +++ b/docviewerflex.backup/src/com/log4ic/utils/security/Security.as @@ -0,0 +1,61 @@ +/** + * @author: 张立鑫 + * @version: 1 + */ +package com.log4ic.utils.security { +import com.sinitek.log4ic.streaming.EncryptedLoader; + +import flash.events.Event; +import flash.events.ProgressEvent; +import flash.events.TimerEvent; +import flash.net.URLLoader; +import flash.net.URLLoaderDataFormat; +import flash.net.URLRequest; +import flash.utils.ByteArray; +import flash.utils.Dictionary; +import flash.utils.Timer; +import flash.utils.clearTimeout; +import flash.utils.setTimeout; + +import mx.controls.Alert; + +public class Security { + + private static var loaderMap:Dictionary = new Dictionary(); + + + public static function loadEncryptedFile(url:URLRequest, key:String, onComplete:Function, onProgress:Function):void { + +// var loader:EncryptedLoader = loaderMap[url.url]; +// +// if (loader) { +// loader.removeEventListener(Event.COMPLETE, onComplete); +// loader.addEventListener(Event.COMPLETE, onComplete); +// if (loader.loaded) { +// loader.dispatchEvent(new Event(Event.COMPLETE)); +// } +// return; +// } +// var keyBytes:ByteArray = null; +// if (key) { +// keyBytes = new ByteArray(); +// keyBytes.writeUTFBytes(key); +// } +// +// var urlLoader:EncryptedLoader = new EncryptedLoader(keyBytes); +// +// urlLoader.addEventListener(Event.COMPLETE, onComplete); +// if (onProgress) { +// urlLoader.addEventListener(ProgressEvent.PROGRESS, onProgress); +// } +// +// loaderMap[url.url] = urlLoader; +// +// urlLoader.load(url); + } + + public static function isLoaded(url:URLRequest) { + return !!loaderMap[url]; + } +} +} diff --git a/docviewerflex/src/com/sinitek/log4ic/utils/security/XXTEA.as b/docviewerflex.backup/src/com/log4ic/utils/security/XXTEA.as similarity index 98% rename from docviewerflex/src/com/sinitek/log4ic/utils/security/XXTEA.as rename to docviewerflex.backup/src/com/log4ic/utils/security/XXTEA.as index 92958f0..52d0f89 100644 --- a/docviewerflex/src/com/sinitek/log4ic/utils/security/XXTEA.as +++ b/docviewerflex.backup/src/com/log4ic/utils/security/XXTEA.as @@ -2,7 +2,7 @@ * @author: 张立鑫 * @version: 1 */ -package com.sinitek.log4ic.utils.security { +package com.log4ic.utils.security { import com.sinitek.log4ic.utils.StringUtils; import flash.utils.ByteArray; diff --git a/docviewerflex/docviewerflex.iml b/docviewerflex/docviewerflex.iml index bcbd809..f031ae1 100644 --- a/docviewerflex/docviewerflex.iml +++ b/docviewerflex/docviewerflex.iml @@ -9,7 +9,7 @@
@@ -18,20 +18,10 @@ - - - - - - - - - - diff --git a/docviewerflex/locale/bg_BG/FlexPaper.properties b/docviewerflex/locale/bg_BG/FlexPaper.properties index bdad003..0f8151a 100644 --- a/docviewerflex/locale/bg_BG/FlexPaper.properties +++ b/docviewerflex/locale/bg_BG/FlexPaper.properties @@ -1,31 +1,31 @@ -# locale/bg_BG/FlexPaper.properties -Print=Принтирай -FitWidth=Запълни на ширина -FitPage=Запълни -Scale=Мащаб -ThumbView=Виж картинки -CurrentPage=Сегашна страница -Search=Търси -NextPage=Следваща страница -PreviousPage=Предишна страница -Fullscreen=Цял екран -About=Относно -Finishedsearching=Търсенето завърши. Не са открити съвпадения -Searchfinished=Търсенето завърши -Selectprintrange=Въведете страници за принтиране -All=Всички -CurrentPage=Сегашна страница -Pages=Страници: -Enterpagenumbers=Въведи номер на страницата или номера от/до, отделени със запетая. Пример: 1,3,5-12 -Cancel=Отмени -IncorrectRange=Въведен неправилен номер от-до -Incorrectrangespecified=Въведени неправилни номера на страници -About=Относно -Developedby=Разработено от Devaldi. -Formoreinformation=Виж за повече информация -CopyText=Копирай текста -TwoPage=Две страници -SinglePage=Една страница -Current\ Page=Create Property -TextSelect=Create Property +# locale/bg_BG/FlexPaper.properties +Print=\u041f\u0440\u0438\u043d\u0442\u0438\u0440\u0430\u0439 +FitWidth=\u0417\u0430\u043f\u044a\u043b\u043d\u0438 \u043d\u0430 \u0448\u0438\u0440\u0438\u043d\u0430 +FitPage=\u0417\u0430\u043f\u044a\u043b\u043d\u0438 +Scale=\u041c\u0430\u0449\u0430\u0431 +ThumbView=\u0412\u0438\u0436 \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438 +CurrentPage=\u0421\u0435\u0433\u0430\u0448\u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +Search=\u0422\u044a\u0440\u0441\u0438 +NextPage=\u0421\u043b\u0435\u0434\u0432\u0430\u0449\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +PreviousPage=\u041f\u0440\u0435\u0434\u0438\u0448\u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +Fullscreen=\u0426\u044f\u043b \u0435\u043a\u0440\u0430\u043d +About=\u041e\u0442\u043d\u043e\u0441\u043d\u043e +Finishedsearching=\u0422\u044a\u0440\u0441\u0435\u043d\u0435\u0442\u043e \u0437\u0430\u0432\u044a\u0440\u0448\u0438. \u041d\u0435 \u0441\u0430 \u043e\u0442\u043a\u0440\u0438\u0442\u0438 \u0441\u044a\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u044f +Searchfinished=\u0422\u044a\u0440\u0441\u0435\u043d\u0435\u0442\u043e \u0437\u0430\u0432\u044a\u0440\u0448\u0438 +Selectprintrange=\u0412\u044a\u0432\u0435\u0434\u0435\u0442\u0435 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0438 \u0437\u0430 \u043f\u0440\u0438\u043d\u0442\u0438\u0440\u0430\u043d\u0435 +All=\u0412\u0441\u0438\u0447\u043a\u0438 +CurrentPage=\u0421\u0435\u0433\u0430\u0448\u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +Pages=\u0421\u0442\u0440\u0430\u043d\u0438\u0446\u0438: +Enterpagenumbers=\u0412\u044a\u0432\u0435\u0434\u0438 \u043d\u043e\u043c\u0435\u0440 \u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430\u0442\u0430 \u0438\u043b\u0438 \u043d\u043e\u043c\u0435\u0440\u0430 \u043e\u0442/\u0434\u043e, \u043e\u0442\u0434\u0435\u043b\u0435\u043d\u0438 \u0441\u044a\u0441 \u0437\u0430\u043f\u0435\u0442\u0430\u044f. \u041f\u0440\u0438\u043c\u0435\u0440: 1,3,5-12 +Cancel=\u041e\u0442\u043c\u0435\u043d\u0438 +IncorrectRange=\u0412\u044a\u0432\u0435\u0434\u0435\u043d \u043d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u0435\u043d \u043d\u043e\u043c\u0435\u0440 \u043e\u0442-\u0434\u043e +Incorrectrangespecified=\u0412\u044a\u0432\u0435\u0434\u0435\u043d\u0438 \u043d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u043d\u0438 \u043d\u043e\u043c\u0435\u0440\u0430 \u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0438 +About=\u041e\u0442\u043d\u043e\u0441\u043d\u043e +Developedby=\u0420\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0435\u043d\u043e \u043e\u0442 Devaldi. +Formoreinformation=\u0412\u0438\u0436 \u0437\u0430 \u043f\u043e\u0432\u0435\u0447\u0435 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f +CopyText=\u041a\u043e\u043f\u0438\u0440\u0430\u0439 \u0442\u0435\u043a\u0441\u0442\u0430 +TwoPage=\u0414\u0432\u0435 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0438 +SinglePage=\u0415\u0434\u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +Current\ Page=Create Property +TextSelect=Create Property TextDrag=Create Property \ No newline at end of file diff --git a/docviewerflex/locale/cz_CS/FlexPaper.properties b/docviewerflex/locale/cz_CS/FlexPaper.properties index 3fdbf51..67a0213 100644 --- a/docviewerflex/locale/cz_CS/FlexPaper.properties +++ b/docviewerflex/locale/cz_CS/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/cz_CS/FlexPaper.properties -Print=Tisk -FitWidth=Přizpůsobit na šířku -FitPage=Přizpůsobit na stránku -Scale=Velikost -ThumbView=Zobrazit náhled -CurrentPage=Aktuální stránka -Search=Hledat -NextPage=Další stránka -PreviousPage=Předchozí stránka -Fullscreen=Celá obrazovka -About=Informace -Finishedsearching=Prohledávaní dokumentu bylo dokončeno. Nebyly nalezeny žádné další hledané položky -Searchfinished=Vyhledávání dokončeno -Selectprintrange=Zvolte rozsah tisku -All=Vše -CurrentPage=Aktuální stránka -Pages=Stránky: -Enterpagenumbers=Zadejte čísla a/nebo rozsahy stránek oddělené čárkou. Například 1,3,5-12 -Cancel=Storno -IncorrectRange=Nesprávný rozsah -Incorrectrangespecified=Byl zadán nesprávný rozsah -About=Informace -Developedby=Vytvořeno Devaldi. -Formoreinformation=Další informace najdete na adrese -TwoPage=Dvě stránky +# locale/cz_CS/FlexPaper.properties +Print=Tisk +FitWidth=P\u0159izp\u016fsobit na \u0161\u00ed\u0159ku +FitPage=P\u0159izp\u016fsobit na str\u00e1nku +Scale=Velikost +ThumbView=Zobrazit n\u00e1hled +CurrentPage=Aktu\u00e1ln\u00ed str\u00e1nka +Search=Hledat +NextPage=Dal\u0161\u00ed str\u00e1nka +PreviousPage=P\u0159edchoz\u00ed str\u00e1nka +Fullscreen=Cel\u00e1 obrazovka +About=Informace +Finishedsearching=Prohled\u00e1van\u00ed dokumentu bylo dokon\u010deno. Nebyly nalezeny \u017e\u00e1dn\u00e9 dal\u0161\u00ed hledan\u00e9 polo\u017eky +Searchfinished=Vyhled\u00e1v\u00e1n\u00ed dokon\u010deno +Selectprintrange=Zvolte rozsah tisku +All=V\u0161e +CurrentPage=Aktu\u00e1ln\u00ed str\u00e1nka +Pages=Str\u00e1nky: +Enterpagenumbers=Zadejte \u010d\u00edsla a/nebo rozsahy str\u00e1nek odd\u011blen\u00e9 \u010d\u00e1rkou. Nap\u0159\u00edklad 1,3,5-12 +Cancel=Storno +IncorrectRange=Nespr\u00e1vn\u00fd rozsah +Incorrectrangespecified=Byl zad\u00e1n nespr\u00e1vn\u00fd rozsah +About=Informace +Developedby=Vytvo\u0159eno Devaldi. +Formoreinformation=Dal\u0161\u00ed informace najdete na adrese +TwoPage=Dv\u011b str\u00e1nky SinglePage=Single Page \ No newline at end of file diff --git a/docviewerflex/locale/de_DE/FlexPaper.properties b/docviewerflex/locale/de_DE/FlexPaper.properties index f91517b..5094564 100644 --- a/docviewerflex/locale/de_DE/FlexPaper.properties +++ b/docviewerflex/locale/de_DE/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/de_DE/FlexPaper.properties -Print=Drucken -FitWidth=Weite anpassen -FitPage=Seite anpassen -Scale=Skalieren -ThumbView=Ansicht vereinfachen -CurrentPage=Derzeitige Seite -Search=Suche -NextPage=Nächste Seite -PreviousPage=Vorherige Seite -Fullscreen=Vollansicht -About=Über -Finishedsearching=Suche nach Dokument fertig. Keine weiteren Einträge gefunden -Searchfinished=Suche fertig -Selectprintrange=Druckbereich wählen -All=Alle -CurrentPage=Derzeitige Seite -Pages=Seiten: -Enterpagenumbers=Geben Sie die Seitenzahl und/oder den Seitenbereich an. Zum Beispiel 1,3,5-12 -Cancel=Abbrechen -IncorrectRange=Bereich nicht korrekt -Incorrectrangespecified=Bereich nicht richtig definiert -About=Über -Developedby=Erstellt von Devaldi. -Formoreinformation=Mehr Information -TwoPage=Zwei Page +# locale/de_DE/FlexPaper.properties +Print=Drucken +FitWidth=Weite anpassen +FitPage=Seite anpassen +Scale=Skalieren +ThumbView=Ansicht vereinfachen +CurrentPage=Derzeitige Seite +Search=Suche +NextPage=N\u00e4chste Seite +PreviousPage=Vorherige Seite +Fullscreen=Vollansicht +About=\u00dcber +Finishedsearching=Suche nach Dokument fertig. Keine weiteren Eintr\u00e4ge gefunden +Searchfinished=Suche fertig +Selectprintrange=Druckbereich w\u00e4hlen +All=Alle +CurrentPage=Derzeitige Seite +Pages=Seiten: +Enterpagenumbers=Geben Sie die Seitenzahl und/oder den Seitenbereich an. Zum Beispiel 1,3,5-12 +Cancel=Abbrechen +IncorrectRange=Bereich nicht korrekt +Incorrectrangespecified=Bereich nicht richtig definiert +About=\u00dcber +Developedby=Erstellt von Devaldi. +Formoreinformation=Mehr Information +TwoPage=Zwei Page SinglePage=Single Page \ No newline at end of file diff --git a/docviewerflex/locale/dn_DN/FlexPaper.properties b/docviewerflex/locale/dn_DN/FlexPaper.properties index 7554bfc..c3957ed 100644 --- a/docviewerflex/locale/dn_DN/FlexPaper.properties +++ b/docviewerflex/locale/dn_DN/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/dn_DN/FlexPaper.properties -Print=Udskriv -FitWidth=Tilpas bredde -FitPage=Tilpas side -Scale=Skala -ThumbView=Miniaturevisning -CurrentPage=Aktuel side -Search=Søg -NextPage=Næste side -PreviousPage=Forrige side -Fullscreen=Fuld skærm -About=Om -Finishedsearching=Søgningen i dokumentet er færdig. Der blev ikke fundet nogen resultater -Searchfinished=Søgning afsluttet -Selectprintrange=Vælg udskriftsområde -All=Alle -CurrentPage=Aktuel side -Pages=Sider: -Enterpagenumbers=Skriv sidetal og/eller sideområder adskilt af kommaer. f.eks. 1,3,5-12 -Cancel=Annuller -IncorrectRange=Ukorrekt område -Incorrectrangespecified=Ukorrekt område angivet -About=Om -Developedby=Udviklet af Devaldi. -Formoreinformation=For yderligere oplysninger, se -TwoPage=To Page +# locale/dn_DN/FlexPaper.properties +Print=Udskriv +FitWidth=Tilpas bredde +FitPage=Tilpas side +Scale=Skala +ThumbView=Miniaturevisning +CurrentPage=Aktuel side +Search=S\u00f8g +NextPage=N\u00e6ste side +PreviousPage=Forrige side +Fullscreen=Fuld sk\u00e6rm +About=Om +Finishedsearching=S\u00f8gningen i dokumentet er f\u00e6rdig. Der blev ikke fundet nogen resultater +Searchfinished=S\u00f8gning afsluttet +Selectprintrange=V\u00e6lg udskriftsomr\u00e5de +All=Alle +CurrentPage=Aktuel side +Pages=Sider: +Enterpagenumbers=Skriv sidetal og/eller sideomr\u00e5der adskilt af kommaer. f.eks. 1,3,5-12 +Cancel=Annuller +IncorrectRange=Ukorrekt omr\u00e5de +Incorrectrangespecified=Ukorrekt omr\u00e5de angivet +About=Om +Developedby=Udviklet af Devaldi. +Formoreinformation=For yderligere oplysninger, se +TwoPage=To Page SinglePage=Single Side \ No newline at end of file diff --git a/docviewerflex/locale/el_EL/FlexPaper.properties b/docviewerflex/locale/el_EL/FlexPaper.properties index 2597740..8287fb9 100644 --- a/docviewerflex/locale/el_EL/FlexPaper.properties +++ b/docviewerflex/locale/el_EL/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/el_EL/FlexPaper.properties -Print=Εκτύπωση -FitWidth=Προσαρμογή πλάτος -FitPage=Προσαρμογή σελίδας -Scale=Κλίμακα -ThumbView=Προεπισκόπηση -CurrentPage=Τρέχων σελίδα -Search=Αναζήτηση -NextPage=Επόμενη σελίδα -PreviousPage=Προηγούμενη σελίδα -Fullscreen=Πλήρης οθόνη -About=Σχετικά -Finishedsearching=Ολοκληρώθηκε η αναζήτηση του εγγράφου. Δε βρέθηκαν άλλες αντιστοιχίες -Searchfinished=Ολοκληρώθηκε η αναζήτηση -Selectprintrange=Επιλογή περιοχής εκτύπωσης -All=Όλα -CurrentPage=Τρέχων σελίδα -Pages=Σελίδες: -Enterpagenumbers=Καταχωρήστε αριθμό σελίδας και/ή περιοχή σελιδών διαχωρισμένες από κόμματα. Για παράδειγμα 1,3,5-12 -Cancel=Ακύρωση -IncorrectRange=Λάθος περιοχή -Incorrectrangespecified=Προσδιορισμός λάθος περιοχής -About=Σχετικά -Developedby=Δημιουργήθηκε από Devaldi. -Formoreinformation=Για περαιτέρω πληροφορίες, βλέπε -TwoPage=Δύο Σελίδα -SinglePage=Ενιαία Σελίδα \ No newline at end of file +# locale/el_EL/FlexPaper.properties +Print=\u0395\u03ba\u03c4\u03cd\u03c0\u03c9\u03c3\u03b7 +FitWidth=\u03a0\u03c1\u03bf\u03c3\u03b1\u03c1\u03bc\u03bf\u03b3\u03ae \u03c0\u03bb\u03ac\u03c4\u03bf\u03c2 +FitPage=\u03a0\u03c1\u03bf\u03c3\u03b1\u03c1\u03bc\u03bf\u03b3\u03ae \u03c3\u03b5\u03bb\u03af\u03b4\u03b1\u03c2 +Scale=\u039a\u03bb\u03af\u03bc\u03b1\u03ba\u03b1 +ThumbView=\u03a0\u03c1\u03bf\u03b5\u03c0\u03b9\u03c3\u03ba\u03cc\u03c0\u03b7\u03c3\u03b7 +CurrentPage=\u03a4\u03c1\u03ad\u03c7\u03c9\u03bd \u03c3\u03b5\u03bb\u03af\u03b4\u03b1 +Search=\u0391\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 +NextPage=\u0395\u03c0\u03cc\u03bc\u03b5\u03bd\u03b7 \u03c3\u03b5\u03bb\u03af\u03b4\u03b1 +PreviousPage=\u03a0\u03c1\u03bf\u03b7\u03b3\u03bf\u03cd\u03bc\u03b5\u03bd\u03b7 \u03c3\u03b5\u03bb\u03af\u03b4\u03b1 +Fullscreen=\u03a0\u03bb\u03ae\u03c1\u03b7\u03c2 \u03bf\u03b8\u03cc\u03bd\u03b7 +About=\u03a3\u03c7\u03b5\u03c4\u03b9\u03ba\u03ac +Finishedsearching=\u039f\u03bb\u03bf\u03ba\u03bb\u03b7\u03c1\u03ce\u03b8\u03b7\u03ba\u03b5 \u03b7 \u03b1\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 \u03c4\u03bf\u03c5 \u03b5\u03b3\u03b3\u03c1\u03ac\u03c6\u03bf\u03c5. \u0394\u03b5 \u03b2\u03c1\u03ad\u03b8\u03b7\u03ba\u03b1\u03bd \u03ac\u03bb\u03bb\u03b5\u03c2 \u03b1\u03bd\u03c4\u03b9\u03c3\u03c4\u03bf\u03b9\u03c7\u03af\u03b5\u03c2 +Searchfinished=\u039f\u03bb\u03bf\u03ba\u03bb\u03b7\u03c1\u03ce\u03b8\u03b7\u03ba\u03b5 \u03b7 \u03b1\u03bd\u03b1\u03b6\u03ae\u03c4\u03b7\u03c3\u03b7 +Selectprintrange=\u0395\u03c0\u03b9\u03bb\u03bf\u03b3\u03ae \u03c0\u03b5\u03c1\u03b9\u03bf\u03c7\u03ae\u03c2 \u03b5\u03ba\u03c4\u03cd\u03c0\u03c9\u03c3\u03b7\u03c2 +All=\u038c\u03bb\u03b1 +CurrentPage=\u03a4\u03c1\u03ad\u03c7\u03c9\u03bd \u03c3\u03b5\u03bb\u03af\u03b4\u03b1 +Pages=\u03a3\u03b5\u03bb\u03af\u03b4\u03b5\u03c2: +Enterpagenumbers=\u039a\u03b1\u03c4\u03b1\u03c7\u03c9\u03c1\u03ae\u03c3\u03c4\u03b5 \u03b1\u03c1\u03b9\u03b8\u03bc\u03cc \u03c3\u03b5\u03bb\u03af\u03b4\u03b1\u03c2 \u03ba\u03b1\u03b9/\u03ae \u03c0\u03b5\u03c1\u03b9\u03bf\u03c7\u03ae \u03c3\u03b5\u03bb\u03b9\u03b4\u03ce\u03bd \u03b4\u03b9\u03b1\u03c7\u03c9\u03c1\u03b9\u03c3\u03bc\u03ad\u03bd\u03b5\u03c2 \u03b1\u03c0\u03cc \u03ba\u03cc\u03bc\u03bc\u03b1\u03c4\u03b1. \u0393\u03b9\u03b1 \u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3\u03bc\u03b1 1,3,5-12 +Cancel=\u0391\u03ba\u03cd\u03c1\u03c9\u03c3\u03b7 +IncorrectRange=\u039b\u03ac\u03b8\u03bf\u03c2 \u03c0\u03b5\u03c1\u03b9\u03bf\u03c7\u03ae +Incorrectrangespecified=\u03a0\u03c1\u03bf\u03c3\u03b4\u03b9\u03bf\u03c1\u03b9\u03c3\u03bc\u03cc\u03c2 \u03bb\u03ac\u03b8\u03bf\u03c2 \u03c0\u03b5\u03c1\u03b9\u03bf\u03c7\u03ae\u03c2 +About=\u03a3\u03c7\u03b5\u03c4\u03b9\u03ba\u03ac +Developedby=\u0394\u03b7\u03bc\u03b9\u03bf\u03c5\u03c1\u03b3\u03ae\u03b8\u03b7\u03ba\u03b5 \u03b1\u03c0\u03cc Devaldi. +Formoreinformation=\u0393\u03b9\u03b1 \u03c0\u03b5\u03c1\u03b1\u03b9\u03c4\u03ad\u03c1\u03c9 \u03c0\u03bb\u03b7\u03c1\u03bf\u03c6\u03bf\u03c1\u03af\u03b5\u03c2, \u03b2\u03bb\u03ad\u03c0\u03b5 +TwoPage=\u0394\u03cd\u03bf \u03a3\u03b5\u03bb\u03af\u03b4\u03b1 +SinglePage=\u0395\u03bd\u03b9\u03b1\u03af\u03b1 \u03a3\u03b5\u03bb\u03af\u03b4\u03b1 \ No newline at end of file diff --git a/docviewerflex/locale/en_US/FlexPaper.properties b/docviewerflex/locale/en_US/FlexPaper.properties index aa3335c..0e7562b 100644 --- a/docviewerflex/locale/en_US/FlexPaper.properties +++ b/docviewerflex/locale/en_US/FlexPaper.properties @@ -1,30 +1,30 @@ -# locale/en_US/FlexPaper.properties -Print=Print -FitWidth=Fit Width -FitPage=Fit Page -Scale=Scale -ThumbView=Thumb View -CurrentPage=Current Page -Search=Search -NextPage=Next Page -PreviousPage=Previous Page -Fullscreen=Fullscreen -About=About -Finishedsearching=Finished searching the document. No more matches were found -Searchfinished=Search finished -Selectprintrange=Select print range -All=All -CurrentPage=Current Page -Pages=Pages: -Enterpagenumbers=Enter page numbers and/or page ranges separated by commas. For example 1,3,5-12 -Cancel=Cancel -IncorrectRange=Incorrect Range -Incorrectrangespecified=Incorrect range specified -About=About -Developedby=Developed by Devaldi. -Formoreinformation=For more information, see -CopyText=Copy Text -TwoPage=Two Pages -SinglePage=Single Page -FirstPage=First Page +# locale/en_US/FlexPaper.properties +Print=Print +FitWidth=Fit Width +FitPage=Fit Page +Scale=Scale +ThumbView=Thumb View +CurrentPage=Current Page +Search=Search +NextPage=Next Page +PreviousPage=Previous Page +Fullscreen=Fullscreen +About=About +Finishedsearching=Finished searching the document. No more matches were found +Searchfinished=Search finished +Selectprintrange=Select print range +All=All +CurrentPage=Current Page +Pages=Pages: +Enterpagenumbers=Enter page numbers and/or page ranges separated by commas. For example 1,3,5-12 +Cancel=Cancel +IncorrectRange=Incorrect Range +Incorrectrangespecified=Incorrect range specified +About=About +Developedby=Developed by Devaldi. +Formoreinformation=For more information, see +CopyText=Copy Text +TwoPage=Two Pages +SinglePage=Single Page +FirstPage=First Page LastPage=Last Page \ No newline at end of file diff --git a/docviewerflex/locale/es_ES/FlexPaper.properties b/docviewerflex/locale/es_ES/FlexPaper.properties index e972742..1400e6f 100644 --- a/docviewerflex/locale/es_ES/FlexPaper.properties +++ b/docviewerflex/locale/es_ES/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/es_ES/FlexPaper.properties -Print=Imprimir -FitWidth=Ajustar ancho -FitPage=Ajustar página -Scale=% Zoom -ThumbView=Vista en miniatura -CurrentPage=Página actual -Search=Buscar -NextPage=Página siguiente -PreviousPage=Página anterior -Fullscreen=Pantalla completa -About=Acerca de -Finishedsearching=Búsqueda finalizada. No se encontraron más coincidencias en el documento. -Searchfinished=Búsqueda finalizada -Selectprintrange=Selecciona el área a imprimir -All=Todo -CurrentPage=Página actual -Pages=Páginas: -Enterpagenumbers=Introducir los números de página y/o los rangos separados por comas. Por ejemplo: 1,3,5-12 -Cancel=Cancelar -IncorrectRange=Rango incorrecto -Incorrectrangespecified=El rango especificado no es correcto -About=Acerca de -Developedby=Developed by Devaldi. -Formoreinformation=For more information, see -TwoPage=Dos Page -SinglePage=sola página \ No newline at end of file +# locale/es_ES/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar ancho +FitPage=Ajustar p\u00e1gina +Scale=% Zoom +ThumbView=Vista en miniatura +CurrentPage=P\u00e1gina actual +Search=Buscar +NextPage=P\u00e1gina siguiente +PreviousPage=P\u00e1gina anterior +Fullscreen=Pantalla completa +About=Acerca de +Finishedsearching=B\u00fasqueda finalizada. No se encontraron m\u00e1s coincidencias en el documento. +Searchfinished=B\u00fasqueda finalizada +Selectprintrange=Selecciona el \u00e1rea a imprimir +All=Todo +CurrentPage=P\u00e1gina actual +Pages=P\u00e1ginas: +Enterpagenumbers=Introducir los n\u00fameros de p\u00e1gina y/o los rangos separados por comas. Por ejemplo: 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Rango incorrecto +Incorrectrangespecified=El rango especificado no es correcto +About=Acerca de +Developedby=Developed by Devaldi. +Formoreinformation=For more information, see +TwoPage=Dos Page +SinglePage=sola p\u00e1gina \ No newline at end of file diff --git a/docviewerflex/locale/fi_FN/FlexPaper.properties b/docviewerflex/locale/fi_FN/FlexPaper.properties index 7b2ca46..916519d 100644 --- a/docviewerflex/locale/fi_FN/FlexPaper.properties +++ b/docviewerflex/locale/fi_FN/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/fi_FN/FlexPaper.properties -Print=Tulosta -FitWidth=Sovita leveyteen -FitPage=Sovita sivulle -Scale=Muuta mittakaava -ThumbView=Pikkukuvanäkymä -CurrentPage=Nykyinen sivu -Search=Haku -NextPage=Seuraava sivu -PreviousPage=Edellinen sivu -Fullscreen=Kokoruutu -About=Tietoa aiheesta -Finishedsearching=Etsintä on valmis. Ei löytynyt uusia hakutuloksia. -Searchfinished=Haku päättynyt -Selectprintrange=Valitse tulostusalue -All=Kaikki -CurrentPage=Nykyinen sivu -Pages=Sivut: -Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 -Cancel=Peruuta -IncorrectRange=Väärä alue -Incorrectrangespecified=Virheellinen alue eriteltynä -About=Tietoa aiheesta -Developedby=Kehittämä Devaldi. -Formoreinformation=Saadaksesi lisätietoja, katso -TwoPage=Kaksi sivu +# locale/fi_FN/FlexPaper.properties +Print=Tulosta +FitWidth=Sovita leveyteen +FitPage=Sovita sivulle +Scale=Muuta mittakaava +ThumbView=Pikkukuvan\u00e4kym\u00e4 +CurrentPage=Nykyinen sivu +Search=Haku +NextPage=Seuraava sivu +PreviousPage=Edellinen sivu +Fullscreen=Kokoruutu +About=Tietoa aiheesta +Finishedsearching=Etsint\u00e4 on valmis. Ei l\u00f6ytynyt uusia hakutuloksia. +Searchfinished=Haku p\u00e4\u00e4ttynyt +Selectprintrange=Valitse tulostusalue +All=Kaikki +CurrentPage=Nykyinen sivu +Pages=Sivut: +Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 +Cancel=Peruuta +IncorrectRange=V\u00e4\u00e4r\u00e4 alue +Incorrectrangespecified=Virheellinen alue eriteltyn\u00e4 +About=Tietoa aiheesta +Developedby=Kehitt\u00e4m\u00e4 Devaldi. +Formoreinformation=Saadaksesi lis\u00e4tietoja, katso +TwoPage=Kaksi sivu SinglePage=Single sivu \ No newline at end of file diff --git a/docviewerflex/locale/fr_FR/FlexPaper.properties b/docviewerflex/locale/fr_FR/FlexPaper.properties index 7df4e0e..69cdbd0 100644 --- a/docviewerflex/locale/fr_FR/FlexPaper.properties +++ b/docviewerflex/locale/fr_FR/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/fr_FR/FlexPaper.properties -Print=Imprimer -FitWidth=Ajuster Largeur -FitPage=Ajuster Page -Scale=Zoom -ThumbView=Vignettes -CurrentPage=Page Courante -Search=Recherche -NextPage=Page Suivante -PreviousPage=Page Précédente -Fullscreen=Plein Ecran -About=A Propos -Finishedsearching=Recherche dans le document terminée. Pas d'autre ocurrence trouvée -Searchfinished=Recherche terminée -Selectprintrange=Etendue de l'impression -All=Tout -CurrentPage=Page Courante -Pages=Pages: -Enterpagenumbers=Entrez les numéros de page et/ou les intervalles de page séparés par des virgules. Par exemple 1,3,5-12 -Cancel=Annuler -IncorrectRange=Intervalle non valide -Incorrectrangespecified=Intervalle non valide spécifié -About=A Propos -Developedby=Développé par Devaldi. -Formoreinformation=Pour plus d'informations, allez sur -TwoPage=Deux Page +# locale/fr_FR/FlexPaper.properties +Print=Imprimer +FitWidth=Ajuster Largeur +FitPage=Ajuster Page +Scale=Zoom +ThumbView=Vignettes +CurrentPage=Page Courante +Search=Recherche +NextPage=Page Suivante +PreviousPage=Page Pr\u00e9c\u00e9dente +Fullscreen=Plein Ecran +About=A Propos +Finishedsearching=Recherche dans le document termin\u00e9e. Pas d'autre ocurrence trouv\u00e9e +Searchfinished=Recherche termin\u00e9e +Selectprintrange=Etendue de l'impression +All=Tout +CurrentPage=Page Courante +Pages=Pages: +Enterpagenumbers=Entrez les num\u00e9ros de page et/ou les intervalles de page s\u00e9par\u00e9s par des virgules. Par exemple 1,3,5-12 +Cancel=Annuler +IncorrectRange=Intervalle non valide +Incorrectrangespecified=Intervalle non valide sp\u00e9cifi\u00e9 +About=A Propos +Developedby=D\u00e9velopp\u00e9 par Devaldi. +Formoreinformation=Pour plus d'informations, allez sur +TwoPage=Deux Page SinglePage=Page unique \ No newline at end of file diff --git a/docviewerflex/locale/he_IL/FlexPaper.properties b/docviewerflex/locale/he_IL/FlexPaper.properties index 9765a29..9df8cf0 100644 --- a/docviewerflex/locale/he_IL/FlexPaper.properties +++ b/docviewerflex/locale/he_IL/FlexPaper.properties @@ -1,28 +1,28 @@ -# locale/he_IL/FlexPaper.properties -Print=הדפסה -FitWidth=התאם רוחב -FitPage=התאם עמוד -Scale=מידה -ThumbView=תמונות ממוזערות -CurrentPage=עמוד נוכחי -Search=חיפוש -NextPage=עמוד הבא -PreviousPage=עמוד קודם -Fullscreen=מסך מלא -About=אודות -Finishedsearching=החיפוש הסתיים ללא תוצאות -Searchfinished=החיפוש הסתיים -Selectprintrange=בחר טווח הדפסה -All=הכל -Pages=דפים: -Enterpagenumbers=הזן מספרי עמודים ו/או טווחי עמודים מופרדים בפיסוק. לדוגמא 1,3,5-12 -Cancel=ביטול -IncorrectRange=טווח שגואי -Incorrectrangespecified=הוזן טווח שגואי -Developedby=פותח על-ידי Devaldi. -Formoreinformation=לפרטים נוספים, צפה ב -CopyText=העתק טקסט -TwoPage=שני עמודים -SinglePage=עמוד בודד -FirstPage=עמוד ראשון -LastPage=עמוד אחרון \ No newline at end of file +# locale/he_IL/FlexPaper.properties +Print=\u05d4\u05d3\u05e4\u05e1\u05d4 +FitWidth=\u05d4\u05ea\u05d0\u05dd \u05e8\u05d5\u05d7\u05d1 +FitPage=\u05d4\u05ea\u05d0\u05dd \u05e2\u05de\u05d5\u05d3 +Scale=\u05de\u05d9\u05d3\u05d4 +ThumbView=\u05ea\u05de\u05d5\u05e0\u05d5\u05ea \u05de\u05de\u05d5\u05d6\u05e2\u05e8\u05d5\u05ea +CurrentPage=\u05e2\u05de\u05d5\u05d3 \u05e0\u05d5\u05db\u05d7\u05d9 +Search=\u05d7\u05d9\u05e4\u05d5\u05e9 +NextPage=\u05e2\u05de\u05d5\u05d3 \u05d4\u05d1\u05d0 +PreviousPage=\u05e2\u05de\u05d5\u05d3 \u05e7\u05d5\u05d3\u05dd +Fullscreen=\u05de\u05e1\u05da \u05de\u05dc\u05d0 +About=\u05d0\u05d5\u05d3\u05d5\u05ea +Finishedsearching=\u05d4\u05d7\u05d9\u05e4\u05d5\u05e9 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd \u05dc\u05dc\u05d0 \u05ea\u05d5\u05e6\u05d0\u05d5\u05ea +Searchfinished=\u05d4\u05d7\u05d9\u05e4\u05d5\u05e9 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd +Selectprintrange=\u05d1\u05d7\u05e8 \u05d8\u05d5\u05d5\u05d7 \u05d4\u05d3\u05e4\u05e1\u05d4 +All=\u05d4\u05db\u05dc +Pages=\u05d3\u05e4\u05d9\u05dd: +Enterpagenumbers=\u05d4\u05d6\u05df \u05de\u05e1\u05e4\u05e8\u05d9 \u05e2\u05de\u05d5\u05d3\u05d9\u05dd \u05d5/\u05d0\u05d5 \u05d8\u05d5\u05d5\u05d7\u05d9 \u05e2\u05de\u05d5\u05d3\u05d9\u05dd \u05de\u05d5\u05e4\u05e8\u05d3\u05d9\u05dd \u05d1\u05e4\u05d9\u05e1\u05d5\u05e7. \u05dc\u05d3\u05d5\u05d2\u05de\u05d0 1,3,5-12 +Cancel=\u05d1\u05d9\u05d8\u05d5\u05dc +IncorrectRange=\u05d8\u05d5\u05d5\u05d7 \u05e9\u05d2\u05d5\u05d0\u05d9 +Incorrectrangespecified=\u05d4\u05d5\u05d6\u05df \u05d8\u05d5\u05d5\u05d7 \u05e9\u05d2\u05d5\u05d0\u05d9 +Developedby=\u05e4\u05d5\u05ea\u05d7 \u05e2\u05dc-\u05d9\u05d3\u05d9 Devaldi. +Formoreinformation=\u05dc\u05e4\u05e8\u05d8\u05d9\u05dd \u05e0\u05d5\u05e1\u05e4\u05d9\u05dd, \u05e6\u05e4\u05d4 \u05d1 +CopyText=\u05d4\u05e2\u05ea\u05e7 \u05d8\u05e7\u05e1\u05d8 +TwoPage=\u05e9\u05e0\u05d9 \u05e2\u05de\u05d5\u05d3\u05d9\u05dd +SinglePage=\u05e2\u05de\u05d5\u05d3 \u05d1\u05d5\u05d3\u05d3 +FirstPage=\u05e2\u05de\u05d5\u05d3 \u05e8\u05d0\u05e9\u05d5\u05df +LastPage=\u05e2\u05de\u05d5\u05d3 \u05d0\u05d7\u05e8\u05d5\u05df \ No newline at end of file diff --git a/docviewerflex/locale/hu_HU/FlexPaper.properties b/docviewerflex/locale/hu_HU/FlexPaper.properties index b61ae0f..20439dd 100644 --- a/docviewerflex/locale/hu_HU/FlexPaper.properties +++ b/docviewerflex/locale/hu_HU/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/hu_HU/FlexPaper.properties -Print=Nyomtatás -FitWidth=Oldalszélességhze igazít -FitPage=Lapszélességhez igazít -Scale=Nagyítás -ThumbView=Miniatürök -CurrentPage=Aktuális oldal -Search=Keresés -NextPage=Következő oldal -PreviousPage=Előző oldal -Fullscreen=Teljes képernyő -About=Névjegy -Finishedsearching=A dokumentum keresése befejeződött. Nincs több találat -Searchfinished=A keresés befejeződött -Selectprintrange=A nyomatási tartomány kiválasztása -All=Összes -CurrentPage=Aktuális oldal -Pages=Oldalak: -Enterpagenumbers=Írja be az oldalakat és/vagy a tartományokat vesszővel elválasztva. Például: 1,3,5-12 -Cancel=Mégse -IncorrectRange=Rossz tartomány -Incorrectrangespecified=Rossz tartományt adott meg -About=Névjegy -Developedby=Fejlesztő Devaldi. -Formoreinformation=További információk -TwoPage=Két oldal +# locale/hu_HU/FlexPaper.properties +Print=Nyomtat\u00e1s +FitWidth=Oldalsz\u00e9less\u00e9ghze igaz\u00edt +FitPage=Lapsz\u00e9less\u00e9ghez igaz\u00edt +Scale=Nagy\u00edt\u00e1s +ThumbView=Miniat\u00fcr\u00f6k +CurrentPage=Aktu\u00e1lis oldal +Search=Keres\u00e9s +NextPage=K\u00f6vetkez\u0151 oldal +PreviousPage=El\u0151z\u0151 oldal +Fullscreen=Teljes k\u00e9perny\u0151 +About=N\u00e9vjegy +Finishedsearching=A dokumentum keres\u00e9se befejez\u0151d\u00f6tt. Nincs t\u00f6bb tal\u00e1lat +Searchfinished=A keres\u00e9s befejez\u0151d\u00f6tt +Selectprintrange=A nyomat\u00e1si tartom\u00e1ny kiv\u00e1laszt\u00e1sa +All=\u00d6sszes +CurrentPage=Aktu\u00e1lis oldal +Pages=Oldalak: +Enterpagenumbers=\u00cdrja be az oldalakat \u00e9s/vagy a tartom\u00e1nyokat vessz\u0151vel elv\u00e1lasztva. P\u00e9ld\u00e1ul: 1,3,5-12 +Cancel=M\u00e9gse +IncorrectRange=Rossz tartom\u00e1ny +Incorrectrangespecified=Rossz tartom\u00e1nyt adott meg +About=N\u00e9vjegy +Developedby=Fejleszt\u0151 Devaldi. +Formoreinformation=Tov\u00e1bbi inform\u00e1ci\u00f3k +TwoPage=K\u00e9t oldal SinglePage=egyetlen oldalon \ No newline at end of file diff --git a/docviewerflex/locale/it_IT/FlexPaper.properties b/docviewerflex/locale/it_IT/FlexPaper.properties index 79c5046..d486e8c 100644 --- a/docviewerflex/locale/it_IT/FlexPaper.properties +++ b/docviewerflex/locale/it_IT/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/it_IT/FlexPaper.properties -Print=Stampa -FitWidth=Adatta Larghezza -FitPage=Adatta Pagina -Scale=Scala -ThumbView=Vista Anteprima -CurrentPage=Pagina Corrente -Search=Ricerca -NextPage=Pagina Seguente -PreviousPage=Pagina precedente -Fullscreen=Fullscreen -About=Su -Finishedsearching=Finita la ricerca nel documento . Trovata nienta occorenza di più. -Searchfinished=Ricerca finita -Selectprintrange=Selezionare la portata di stampa -All=Tutto -CurrentPage=Pagina corrente -Pages=Pagine: -Enterpagenumbers=Immettere i numeri di pagina e/o gli intervalli pagina separati da virgole. Es. 1,3,5-12 -Cancel=Annulla -IncorrectRange=Gamma sbagliata -Incorrectrangespecified=Gamma specificata sbagliata -About=Su -Developedby=Sviluppato da Devaldi. -Formoreinformation=Per più d'informazioni, si prega di visitare -TwoPage=Due pagina +# locale/it_IT/FlexPaper.properties +Print=Stampa +FitWidth=Adatta Larghezza +FitPage=Adatta Pagina +Scale=Scala +ThumbView=Vista Anteprima +CurrentPage=Pagina Corrente +Search=Ricerca +NextPage=Pagina Seguente +PreviousPage=Pagina precedente +Fullscreen=Fullscreen +About=Su +Finishedsearching=Finita la ricerca nel documento . Trovata nienta occorenza di pi\u00f9. +Searchfinished=Ricerca finita +Selectprintrange=Selezionare la portata di stampa +All=Tutto +CurrentPage=Pagina corrente +Pages=Pagine: +Enterpagenumbers=Immettere i numeri di pagina e/o gli intervalli pagina separati da virgole. Es. 1,3,5-12 +Cancel=Annulla +IncorrectRange=Gamma sbagliata +Incorrectrangespecified=Gamma specificata sbagliata +About=Su +Developedby=Sviluppato da Devaldi. +Formoreinformation=Per pi\u00f9 d'informazioni, si prega di visitare +TwoPage=Due pagina SinglePage=singola pagina \ No newline at end of file diff --git a/docviewerflex/locale/nl_NL/FlexPaper.properties b/docviewerflex/locale/nl_NL/FlexPaper.properties index 95ea696..41a323e 100644 --- a/docviewerflex/locale/nl_NL/FlexPaper.properties +++ b/docviewerflex/locale/nl_NL/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/nl_NL/FlexPaper.properties -Print=Print -FitWidth=Passend maken breedte -FitPage=Passend maken pagina -Scale=Schaal -ThumbView=Thumb bekijken -CurrentPage=Huidige pagina -Search=Zoeken -NextPage=Volgende pagina -PreviousPage=Vorige pagina -Fullscreen=Volledig Scherm -About=Over -Finishedsearching=Klaar met doorzoeken document. Er zijn geen matches meer gevonden -Searchfinished=Zoek is klaar -Selectprintrange=Selecteer de print range -All=Alle -CurrentPage=Huidige pagina -Pages=Paginas: -Enterpagenumbers=Voer paginanummers in en/of pagina schalen gescheiden door commas. Bijvoorbeeld 1,3,5-12 -Cancel=Annuleren -IncorrectRange=Foute range -Incorrectrangespecified=Foute range ingevoerd -About=Over -Developedby=Ontwikkeld door Devaldi. -Formoreinformation=Voor meer informatie, zie -TwoPage=Twee pagina +# locale/nl_NL/FlexPaper.properties +Print=Print +FitWidth=Passend maken breedte +FitPage=Passend maken pagina +Scale=Schaal +ThumbView=Thumb bekijken +CurrentPage=Huidige pagina +Search=Zoeken +NextPage=Volgende pagina +PreviousPage=Vorige pagina +Fullscreen=Volledig Scherm +About=Over +Finishedsearching=Klaar met doorzoeken document. Er zijn geen matches meer gevonden +Searchfinished=Zoek is klaar +Selectprintrange=Selecteer de print range +All=Alle +CurrentPage=Huidige pagina +Pages=Paginas: +Enterpagenumbers=Voer paginanummers in en/of pagina schalen gescheiden door commas. Bijvoorbeeld 1,3,5-12 +Cancel=Annuleren +IncorrectRange=Foute range +Incorrectrangespecified=Foute range ingevoerd +About=Over +Developedby=Ontwikkeld door Devaldi. +Formoreinformation=Voor meer informatie, zie +TwoPage=Twee pagina SinglePage=Single pagina \ No newline at end of file diff --git a/docviewerflex/locale/pl_PL/FlexPaper.properties b/docviewerflex/locale/pl_PL/FlexPaper.properties index d607138..33a4f54 100644 --- a/docviewerflex/locale/pl_PL/FlexPaper.properties +++ b/docviewerflex/locale/pl_PL/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/pl_PL/FlexPaper.properties -Print=Drukuj -FitWidth=Dopasuj do szerokości -FitPage=Dopasuj do strony -Scale=Skaluj -ThumbView=Widok miniaturek -CurrentPage=Obecna strona -Search=Szukaj -NextPage=Następna strona -PreviousPage=Poprzednia strona -Fullscreen=Pełny ekran -About=O -Finishedsearching=Wyszukiwanie zakończone, nic więcej nie znaleziono -Searchfinished=Wyszukiwanie zakończone -Selectprintrange=Wybierz zakres wydruku -All=Wszystkie -CurrentPage=Obecna strona -Pages=Strony: -Enterpagenumbers=Podaj numery stron lub zakres, np. 1,3,5-12 -Cancel=Anuluj -IncorrectRange=Niepoprawny zakres -Incorrectrangespecified=Niepoprawny zakres -About=O -Developedby=Stworzony przez Devaldi. -Formoreinformation=Aby uzyskać więcej informacji zobacz -TwoPage=Dwie strony +# locale/pl_PL/FlexPaper.properties +Print=Drukuj +FitWidth=Dopasuj do szeroko\u015bci +FitPage=Dopasuj do strony +Scale=Skaluj +ThumbView=Widok miniaturek +CurrentPage=Obecna strona +Search=Szukaj +NextPage=Nast\u0119pna strona +PreviousPage=Poprzednia strona +Fullscreen=Pe\u0142ny ekran +About=O +Finishedsearching=Wyszukiwanie zako\u0144czone, nic wi\u0119cej nie znaleziono +Searchfinished=Wyszukiwanie zako\u0144czone +Selectprintrange=Wybierz zakres wydruku +All=Wszystkie +CurrentPage=Obecna strona +Pages=Strony: +Enterpagenumbers=Podaj numery stron lub zakres, np. 1,3,5-12 +Cancel=Anuluj +IncorrectRange=Niepoprawny zakres +Incorrectrangespecified=Niepoprawny zakres +About=O +Developedby=Stworzony przez Devaldi. +Formoreinformation=Aby uzyska\u0107 wi\u0119cej informacji zobacz +TwoPage=Dwie strony SinglePage=jednej stronie \ No newline at end of file diff --git a/docviewerflex/locale/pt_BR/FlexPaper.properties b/docviewerflex/locale/pt_BR/FlexPaper.properties index ddcc8f8..34c927f 100644 --- a/docviewerflex/locale/pt_BR/FlexPaper.properties +++ b/docviewerflex/locale/pt_BR/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/pt_BR/FlexPaper.properties -Print=Imprimir -FitWidth=Ajustar Largura -FitPage=Ajustar Página -Scale=Escala -ThumbView=Ver Miniaturas -CurrentPage=Página atual -Search=Pesquisa -NextPage=Próxima página -PreviousPage=Página Anterior -Fullscreen=Tela cheia -About=Sobre -Finishedsearching=Terminou a procura no documento. Mais candidatos não foram encontrados -Searchfinished=Pesquisa concluída -Selectprintrange=Selecione o intervalo de impressão -All=Todos -CurrentPage=Página atual -Pages=Páginas: -Enterpagenumbers=Digite os números das páginas e / ou intervalos das páginas separados por vírgulas. Por exemplo, 1,3,5-12 -Cancel=Cancelar -IncorrectRange=Ordem incorreta -Incorrectrangespecified=Ordem especificada incorreta -About=Sobre -Developedby=Desenvolvido por Devaldi. -Formoreinformation=Para obter mais informações, consulte: -TwoPage=Duas Páginas -SinglePage=Página Única \ No newline at end of file +# locale/pt_BR/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar Largura +FitPage=Ajustar P\u00e1gina +Scale=Escala +ThumbView=Ver Miniaturas +CurrentPage=P\u00e1gina atual +Search=Pesquisa +NextPage=Pr\u00f3xima p\u00e1gina +PreviousPage=P\u00e1gina Anterior +Fullscreen=Tela cheia +About=Sobre +Finishedsearching=Terminou a procura no documento. Mais candidatos n\u00e3o foram encontrados +Searchfinished=Pesquisa conclu\u00edda +Selectprintrange=Selecione o intervalo de impress\u00e3o +All=Todos +CurrentPage=P\u00e1gina atual +Pages=P\u00e1ginas: +Enterpagenumbers=Digite os n\u00fameros das p\u00e1ginas e / ou intervalos das p\u00e1ginas separados por v\u00edrgulas. Por exemplo, 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Ordem incorreta +Incorrectrangespecified=Ordem especificada incorreta +About=Sobre +Developedby=Desenvolvido por Devaldi. +Formoreinformation=Para obter mais informa\u00e7\u00f5es, consulte: +TwoPage=Duas P\u00e1ginas +SinglePage=P\u00e1gina \u00danica \ No newline at end of file diff --git a/docviewerflex/locale/pt_PT/FlexPaper.properties b/docviewerflex/locale/pt_PT/FlexPaper.properties index 77f059f..79741d3 100644 --- a/docviewerflex/locale/pt_PT/FlexPaper.properties +++ b/docviewerflex/locale/pt_PT/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/pt_PT/FlexPaper.properties -Print=Imprimir -FitWidth=Ajustar Largura -FitPage=Ajustar Página -Scale=Escala -ThumbView=Ver Polegar -CurrentPage=Página atual -Search=Pesquisa -NextPage=Próxima página -PreviousPage=Página precedente -Fullscreen=Ecrã cheio -About=Sobre -Finishedsearching=Terminou a procura no documento. Mais competidores não foram encontrados -Searchfinished=Pesquisa concluída -Selectprintrange=Seleccione o intervalo de impressão -All=Todos -CurrentPage=Página actual -Pages=Páginas: -Enterpagenumbers=Digite os números das páginas e / ou intervalos das páginas separados por vírgulas. Por exemplo 1,3,5-12 -Cancel=Cancelar -IncorrectRange=Ordem incorreta -Incorrectrangespecified=Ordem especificada incorreta -About=Sobre -Developedby=Developed by Devaldi. -Formoreinformation=Para obter mais informações, consulte: -TwoPage=Dois Página -SinglePage=Página Única \ No newline at end of file +# locale/pt_PT/FlexPaper.properties +Print=Imprimir +FitWidth=Ajustar Largura +FitPage=Ajustar P\u00e1gina +Scale=Escala +ThumbView=Ver Polegar +CurrentPage=P\u00e1gina atual +Search=Pesquisa +NextPage=Pr\u00f3xima p\u00e1gina +PreviousPage=P\u00e1gina precedente +Fullscreen=Ecr\u00e3 cheio +About=Sobre +Finishedsearching=Terminou a procura no documento. Mais competidores n\u00e3o foram encontrados +Searchfinished=Pesquisa conclu\u00edda +Selectprintrange=Seleccione o intervalo de impress\u00e3o +All=Todos +CurrentPage=P\u00e1gina actual +Pages=P\u00e1ginas: +Enterpagenumbers=Digite os n\u00fameros das p\u00e1ginas e / ou intervalos das p\u00e1ginas separados por v\u00edrgulas. Por exemplo 1,3,5-12 +Cancel=Cancelar +IncorrectRange=Ordem incorreta +Incorrectrangespecified=Ordem especificada incorreta +About=Sobre +Developedby=Developed by Devaldi. +Formoreinformation=Para obter mais informa\u00e7\u00f5es, consulte: +TwoPage=Dois P\u00e1gina +SinglePage=P\u00e1gina \u00danica \ No newline at end of file diff --git a/docviewerflex/locale/pv_FN/FlexPaper.properties b/docviewerflex/locale/pv_FN/FlexPaper.properties index 6467da0..e19053a 100644 --- a/docviewerflex/locale/pv_FN/FlexPaper.properties +++ b/docviewerflex/locale/pv_FN/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/pv_FN/FlexPaper.properties -Print=Tulosta -FitWidth=Sovita leveyteen -FitPage=Sovita sivulle -Scale=Muuta mittakaava -ThumbView=Pikkukuvanäkymä -CurrentPage=Nykyinen sivu -Search=Haku -NextPage=Seuraava sivu -PreviousPage=Edellinen sivu -Fullscreen=Kokoruutu -About=Tietoa aiheesta -Finishedsearching=Etsintä on valmis. Ei löytynyt uusia hakutuloksia. -Searchfinished=Haku päättynyt -Selectprintrange=Valitse tulostusalue -All=Kaikki -CurrentPage=Nykyinen sivu -Pages=Sivut: -Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 -Cancel=Peruuta -IncorrectRange=Väärä alue -Incorrectrangespecified=Virheellinen alue eriteltynä -About=Tietoa aiheesta -Developedby=Devaldi Group. -Formoreinformation=Saadaksesi lisätietoja, katso -TwoPage=Kaksi sivu +# locale/pv_FN/FlexPaper.properties +Print=Tulosta +FitWidth=Sovita leveyteen +FitPage=Sovita sivulle +Scale=Muuta mittakaava +ThumbView=Pikkukuvan\u00e4kym\u00e4 +CurrentPage=Nykyinen sivu +Search=Haku +NextPage=Seuraava sivu +PreviousPage=Edellinen sivu +Fullscreen=Kokoruutu +About=Tietoa aiheesta +Finishedsearching=Etsint\u00e4 on valmis. Ei l\u00f6ytynyt uusia hakutuloksia. +Searchfinished=Haku p\u00e4\u00e4ttynyt +Selectprintrange=Valitse tulostusalue +All=Kaikki +CurrentPage=Nykyinen sivu +Pages=Sivut: +Enterpagenumbers=Anna sivunumerot ja / tai sivualueet pilkulla eroteltuina. Esimerkiksi 1,3,5-12 +Cancel=Peruuta +IncorrectRange=V\u00e4\u00e4r\u00e4 alue +Incorrectrangespecified=Virheellinen alue eriteltyn\u00e4 +About=Tietoa aiheesta +Developedby=Devaldi Group. +Formoreinformation=Saadaksesi lis\u00e4tietoja, katso +TwoPage=Kaksi sivu SinglePage=Single sivu \ No newline at end of file diff --git a/docviewerflex/locale/ru_RU/FlexPaper.properties b/docviewerflex/locale/ru_RU/FlexPaper.properties index ebbf3a4..24a04d5 100644 --- a/docviewerflex/locale/ru_RU/FlexPaper.properties +++ b/docviewerflex/locale/ru_RU/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/ru_RU/FlexPaper.properties -Print=Печать -FitWidth=По ширине -FitPage=По высоте -Scale=Масштаб -ThumbView=Эксизы -CurrentPage=Текущая страница -Search=Поиск -NextPage=Следующая -PreviousPage=Предыдущая -Fullscreen=Полноэкранный вид -About=О проекте -Finishedsearching=Поиск в документе завершен. Результатов не найдено. -Searchfinished=Поиск окончен. -Selectprintrange=Выберите страницы для печати -All=Все -CurrentPage=Только текущая -Pages=Выбор: -Enterpagenumbers=Укажите номера и/или диапазоны страниц через запятую. Например 1,3, 5-12 -Cancel=Отмена -IncorrectRange=Неправильный диапазон -Incorrectrangespecified=Неправильно указан диапазон -About=О проекте -Developedby=Разработано Devaldi. -Formoreinformation=Доп. информация: -TwoPage=Две страницы -SinglePage=Одна страница +# locale/ru_RU/FlexPaper.properties +Print=\u041f\u0435\u0447\u0430\u0442\u044c +FitWidth=\u041f\u043e \u0448\u0438\u0440\u0438\u043d\u0435 +FitPage=\u041f\u043e \u0432\u044b\u0441\u043e\u0442\u0435 +Scale=\u041c\u0430\u0441\u0448\u0442\u0430\u0431 +ThumbView=\u042d\u043a\u0441\u0438\u0437\u044b +CurrentPage=\u0422\u0435\u043a\u0443\u0449\u0430\u044f \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 +Search=\u041f\u043e\u0438\u0441\u043a +NextPage=\u0421\u043b\u0435\u0434\u0443\u044e\u0449\u0430\u044f +PreviousPage=\u041f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0430\u044f +Fullscreen=\u041f\u043e\u043b\u043d\u043e\u044d\u043a\u0440\u0430\u043d\u043d\u044b\u0439 \u0432\u0438\u0434 +About=\u041e \u043f\u0440\u043e\u0435\u043a\u0442\u0435 +Finishedsearching=\u041f\u043e\u0438\u0441\u043a \u0432 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043d. \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u0432 \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u043e. +Searchfinished=\u041f\u043e\u0438\u0441\u043a \u043e\u043a\u043e\u043d\u0447\u0435\u043d. +Selectprintrange=\u0412\u044b\u0431\u0435\u0440\u0438\u0442\u0435 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u044b \u0434\u043b\u044f \u043f\u0435\u0447\u0430\u0442\u0438 +All=\u0412\u0441\u0435 +CurrentPage=\u0422\u043e\u043b\u044c\u043a\u043e \u0442\u0435\u043a\u0443\u0449\u0430\u044f +Pages=\u0412\u044b\u0431\u043e\u0440: +Enterpagenumbers=\u0423\u043a\u0430\u0436\u0438\u0442\u0435 \u043d\u043e\u043c\u0435\u0440\u0430 \u0438/\u0438\u043b\u0438 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d\u044b \u0441\u0442\u0440\u0430\u043d\u0438\u0446 \u0447\u0435\u0440\u0435\u0437 \u0437\u0430\u043f\u044f\u0442\u0443\u044e. \u041d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 1,3, 5-12 +Cancel=\u041e\u0442\u043c\u0435\u043d\u0430 +IncorrectRange=\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d +Incorrectrangespecified=\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e \u0443\u043a\u0430\u0437\u0430\u043d \u0434\u0438\u0430\u043f\u0430\u0437\u043e\u043d +About=\u041e \u043f\u0440\u043e\u0435\u043a\u0442\u0435 +Developedby=\u0420\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043e Devaldi. +Formoreinformation=\u0414\u043e\u043f. \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f: +TwoPage=\u0414\u0432\u0435 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u044b +SinglePage=\u041e\u0434\u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430 diff --git a/docviewerflex/locale/se_SE/FlexPaper.properties b/docviewerflex/locale/se_SE/FlexPaper.properties index 18e00df..d305347 100644 --- a/docviewerflex/locale/se_SE/FlexPaper.properties +++ b/docviewerflex/locale/se_SE/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/se_SE/FlexPaper.properties -Print=Skriv ut -FitWidth=Anpassa efter bredd -FitPage=Anpassa efter sida -Scale=Skala -ThumbView=Visa miniatyrer -CurrentPage=Aktuell sida -Search=Sök -NextPage=Nästa sida -PreviousPage=Föregående sida -Fullscreen=Helskärm -About=Om -Finishedsearching=Sökning i dokumentet har avslutats. Hittade inte fler träffar. -Searchfinished=Sökning avslutad -Selectprintrange=Välj utskriftsområde -All=Alla -CurrentPage=Aktuell sida -Pages=Sidor: -Enterpagenumbers=Ange sidnummer och/eller sidintervall avgränsade med kommatecken, t ex 1,3,5-12 -Cancel=Avbryt -IncorrectRange=Felaktigt intervall -Incorrectrangespecified=Felaktigt intervall har specifierats -About=Om -Developedby=Utvecklad av Devaldi. -Formoreinformation=För mer information, se -TwoPage=Dubbel sidvy +# locale/se_SE/FlexPaper.properties +Print=Skriv ut +FitWidth=Anpassa efter bredd +FitPage=Anpassa efter sida +Scale=Skala +ThumbView=Visa miniatyrer +CurrentPage=Aktuell sida +Search=S\u00f6k +NextPage=N\u00e4sta sida +PreviousPage=F\u00f6reg\u00e5ende sida +Fullscreen=Helsk\u00e4rm +About=Om +Finishedsearching=S\u00f6kning i dokumentet har avslutats. Hittade inte fler tr\u00e4ffar. +Searchfinished=S\u00f6kning avslutad +Selectprintrange=V\u00e4lj utskriftsomr\u00e5de +All=Alla +CurrentPage=Aktuell sida +Pages=Sidor: +Enterpagenumbers=Ange sidnummer och/eller sidintervall avgr\u00e4nsade med kommatecken, t ex 1,3,5-12 +Cancel=Avbryt +IncorrectRange=Felaktigt intervall +Incorrectrangespecified=Felaktigt intervall har specifierats +About=Om +Developedby=Utvecklad av Devaldi. +Formoreinformation=F\u00f6r mer information, se +TwoPage=Dubbel sidvy SinglePage=Enkel sida \ No newline at end of file diff --git a/docviewerflex/locale/tr_TR/FlexPaper.properties b/docviewerflex/locale/tr_TR/FlexPaper.properties index 6a16ede..f63e41a 100644 --- a/docviewerflex/locale/tr_TR/FlexPaper.properties +++ b/docviewerflex/locale/tr_TR/FlexPaper.properties @@ -1,26 +1,26 @@ -# locale/tr_TR/FlexPaper.properties -Print=Yazdır -FitWidth=En uygun genişlik -FitPage=En uygun sayfa -Scale=Ölçekle -ThumbView=Gözetle -CurrentPage=Şimdiki sayfa -Search=Ara -NextPage=Sonraki sayfa -PreviousPage=Önceki sayfa -Fullscreen=Tam ekran -About=Hakkında -Finishedsearching=Dökümanı arama bitti. Eşleştirme bulunamadı -Searchfinished=Arama bitti -Selectprintrange=Yazdırma aralığını seç -All=Bütün -CurrentPage=Şimdiki sayfa -Pages=Sayfalar: -Enterpagenumbers=Virgülle aytılmış sayfa numaralarını gir Örneğin 1,3,5-12 -Cancel=İptal -IncorrectRange=Yanlış dizi -Incorrectrangespecified=Yanlış dizi tanımlanmış -Developedby=By Devaldi Group. -Formoreinformation=Daha fazla bilgi için... -TwoPage=İki Sayfa +# locale/tr_TR/FlexPaper.properties +Print=Yazd\u0131r +FitWidth=En uygun geni\u015flik +FitPage=En uygun sayfa +Scale=\u00d6l\u00e7ekle +ThumbView=G\u00f6zetle +CurrentPage=\u015eimdiki sayfa +Search=Ara +NextPage=Sonraki sayfa +PreviousPage=\u00d6nceki sayfa +Fullscreen=Tam ekran +About=Hakk\u0131nda +Finishedsearching=D\u00f6k\u00fcman\u0131 arama bitti. E\u015fle\u015ftirme bulunamad\u0131 +Searchfinished=Arama bitti +Selectprintrange=Yazd\u0131rma aral\u0131\u011f\u0131n\u0131 se\u00e7 +All=B\u00fct\u00fcn +CurrentPage=\u015eimdiki sayfa +Pages=Sayfalar: +Enterpagenumbers=Virg\u00fclle ayt\u0131lm\u0131\u015f sayfa numaralar\u0131n\u0131 gir \u00d6rne\u011fin 1,3,5-12 +Cancel=\u0130ptal +IncorrectRange=Yanl\u0131\u015f dizi +Incorrectrangespecified=Yanl\u0131\u015f dizi tan\u0131mlanm\u0131\u015f +Developedby=By Devaldi Group. +Formoreinformation=Daha fazla bilgi i\u00e7in... +TwoPage=\u0130ki Sayfa SinglePage=Tek Sayfa \ No newline at end of file diff --git a/docviewerflex/locale/zh_CN/DocViewer.properties b/docviewerflex/locale/zh_CN/DocViewer.properties new file mode 100644 index 0000000..5a34646 --- /dev/null +++ b/docviewerflex/locale/zh_CN/DocViewer.properties @@ -0,0 +1,3 @@ +# locale/zh_CN/DocViewer.properties +information=\u4e00\u4e2a\u6587\u6863\u5728\u7ebf\u9605\u8bfb\u7684JAVA\u4f01\u4e1a\u7ea7\u89e3\u51b3\u65b9\u6848\u3002 +developedBy=IntelligentCode \ No newline at end of file diff --git a/docviewerflex/locale/zh_CN/FlexPaper.properties b/docviewerflex/locale/zh_CN/FlexPaper.properties index 378dbc1..d9c90fb 100644 --- a/docviewerflex/locale/zh_CN/FlexPaper.properties +++ b/docviewerflex/locale/zh_CN/FlexPaper.properties @@ -1,27 +1,27 @@ -# locale/zh_CN/FlexPaper.properties -Print=打印 -FitWidth=适合宽度 -FitPage=适合整页 -Scale=缩放 -ThumbView=缩略图 -CurrentPage=当前页 -Search=搜索 -NextPage=下一页 -PreviousPage=上一页 -Fullscreen=全屏 -About=关于 -Finishedsearching=文档搜索完成.没有发现更多 的匹配. -Searchfinished=搜索完成 -Selectprintrange=选择打印范围 -All=所有页 -CurrentPage=当前页 -Pages=页范围: -Enterpagenumbers=输 入页码,用逗号分割各页.例如 1,3,5-12 -Cancel=取消 -IncorrectRange=页范围输入不正确 -Incorrectrangespecified=没有按照规定输入页范围 -About=关于 -Developedby=开发者 Devaldi. -Formoreinformation=需要了解更多信息,请参见 -TwoPage=第二页 -SinglePage=单页 \ No newline at end of file +# locale/zh_CN/FlexPaper.properties +Print=\u6253\u5370 +FitWidth=\u9002\u5408\u5bbd\u5ea6 +FitPage=\u9002\u5408\u6574\u9875 +Scale=\u7f29\u653e +ThumbView=\u7f29\u7565\u56fe +CurrentPage=\u5f53\u524d\u9875 +Search=\u641c\u7d22 +NextPage=\u4e0b\u4e00\u9875 +PreviousPage=\u4e0a\u4e00\u9875 +Fullscreen=\u5168\u5c4f +About=\u5173\u4e8e +Finishedsearching=\u6587\u6863\u641c\u7d22\u5b8c\u6210.\u6ca1\u6709\u53d1\u73b0\u66f4\u591a \u7684\u5339\u914d. +Searchfinished=\u641c\u7d22\u5b8c\u6210 +Selectprintrange=\u9009\u62e9\u6253\u5370\u8303\u56f4 +All=\u6240\u6709\u9875 +CurrentPage=\u5f53\u524d\u9875 +Pages=\u9875\u8303\u56f4: +Enterpagenumbers=\u8f93 \u5165\u9875\u7801,\u7528\u9017\u53f7\u5206\u5272\u5404\u9875.\u4f8b\u5982 1,3,5-12 +Cancel=\u53d6\u6d88 +IncorrectRange=\u9875\u8303\u56f4\u8f93\u5165\u4e0d\u6b63\u786e +Incorrectrangespecified=\u6ca1\u6709\u6309\u7167\u89c4\u5b9a\u8f93\u5165\u9875\u8303\u56f4 +About=\u5173\u4e8e +Developedby=\u5f00\u53d1\u8005 Devaldi. +Formoreinformation=\u9700\u8981\u4e86\u89e3\u66f4\u591a\u4fe1\u606f,\u8bf7\u53c2\u89c1 +TwoPage=\u7b2c\u4e8c\u9875 +SinglePage=\u5355\u9875 \ No newline at end of file diff --git a/docviewerflex/module_docviewerflex.xml b/docviewerflex/module_docviewerflex.xml index 86032f2..d5613bb 100644 --- a/docviewerflex/module_docviewerflex.xml +++ b/docviewerflex/module_docviewerflex.xml @@ -8,8 +8,8 @@ - - + + @@ -47,7 +47,7 @@ - + @@ -68,15 +68,15 @@ - + - + - + diff --git a/docviewerflex/resources/bar.gif b/docviewerflex/resources/bar.gif new file mode 100644 index 0000000..9db4bbc Binary files /dev/null and b/docviewerflex/resources/bar.gif differ diff --git a/docviewerflex/resources/blank.gif b/docviewerflex/resources/blank.gif new file mode 100644 index 0000000..de3bed6 Binary files /dev/null and b/docviewerflex/resources/blank.gif differ diff --git a/docviewerflex/resources/find.gif b/docviewerflex/resources/find.gif new file mode 100644 index 0000000..633c1f8 Binary files /dev/null and b/docviewerflex/resources/find.gif differ diff --git a/docviewerflex/resources/fit.gif b/docviewerflex/resources/fit.gif new file mode 100644 index 0000000..9cf7c9e Binary files /dev/null and b/docviewerflex/resources/fit.gif differ diff --git a/docviewerflex/resources/fullscreen.gif b/docviewerflex/resources/fullscreen.gif new file mode 100644 index 0000000..c3f1925 Binary files /dev/null and b/docviewerflex/resources/fullscreen.gif differ diff --git a/docviewerflex/resources/grab.gif b/docviewerflex/resources/grab.gif new file mode 100644 index 0000000..cce44ec Binary files /dev/null and b/docviewerflex/resources/grab.gif differ diff --git a/docviewerflex/resources/grabbing.gif b/docviewerflex/resources/grabbing.gif new file mode 100644 index 0000000..2c0a203 Binary files /dev/null and b/docviewerflex/resources/grabbing.gif differ diff --git a/docviewerflex/resources/hand2.gif b/docviewerflex/resources/hand2.gif new file mode 100644 index 0000000..6a878a4 Binary files /dev/null and b/docviewerflex/resources/hand2.gif differ diff --git a/docviewerflex/resources/icon-arrow-left.gif b/docviewerflex/resources/icon-arrow-left.gif new file mode 100644 index 0000000..1e95056 Binary files /dev/null and b/docviewerflex/resources/icon-arrow-left.gif differ diff --git a/docviewerflex/resources/icon-arrow-right.gif b/docviewerflex/resources/icon-arrow-right.gif new file mode 100644 index 0000000..d7f28e0 Binary files /dev/null and b/docviewerflex/resources/icon-arrow-right.gif differ diff --git a/docviewerflex/resources/logosmall-trans.png b/docviewerflex/resources/logosmall-trans.png new file mode 100644 index 0000000..0b89c54 Binary files /dev/null and b/docviewerflex/resources/logosmall-trans.png differ diff --git a/docviewerflex/resources/logosmall-transc.png b/docviewerflex/resources/logosmall-transc.png new file mode 100644 index 0000000..3b64150 Binary files /dev/null and b/docviewerflex/resources/logosmall-transc.png differ diff --git a/docviewerflex/resources/logosmall.png b/docviewerflex/resources/logosmall.png new file mode 100644 index 0000000..4889a13 Binary files /dev/null and b/docviewerflex/resources/logosmall.png differ diff --git a/docviewerflex/resources/logosmallgray.png b/docviewerflex/resources/logosmallgray.png new file mode 100644 index 0000000..fdff125 Binary files /dev/null and b/docviewerflex/resources/logosmallgray.png differ diff --git a/docviewerflex/resources/pagefit.gif b/docviewerflex/resources/pagefit.gif new file mode 100644 index 0000000..69dc8e6 Binary files /dev/null and b/docviewerflex/resources/pagefit.gif differ diff --git a/docviewerflex/resources/print-icon.gif b/docviewerflex/resources/print-icon.gif new file mode 100644 index 0000000..618b6ba Binary files /dev/null and b/docviewerflex/resources/print-icon.gif differ diff --git a/docviewerflex/resources/singlepage.gif b/docviewerflex/resources/singlepage.gif new file mode 100644 index 0000000..ffe4991 Binary files /dev/null and b/docviewerflex/resources/singlepage.gif differ diff --git a/docviewerflex/resources/sliderdot.gif b/docviewerflex/resources/sliderdot.gif new file mode 100644 index 0000000..70c6042 Binary files /dev/null and b/docviewerflex/resources/sliderdot.gif differ diff --git a/docviewerflex/resources/textselect.gif b/docviewerflex/resources/textselect.gif new file mode 100644 index 0000000..27ea1c7 Binary files /dev/null and b/docviewerflex/resources/textselect.gif differ diff --git a/docviewerflex/resources/textselectcursor.gif b/docviewerflex/resources/textselectcursor.gif new file mode 100644 index 0000000..e8b29e5 Binary files /dev/null and b/docviewerflex/resources/textselectcursor.gif differ diff --git a/docviewerflex/resources/thumbs.gif b/docviewerflex/resources/thumbs.gif new file mode 100644 index 0000000..f549bf9 Binary files /dev/null and b/docviewerflex/resources/thumbs.gif differ diff --git a/docviewerflex/resources/twopage.gif b/docviewerflex/resources/twopage.gif new file mode 100644 index 0000000..b1080e4 Binary files /dev/null and b/docviewerflex/resources/twopage.gif differ diff --git a/docviewerflex/src/DocViewerFlex.mxml b/docviewerflex/src/DocViewerFlex.mxml index 5b65a57..6479a1f 100644 --- a/docviewerflex/src/DocViewerFlex.mxml +++ b/docviewerflex/src/DocViewerFlex.mxml @@ -4,15 +4,19 @@ @version: 1 @date: 2011/08/25 下午1:00 --> - - + - + - \ No newline at end of file + \ No newline at end of file diff --git a/docviewerflex/src/caurina/transitions/AuxFunctions.as b/docviewerflex/src/caurina/transitions/AuxFunctions.as index 75dffc6..4891e00 100644 --- a/docviewerflex/src/caurina/transitions/AuxFunctions.as +++ b/docviewerflex/src/caurina/transitions/AuxFunctions.as @@ -1,77 +1,77 @@ -package caurina.transitions { - - /** - * Generic, auxiliary functions - * - * @author Zeh Fernando - * @version 1.0.0 - * @private - */ - - public class AuxFunctions { - - /** - * Gets the R (xx0000) bits from a number - * - * @param p_num Number Color number (ie, 0xffff00) - * @return Number The R value - */ - public static function numberToR(p_num:Number):Number { - // The initial & is meant to crop numbers bigger than 0xffffff - return (p_num & 0xff0000) >> 16; - } - - /** - * Gets the G (00xx00) bits from a number - * - * @param p_num Number Color number (ie, 0xffff00) - * @return Number The G value - */ - public static function numberToG(p_num:Number):Number { - return (p_num & 0xff00) >> 8; - } - - /** - * Gets the B (0000xx) bits from a number - * - * @param p_num Number Color number (ie, 0xffff00) - * @return Number The B value - */ - public static function numberToB(p_num:Number):Number { - return (p_num & 0xff); - } - - /** - * Returns the number of properties an object has - * - * @param p_object Object Target object with a number of properties - * @return Number Number of total properties the object has - */ - public static function getObjectLength(p_object:Object):uint { - var totalProperties:uint = 0; - for (var pName:String in p_object) totalProperties ++; - return totalProperties; - } - - /* Takes a variable number of objects as parameters and "adds" their properties, from left to right. If a latter object defines a property as null, it will be removed from the final object - * @param args Object(s) A variable number of objects - * @return Object An object with the sum of all paremeters added as properties. - */ - public static function concatObjects(...args) : Object{ - var finalObject : Object = {}; - var currentObject : Object; - for (var i : int = 0; i < args.length; i++){ - currentObject = args[i]; - for (var prop : String in currentObject){ - if (currentObject[prop] == null){ - // delete in case is null - delete finalObject[prop]; - }else{ - finalObject[prop] = currentObject[prop]; - } - } - } - return finalObject; - } - } -} +package caurina.transitions { + + /** + * Generic, auxiliary functions + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class AuxFunctions { + + /** + * Gets the R (xx0000) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The R value + */ + public static function numberToR(p_num:Number):Number { + // The initial & is meant to crop numbers bigger than 0xffffff + return (p_num & 0xff0000) >> 16; + } + + /** + * Gets the G (00xx00) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The G value + */ + public static function numberToG(p_num:Number):Number { + return (p_num & 0xff00) >> 8; + } + + /** + * Gets the B (0000xx) bits from a number + * + * @param p_num Number Color number (ie, 0xffff00) + * @return Number The B value + */ + public static function numberToB(p_num:Number):Number { + return (p_num & 0xff); + } + + /** + * Returns the number of properties an object has + * + * @param p_object Object Target object with a number of properties + * @return Number Number of total properties the object has + */ + public static function getObjectLength(p_object:Object):uint { + var totalProperties:uint = 0; + for (var pName:String in p_object) totalProperties ++; + return totalProperties; + } + + /* Takes a variable number of objects as parameters and "adds" their properties, from left to right. If a latter object defines a property as null, it will be removed from the final object + * @param args Object(s) A variable number of objects + * @return Object An object with the sum of all paremeters added as properties. + */ + public static function concatObjects(...args) : Object{ + var finalObject : Object = {}; + var currentObject : Object; + for (var i : int = 0; i < args.length; i++){ + currentObject = args[i]; + for (var prop : String in currentObject){ + if (currentObject[prop] == null){ + // delete in case is null + delete finalObject[prop]; + }else{ + finalObject[prop] = currentObject[prop]; + } + } + } + return finalObject; + } + } +} diff --git a/docviewerflex/src/caurina/transitions/Equations.as b/docviewerflex/src/caurina/transitions/Equations.as index d9893c4..6d77eec 100644 --- a/docviewerflex/src/caurina/transitions/Equations.as +++ b/docviewerflex/src/caurina/transitions/Equations.as @@ -1,714 +1,687 @@ -/** - * Equations - * Main equations for the Tweener class - * - * @author Zeh Fernando, Nate Chatellier - * @version 1.0.2 - */ - -/* -Disclaimer for Robert Penner's Easing Equations license: - -TERMS OF USE - EASING EQUATIONS - -Open source under the BSD License. - -Copyright © 2001 Robert Penner -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -package caurina.transitions { - - public class Equations { - - /** - * There's no constructor. - * @private - */ - public function Equations () { - trace ("Equations is a static class and should not be instantiated.") - } - - /** - * Registers all the equations to the Tweener class, so they can be found by the direct string parameters. - * This method doesn't actually have to be used - equations can always be referenced by their full function - * names. But "registering" them make them available as their shorthand string names. - */ - public static function init():void { - Tweener.registerTransition("easenone", easeNone); - Tweener.registerTransition("linear", easeNone); // mx.transitions.easing.None.easeNone - - Tweener.registerTransition("easeinquad", easeInQuad); // mx.transitions.easing.Regular.easeIn - Tweener.registerTransition("easeoutquad", easeOutQuad); // mx.transitions.easing.Regular.easeOut - Tweener.registerTransition("easeinoutquad", easeInOutQuad); // mx.transitions.easing.Regular.easeInOut - Tweener.registerTransition("easeoutinquad", easeOutInQuad); - - Tweener.registerTransition("easeincubic", easeInCubic); - Tweener.registerTransition("easeoutcubic", easeOutCubic); - Tweener.registerTransition("easeinoutcubic", easeInOutCubic); - Tweener.registerTransition("easeoutincubic", easeOutInCubic); - - Tweener.registerTransition("easeinquart", easeInQuart); - Tweener.registerTransition("easeoutquart", easeOutQuart); - Tweener.registerTransition("easeinoutquart", easeInOutQuart); - Tweener.registerTransition("easeoutinquart", easeOutInQuart); - - Tweener.registerTransition("easeinquint", easeInQuint); - Tweener.registerTransition("easeoutquint", easeOutQuint); - Tweener.registerTransition("easeinoutquint", easeInOutQuint); - Tweener.registerTransition("easeoutinquint", easeOutInQuint); - - Tweener.registerTransition("easeinsine", easeInSine); - Tweener.registerTransition("easeoutsine", easeOutSine); - Tweener.registerTransition("easeinoutsine", easeInOutSine); - Tweener.registerTransition("easeoutinsine", easeOutInSine); - - Tweener.registerTransition("easeincirc", easeInCirc); - Tweener.registerTransition("easeoutcirc", easeOutCirc); - Tweener.registerTransition("easeinoutcirc", easeInOutCirc); - Tweener.registerTransition("easeoutincirc", easeOutInCirc); - - Tweener.registerTransition("easeinexpo", easeInExpo); // mx.transitions.easing.Strong.easeIn - Tweener.registerTransition("easeoutexpo", easeOutExpo); // mx.transitions.easing.Strong.easeOut - Tweener.registerTransition("easeinoutexpo", easeInOutExpo); // mx.transitions.easing.Strong.easeInOut - Tweener.registerTransition("easeoutinexpo", easeOutInExpo); - - Tweener.registerTransition("easeinelastic", easeInElastic); // mx.transitions.easing.Elastic.easeIn - Tweener.registerTransition("easeoutelastic", easeOutElastic); // mx.transitions.easing.Elastic.easeOut - Tweener.registerTransition("easeinoutelastic", easeInOutElastic); // mx.transitions.easing.Elastic.easeInOut - Tweener.registerTransition("easeoutinelastic", easeOutInElastic); - - Tweener.registerTransition("easeinback", easeInBack); // mx.transitions.easing.Back.easeIn - Tweener.registerTransition("easeoutback", easeOutBack); // mx.transitions.easing.Back.easeOut - Tweener.registerTransition("easeinoutback", easeInOutBack); // mx.transitions.easing.Back.easeInOut - Tweener.registerTransition("easeoutinback", easeOutInBack); - - Tweener.registerTransition("easeinbounce", easeInBounce); // mx.transitions.easing.Bounce.easeIn - Tweener.registerTransition("easeoutbounce", easeOutBounce); // mx.transitions.easing.Bounce.easeOut - Tweener.registerTransition("easeinoutbounce", easeInOutBounce); // mx.transitions.easing.Bounce.easeInOut - Tweener.registerTransition("easeoutinbounce", easeOutInBounce); - } - - // ================================================================================================================================== - // TWEENING EQUATIONS functions ----------------------------------------------------------------------------------------------------- - // (the original equations are Robert Penner's work as mentioned on the disclaimer) - - /** - * Easing equation function for a simple linear tweening, with no easing. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeNone (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*t/d + b; - } - - /** - * Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*(t/=d)*t + b; - } - - /** - * Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return -c *(t/=d)*(t-2) + b; - } - - /** - * Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d/2) < 1) return c/2*t*t + b; - return -c/2 * ((--t)*(t-2) - 1) + b; - } - - /** - * Easing equation function for a quadratic (t^2) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutQuad (t*2, b, c/2, d, p_params); - return easeInQuad((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a cubic (t^3) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*(t/=d)*t*t + b; - } - - /** - * Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*((t=t/d-1)*t*t + 1) + b; - } - - /** - * Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d/2) < 1) return c/2*t*t*t + b; - return c/2*((t-=2)*t*t + 2) + b; - } - - /** - * Easing equation function for a cubic (t^3) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutCubic (t*2, b, c/2, d, p_params); - return easeInCubic((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*(t/=d)*t*t*t + b; - } - - /** - * Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return -c * ((t=t/d-1)*t*t*t - 1) + b; - } - - /** - * Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d/2) < 1) return c/2*t*t*t*t + b; - return -c/2 * ((t-=2)*t*t*t - 2) + b; - } - - /** - * Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutQuart (t*2, b, c/2, d, p_params); - return easeInQuart((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*(t/=d)*t*t*t*t + b; - } - - /** - * Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c*((t=t/d-1)*t*t*t*t + 1) + b; - } - - /** - * Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; - return c/2*((t-=2)*t*t*t*t + 2) + b; - } - - /** - * Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutQuint (t*2, b, c/2, d, p_params); - return easeInQuint((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return -c * Math.cos(t/d * (Math.PI/2)) + c + b; - } - - /** - * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c * Math.sin(t/d * (Math.PI/2)) + b; - } - - /** - * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; - } - - /** - * Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutSine (t*2, b, c/2, d, p_params); - return easeInSine((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b - c * 0.001; - } - - /** - * Easing equation function for an exponential (2^t) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return (t==d) ? b+c : c * 1.001 * (-Math.pow(2, -10 * t/d) + 1) + b; - } - - /** - * Easing equation function for an exponential (2^t) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t==0) return b; - if (t==d) return b+c; - if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b - c * 0.0005; - return c/2 * 1.0005 * (-Math.pow(2, -10 * --t) + 2) + b; - } - - /** - * Easing equation function for an exponential (2^t) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutExpo (t*2, b, c/2, d, p_params); - return easeInExpo((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a circular (sqrt(1-t^2)) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; - } - - /** - * Easing equation function for a circular (sqrt(1-t^2)) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c * Math.sqrt(1 - (t=t/d-1)*t) + b; - } - - /** - * Easing equation function for a circular (sqrt(1-t^2)) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; - return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; - } - - /** - * Easing equation function for a circular (sqrt(1-t^2)) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutCirc (t*2, b, c/2, d, p_params); - return easeInCirc((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for an elastic (exponentially decaying sine wave) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ - public static function easeInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t==0) return b; - if ((t/=d)==1) return b+c; - var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; - var s:Number; - var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; - if (!Boolean(a) || a < Math.abs(c)) { - a = c; - s = p/4; - } else { - s = p/(2*Math.PI) * Math.asin (c/a); - } - return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - } - - /** - * Easing equation function for an elastic (exponentially decaying sine wave) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ - public static function easeOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t==0) return b; - if ((t/=d)==1) return b+c; - var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; - var s:Number; - var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; - if (!Boolean(a) || a < Math.abs(c)) { - a = c; - s = p/4; - } else { - s = p/(2*Math.PI) * Math.asin (c/a); - } - return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b); - } - - /** - * Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ - public static function easeInOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t==0) return b; - if ((t/=d/2)==2) return b+c; - var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*(.3*1.5) : p_params.period; - var s:Number; - var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; - if (!Boolean(a) || a < Math.abs(c)) { - a = c; - s = p/4; - } else { - s = p/(2*Math.PI) * Math.asin (c/a); - } - if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; - return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; - } - - /** - * Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ - public static function easeOutInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutElastic (t*2, b, c/2, d, p_params); - return easeInElastic((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ - public static function easeInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; - return c*(t/=d)*t*((s+1)*t - s) + b; - } - - /** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ - public static function easeOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; - return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; - } - - /** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ - public static function easeInOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; - if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; - return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; - } - - /** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ - public static function easeOutInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutBack (t*2, b, c/2, d, p_params); - return easeInBack((t*2)-d, b+c/2, c/2, d, p_params); - } - - /** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - return c - easeOutBounce (d-t, 0, c, d) + b; - } - - /** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if ((t/=d) < (1/2.75)) { - return c*(7.5625*t*t) + b; - } else if (t < (2/2.75)) { - return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; - } else if (t < (2.5/2.75)) { - return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; - } else { - return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; - } - } - - /** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeInOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeInBounce (t*2, 0, c, d) * .5 + b; - else return easeOutBounce (t*2-d, 0, c, d) * .5 + c*.5 + b; - } - - /** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param b Starting value. - * @param c Change needed in value. - * @param d Expected easing duration (in frames or seconds). - * @return The correct value. - */ - public static function easeOutInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { - if (t < d/2) return easeOutBounce (t*2, b, c/2, d, p_params); - return easeInBounce((t*2)-d, b+c/2, c/2, d, p_params); - } - } -} +package caurina.transitions { + + public class Equations { + + /** + * There's no constructor. + * @private + */ + public function Equations () { + trace ("Equations is a static class and should not be instantiated.") + } + + /** + * Registers all the equations to the Tweener class, so they can be found by the direct string parameters. + * This method doesn't actually have to be used - equations can always be referenced by their full function + * names. But "registering" them make them available as their shorthand string names. + */ + public static function init():void { + Tweener.registerTransition("easenone", easeNone); + Tweener.registerTransition("linear", easeNone); // mx.transitions.easing.None.easeNone + + Tweener.registerTransition("easeinquad", easeInQuad); // mx.transitions.easing.Regular.easeIn + Tweener.registerTransition("easeoutquad", easeOutQuad); // mx.transitions.easing.Regular.easeOut + Tweener.registerTransition("easeinoutquad", easeInOutQuad); // mx.transitions.easing.Regular.easeInOut + Tweener.registerTransition("easeoutinquad", easeOutInQuad); + + Tweener.registerTransition("easeincubic", easeInCubic); + Tweener.registerTransition("easeoutcubic", easeOutCubic); + Tweener.registerTransition("easeinoutcubic", easeInOutCubic); + Tweener.registerTransition("easeoutincubic", easeOutInCubic); + + Tweener.registerTransition("easeinquart", easeInQuart); + Tweener.registerTransition("easeoutquart", easeOutQuart); + Tweener.registerTransition("easeinoutquart", easeInOutQuart); + Tweener.registerTransition("easeoutinquart", easeOutInQuart); + + Tweener.registerTransition("easeinquint", easeInQuint); + Tweener.registerTransition("easeoutquint", easeOutQuint); + Tweener.registerTransition("easeinoutquint", easeInOutQuint); + Tweener.registerTransition("easeoutinquint", easeOutInQuint); + + Tweener.registerTransition("easeinsine", easeInSine); + Tweener.registerTransition("easeoutsine", easeOutSine); + Tweener.registerTransition("easeinoutsine", easeInOutSine); + Tweener.registerTransition("easeoutinsine", easeOutInSine); + + Tweener.registerTransition("easeincirc", easeInCirc); + Tweener.registerTransition("easeoutcirc", easeOutCirc); + Tweener.registerTransition("easeinoutcirc", easeInOutCirc); + Tweener.registerTransition("easeoutincirc", easeOutInCirc); + + Tweener.registerTransition("easeinexpo", easeInExpo); // mx.transitions.easing.Strong.easeIn + Tweener.registerTransition("easeoutexpo", easeOutExpo); // mx.transitions.easing.Strong.easeOut + Tweener.registerTransition("easeinoutexpo", easeInOutExpo); // mx.transitions.easing.Strong.easeInOut + Tweener.registerTransition("easeoutinexpo", easeOutInExpo); + + Tweener.registerTransition("easeinelastic", easeInElastic); // mx.transitions.easing.Elastic.easeIn + Tweener.registerTransition("easeoutelastic", easeOutElastic); // mx.transitions.easing.Elastic.easeOut + Tweener.registerTransition("easeinoutelastic", easeInOutElastic); // mx.transitions.easing.Elastic.easeInOut + Tweener.registerTransition("easeoutinelastic", easeOutInElastic); + + Tweener.registerTransition("easeinback", easeInBack); // mx.transitions.easing.Back.easeIn + Tweener.registerTransition("easeoutback", easeOutBack); // mx.transitions.easing.Back.easeOut + Tweener.registerTransition("easeinoutback", easeInOutBack); // mx.transitions.easing.Back.easeInOut + Tweener.registerTransition("easeoutinback", easeOutInBack); + + Tweener.registerTransition("easeinbounce", easeInBounce); // mx.transitions.easing.Bounce.easeIn + Tweener.registerTransition("easeoutbounce", easeOutBounce); // mx.transitions.easing.Bounce.easeOut + Tweener.registerTransition("easeinoutbounce", easeInOutBounce); // mx.transitions.easing.Bounce.easeInOut + Tweener.registerTransition("easeoutinbounce", easeOutInBounce); + } + + // ================================================================================================================================== + // TWEENING EQUATIONS functions ----------------------------------------------------------------------------------------------------- + // (the original equations are Robert Penner's work as mentioned on the disclaimer) + + /** + * Easing equation function for a simple linear tweening, with no easing. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeNone (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*t/d + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c *(t/=d)*(t-2) + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + } + + /** + * Easing equation function for a quadratic (t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuad (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuad (t*2, b, c/2, d, p_params); + return easeInQuad((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a cubic (t^3) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t + b; + } + + /** + * Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*((t=t/d-1)*t*t + 1) + b; + } + + /** + * Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t + b; + return c/2*((t-=2)*t*t + 2) + b; + } + + /** + * Easing equation function for a cubic (t^3) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInCubic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutCubic (t*2, b, c/2, d, p_params); + return easeInCubic((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t*t + b; + } + + /** + * Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + } + + /** + * Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + } + + /** + * Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuart (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuart (t*2, b, c/2, d, p_params); + return easeInQuart((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*(t/=d)*t*t*t*t + b; + } + + /** + * Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c*((t=t/d-1)*t*t*t*t + 1) + b; + } + + /** + * Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; + return c/2*((t-=2)*t*t*t*t + 2) + b; + } + + /** + * Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInQuint (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutQuint (t*2, b, c/2, d, p_params); + return easeInQuint((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * Math.cos(t/d * (Math.PI/2)) + c + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c * Math.sin(t/d * (Math.PI/2)) + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; + } + + /** + * Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInSine (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutSine (t*2, b, c/2, d, p_params); + return easeInSine((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b - c * 0.001; + } + + /** + * Easing equation function for an exponential (2^t) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return (t==d) ? b+c : c * 1.001 * (-Math.pow(2, -10 * t/d) + 1) + b; + } + + /** + * Easing equation function for an exponential (2^t) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if (t==d) return b+c; + if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b - c * 0.0005; + return c/2 * 1.0005 * (-Math.pow(2, -10 * --t) + 2) + b; + } + + /** + * Easing equation function for an exponential (2^t) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInExpo (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutExpo (t*2, b, c/2, d, p_params); + return easeInExpo((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c * Math.sqrt(1 - (t=t/d-1)*t) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; + return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; + } + + /** + * Easing equation function for a circular (sqrt(1-t^2)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInCirc (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutCirc (t*2, b, c/2, d, p_params); + return easeInCirc((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d)==1) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d)==1) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*.3 : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b); + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeInOutElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t==0) return b; + if ((t/=d/2)==2) return b+c; + var p:Number = !Boolean(p_params) || isNaN(p_params.period) ? d*(.3*1.5) : p_params.period; + var s:Number; + var a:Number = !Boolean(p_params) || isNaN(p_params.amplitude) ? 0 : p_params.amplitude; + if (!Boolean(a) || a < Math.abs(c)) { + a = c; + s = p/4; + } else { + s = p/(2*Math.PI) * Math.asin (c/a); + } + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + } + + /** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ + public static function easeOutInElastic (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutElastic (t*2, b, c/2, d, p_params); + return easeInElastic((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + return c*(t/=d)*t*((s+1)*t - s) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeInOutBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + var s:Number = !Boolean(p_params) || isNaN(p_params.overshoot) ? 1.70158 : p_params.overshoot; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + } + + /** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ + public static function easeOutInBack (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutBack (t*2, b, c/2, d, p_params); + return easeInBack((t*2)-d, b+c/2, c/2, d, p_params); + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + return c - easeOutBounce (d-t, 0, c, d) + b; + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeInOutBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeInBounce (t*2, 0, c, d) * .5 + b; + else return easeOutBounce (t*2-d, 0, c, d) * .5 + c*.5 + b; + } + + /** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param b Starting value. + * @param c Change needed in value. + * @param d Expected easing duration (in frames or seconds). + * @return The correct value. + */ + public static function easeOutInBounce (t:Number, b:Number, c:Number, d:Number, p_params:Object = null):Number { + if (t < d/2) return easeOutBounce (t*2, b, c/2, d, p_params); + return easeInBounce((t*2)-d, b+c/2, c/2, d, p_params); + } + } +} diff --git a/docviewerflex/src/caurina/transitions/PropertyInfoObj.as b/docviewerflex/src/caurina/transitions/PropertyInfoObj.as index 132aaa5..200272b 100644 --- a/docviewerflex/src/caurina/transitions/PropertyInfoObj.as +++ b/docviewerflex/src/caurina/transitions/PropertyInfoObj.as @@ -1,90 +1,90 @@ -package caurina.transitions { - - /** - * PropertyInfoObj - * An object containing the updating info for a given property (its starting value, and its final value) - * - * @author Zeh Fernando - * @version 1.0.0 - * @private - */ - - public class PropertyInfoObj { - - public var valueStart :Number; // Starting value of the tweening (null if not started yet) - public var valueComplete :Number; // Final desired value - public var originalValueComplete :Object; // Final desired value as declared initially - public var arrayIndex :Number; // Index (if this is an array item) - public var extra :Object; // Additional parameters, used by some special properties - public var isSpecialProperty :Boolean; // Whether or not this is a special property instead of a direct one - public var hasModifier :Boolean; // Whether or not it has a modifier function - public var modifierFunction :Function; // Modifier function, if any - public var modifierParameters :Array; // Additional array of modifier parameters - - // ================================================================================================================================== - // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- - - /** - * Initializes the basic PropertyInfoObj. - * - * @param p_valueStart Number Starting value of the tweening (null if not started yet) - * @param p_valueComplete Number Final (desired) property value - */ - function PropertyInfoObj(p_valueStart:Number, p_valueComplete:Number, p_originalValueComplete:Object, p_arrayIndex:Number, p_extra:Object, p_isSpecialProperty:Boolean, p_modifierFunction:Function, p_modifierParameters:Array) { - valueStart = p_valueStart; - valueComplete = p_valueComplete; - originalValueComplete = p_originalValueComplete; - arrayIndex = p_arrayIndex; - extra = p_extra; - isSpecialProperty = p_isSpecialProperty; - hasModifier = Boolean(p_modifierFunction); - modifierFunction = p_modifierFunction; - modifierParameters = p_modifierParameters; - } - - - // ================================================================================================================================== - // OTHER functions ------------------------------------------------------------------------------------------------------------------ - - /** - * Clones this property info and returns the new PropertyInfoObj - * - * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted - * @return TweenListObj A copy of this object - */ - public function clone():PropertyInfoObj { - var nProperty:PropertyInfoObj = new PropertyInfoObj(valueStart, valueComplete, originalValueComplete, arrayIndex, extra, isSpecialProperty, modifierFunction, modifierParameters); - return nProperty; - } - - /** - * Returns this object described as a String. - * - * @return String The description of this object. - */ - public function toString():String { - var returnStr:String = "\n[PropertyInfoObj "; - returnStr += "valueStart:" + String(valueStart); - returnStr += ", "; - returnStr += "valueComplete:" + String(valueComplete); - returnStr += ", "; - returnStr += "originalValueComplete:" + String(originalValueComplete); - returnStr += ", "; - returnStr += "arrayIndex:" + String(arrayIndex); - returnStr += ", "; - returnStr += "extra:" + String(extra); - returnStr += ", "; - returnStr += "isSpecialProperty:" + String(isSpecialProperty); - returnStr += ", "; - returnStr += "hasModifier:" + String(hasModifier); - returnStr += ", "; - returnStr += "modifierFunction:" + String(modifierFunction); - returnStr += ", "; - returnStr += "modifierParameters:" + String(modifierParameters); - returnStr += "]\n"; - return returnStr; - } - - } - -} +package caurina.transitions { + + /** + * PropertyInfoObj + * An object containing the updating info for a given property (its starting value, and its final value) + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class PropertyInfoObj { + + public var valueStart :Number; // Starting value of the tweening (null if not started yet) + public var valueComplete :Number; // Final desired value + public var originalValueComplete :Object; // Final desired value as declared initially + public var arrayIndex :Number; // Index (if this is an array item) + public var extra :Object; // Additional parameters, used by some special properties + public var isSpecialProperty :Boolean; // Whether or not this is a special property instead of a direct one + public var hasModifier :Boolean; // Whether or not it has a modifier function + public var modifierFunction :Function; // Modifier function, if any + public var modifierParameters :Array; // Additional array of modifier parameters + + // ================================================================================================================================== + // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- + + /** + * Initializes the basic PropertyInfoObj. + * + * @param p_valueStart Number Starting value of the tweening (null if not started yet) + * @param p_valueComplete Number Final (desired) property value + */ + function PropertyInfoObj(p_valueStart:Number, p_valueComplete:Number, p_originalValueComplete:Object, p_arrayIndex:Number, p_extra:Object, p_isSpecialProperty:Boolean, p_modifierFunction:Function, p_modifierParameters:Array) { + valueStart = p_valueStart; + valueComplete = p_valueComplete; + originalValueComplete = p_originalValueComplete; + arrayIndex = p_arrayIndex; + extra = p_extra; + isSpecialProperty = p_isSpecialProperty; + hasModifier = Boolean(p_modifierFunction); + modifierFunction = p_modifierFunction; + modifierParameters = p_modifierParameters; + } + + + // ================================================================================================================================== + // OTHER functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Clones this property info and returns the new PropertyInfoObj + * + * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted + * @return TweenListObj A copy of this object + */ + public function clone():PropertyInfoObj { + var nProperty:PropertyInfoObj = new PropertyInfoObj(valueStart, valueComplete, originalValueComplete, arrayIndex, extra, isSpecialProperty, modifierFunction, modifierParameters); + return nProperty; + } + + /** + * Returns this object described as a String. + * + * @return String The description of this object. + */ + public function toString():String { + var returnStr:String = "\n[PropertyInfoObj "; + returnStr += "valueStart:" + String(valueStart); + returnStr += ", "; + returnStr += "valueComplete:" + String(valueComplete); + returnStr += ", "; + returnStr += "originalValueComplete:" + String(originalValueComplete); + returnStr += ", "; + returnStr += "arrayIndex:" + String(arrayIndex); + returnStr += ", "; + returnStr += "extra:" + String(extra); + returnStr += ", "; + returnStr += "isSpecialProperty:" + String(isSpecialProperty); + returnStr += ", "; + returnStr += "hasModifier:" + String(hasModifier); + returnStr += ", "; + returnStr += "modifierFunction:" + String(modifierFunction); + returnStr += ", "; + returnStr += "modifierParameters:" + String(modifierParameters); + returnStr += "]\n"; + return returnStr; + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/SpecialProperty.as b/docviewerflex/src/caurina/transitions/SpecialProperty.as index a261597..87cb989 100644 --- a/docviewerflex/src/caurina/transitions/SpecialProperty.as +++ b/docviewerflex/src/caurina/transitions/SpecialProperty.as @@ -1,49 +1,49 @@ -package caurina.transitions { - - /** - * SpecialProperty - * A kind of a getter/setter for special properties - * - * @author Zeh Fernando - * @version 1.0.0 - * @private - */ - - public class SpecialProperty { - - public var getValue:Function; // (p_obj:Object, p_parameters:Array, p_extra:Object): Number - public var setValue:Function; // (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object): Void - public var parameters:Array; - public var preProcess:Function; // (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number - - /** - * Builds a new special property object. - * - * @param p_getFunction Function Reference to the function used to get the special property value - * @param p_setFunction Function Reference to the function used to set the special property value - */ - public function SpecialProperty (p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null) { - getValue = p_getFunction; - setValue = p_setFunction; - parameters = p_parameters; - preProcess = p_preProcessFunction; - } - - /** - * Converts the instance to a string that can be used when trace()ing the object - */ - public function toString():String { - var value:String = ""; - value += "[SpecialProperty "; - value += "getValue:"+String(getValue); - value += ", "; - value += "setValue:"+String(setValue); - value += ", "; - value += "parameters:"+String(parameters); - value += ", "; - value += "preProcess:"+String(preProcess); - value += "]"; - return value; - } - } -} +package caurina.transitions { + + /** + * SpecialProperty + * A kind of a getter/setter for special properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialProperty { + + public var getValue:Function; // (p_obj:Object, p_parameters:Array, p_extra:Object): Number + public var setValue:Function; // (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object): Void + public var parameters:Array; + public var preProcess:Function; // (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number + + /** + * Builds a new special property object. + * + * @param p_getFunction Function Reference to the function used to get the special property value + * @param p_setFunction Function Reference to the function used to set the special property value + */ + public function SpecialProperty (p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null) { + getValue = p_getFunction; + setValue = p_setFunction; + parameters = p_parameters; + preProcess = p_preProcessFunction; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialProperty "; + value += "getValue:"+String(getValue); + value += ", "; + value += "setValue:"+String(setValue); + value += ", "; + value += "parameters:"+String(parameters); + value += ", "; + value += "preProcess:"+String(preProcess); + value += "]"; + return value; + } + } +} diff --git a/docviewerflex/src/caurina/transitions/SpecialPropertyModifier.as b/docviewerflex/src/caurina/transitions/SpecialPropertyModifier.as index 049af18..2c9e99f 100644 --- a/docviewerflex/src/caurina/transitions/SpecialPropertyModifier.as +++ b/docviewerflex/src/caurina/transitions/SpecialPropertyModifier.as @@ -1,42 +1,42 @@ -package caurina.transitions { - - /** - * SpecialPropertyModifier - * A special property which actually acts on other properties - * - * @author Zeh Fernando - * @version 1.0.0 - * @private - */ - - public class SpecialPropertyModifier { - - public var modifyValues:Function; - public var getValue:Function; - - /** - * Builds a new special property modifier object. - * - * @param p_modifyFunction Function Function that returns the modifider parameters. - */ - public function SpecialPropertyModifier (p_modifyFunction:Function, p_getFunction:Function) { - modifyValues = p_modifyFunction; - getValue = p_getFunction; - } - - /** - * Converts the instance to a string that can be used when trace()ing the object - */ - public function toString():String { - var value:String = ""; - value += "[SpecialPropertyModifier "; - value += "modifyValues:"+String(modifyValues); - value += ", "; - value += "getValue:"+String(getValue); - value += "]"; - return value; - } - - } - -} +package caurina.transitions { + + /** + * SpecialPropertyModifier + * A special property which actually acts on other properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialPropertyModifier { + + public var modifyValues:Function; + public var getValue:Function; + + /** + * Builds a new special property modifier object. + * + * @param p_modifyFunction Function Function that returns the modifider parameters. + */ + public function SpecialPropertyModifier (p_modifyFunction:Function, p_getFunction:Function) { + modifyValues = p_modifyFunction; + getValue = p_getFunction; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialPropertyModifier "; + value += "modifyValues:"+String(modifyValues); + value += ", "; + value += "getValue:"+String(getValue); + value += "]"; + return value; + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/SpecialPropertySplitter.as b/docviewerflex/src/caurina/transitions/SpecialPropertySplitter.as index eeef903..ff49c31 100644 --- a/docviewerflex/src/caurina/transitions/SpecialPropertySplitter.as +++ b/docviewerflex/src/caurina/transitions/SpecialPropertySplitter.as @@ -1,42 +1,42 @@ -package caurina.transitions { - - /** - * SpecialPropertySplitter - * A proxy setter for special properties - * - * @author Zeh Fernando - * @version 1.0.0 - * @private - */ - - public class SpecialPropertySplitter { - - public var parameters:Array; - public var splitValues:Function; - - /** - * Builds a new group special property object. - * - * @param p_splitFunction Function Reference to the function used to split a value - */ - public function SpecialPropertySplitter (p_splitFunction:Function, p_parameters:Array) { - splitValues = p_splitFunction; - parameters = p_parameters; - } - - /** - * Converts the instance to a string that can be used when trace()ing the object - */ - public function toString():String { - var value:String = ""; - value += "[SpecialPropertySplitter "; - value += "splitValues:"+String(splitValues); // .toString(); - value += ", "; - value += "parameters:"+String(parameters); - value += "]"; - return value; - } - - } - -} +package caurina.transitions { + + /** + * SpecialPropertySplitter + * A proxy setter for special properties + * + * @author Zeh Fernando + * @version 1.0.0 + * @private + */ + + public class SpecialPropertySplitter { + + public var parameters:Array; + public var splitValues:Function; + + /** + * Builds a new group special property object. + * + * @param p_splitFunction Function Reference to the function used to split a value + */ + public function SpecialPropertySplitter (p_splitFunction:Function, p_parameters:Array) { + splitValues = p_splitFunction; + parameters = p_parameters; + } + + /** + * Converts the instance to a string that can be used when trace()ing the object + */ + public function toString():String { + var value:String = ""; + value += "[SpecialPropertySplitter "; + value += "splitValues:"+String(splitValues); // .toString(); + value += ", "; + value += "parameters:"+String(parameters); + value += "]"; + return value; + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/TweenListObj.as b/docviewerflex/src/caurina/transitions/TweenListObj.as index 77fa1fe..1e0d63f 100644 --- a/docviewerflex/src/caurina/transitions/TweenListObj.as +++ b/docviewerflex/src/caurina/transitions/TweenListObj.as @@ -1,236 +1,236 @@ -package caurina.transitions { - import caurina.transitions.AuxFunctions; - /** - * The tween list object. Stores all of the properties and information that pertain to individual tweens. - * - * @author Nate Chatellier, Zeh Fernando - * @version 1.0.4 - * @private - */ - - public class TweenListObj { - - public var scope :Object; // Object affected by this tweening - public var properties :Object; // List of properties that are tweened (PropertyInfoObj instances) - // .valueStart :Number // Initial value of the property - // .valueComplete :Number // The value the property should have when completed - public var timeStart :Number; // Time when this tweening should start - public var timeComplete :Number; // Time when this tweening should end - public var useFrames :Boolean; // Whether or not to use frames instead of time - public var transition :Function; // Equation to control the transition animation - public var transitionParams :Object; // Additional parameters for the transition - public var onStart :Function; // Function to be executed on the object when the tween starts (once) - public var onUpdate :Function; // Function to be executed on the object when the tween updates (several times) - public var onComplete :Function; // Function to be executed on the object when the tween completes (once) - public var onOverwrite :Function; // Function to be executed on the object when the tween is overwritten - public var onError :Function; // Function to be executed if an error is thrown when tweener exectues a callback (onComplete, onUpdate etc) - public var onStartParams :Array; // Array of parameters to be passed for the event - public var onUpdateParams :Array; // Array of parameters to be passed for the event - public var onCompleteParams :Array; // Array of parameters to be passed for the event - public var onOverwriteParams :Array; // Array of parameters to be passed for the event - public var onStartScope :Object; // Scope in which the event function is ran - public var onUpdateScope :Object; // Scope in which the event function is ran - public var onCompleteScope :Object; // Scope in which the event function is ran - public var onOverwriteScope :Object; // Scope in which the event function is ran - public var onErrorScope :Object; // Scope in which the event function is ran - public var rounded :Boolean; // Use rounded values when updating - public var isPaused :Boolean; // Whether or not this tween is paused - public var timePaused :Number; // Time when this tween was paused - public var isCaller :Boolean; // Whether or not this tween is a "caller" tween - public var count :Number; // Number of times this caller should be called - public var timesCalled :Number; // How many times the caller has already been called ("caller" tweens only) - public var waitFrames :Boolean; // Whether or not this caller should wait at least one frame for each call execution ("caller" tweens only) - public var skipUpdates :Number; // How many updates should be skipped (default = 0; 1 = update-skip-update-skip...) - public var updatesSkipped :Number; // How many updates have already been skipped - public var hasStarted :Boolean; // Whether or not this tween has already started - - // ================================================================================================================================== - // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- - - /** - * Initializes the basic TweenListObj. - * - * @param p_scope Object Object affected by this tweening - * @param p_timeStart Number Time when this tweening should start - * @param p_timeComplete Number Time when this tweening should end - * @param p_useFrames Boolean Whether or not to use frames instead of time - * @param p_transition Function Equation to control the transition animation - */ - function TweenListObj(p_scope:Object, p_timeStart:Number, p_timeComplete:Number, p_useFrames:Boolean, p_transition:Function, p_transitionParams:Object) { - scope = p_scope; - timeStart = p_timeStart; - timeComplete = p_timeComplete; - useFrames = p_useFrames; - transition = p_transition; - transitionParams = p_transitionParams; - - // Other default information - properties = new Object(); - isPaused = false; - timePaused = undefined; - isCaller = false; - updatesSkipped = 0; - timesCalled = 0; - skipUpdates = 0; - hasStarted = false; - } - - - // ================================================================================================================================== - // OTHER functions ------------------------------------------------------------------------------------------------------------------ - - /** - * Clones this tweening and returns the new TweenListObj - * - * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted - * @return TweenListObj A copy of this object - */ - public function clone(omitEvents:Boolean):TweenListObj { - var nTween:TweenListObj = new TweenListObj(scope, timeStart, timeComplete, useFrames, transition, transitionParams); - nTween.properties = new Array(); - for (var pName:String in properties) { - nTween.properties[pName] = properties[pName].clone(); - } - nTween.skipUpdates = skipUpdates; - nTween.updatesSkipped = updatesSkipped; - if (!omitEvents) { - nTween.onStart = onStart; - nTween.onUpdate = onUpdate; - nTween.onComplete = onComplete; - nTween.onOverwrite = onOverwrite; - nTween.onError = onError; - nTween.onStartParams = onStartParams; - nTween.onUpdateParams = onUpdateParams; - nTween.onCompleteParams = onCompleteParams; - nTween.onOverwriteParams = onOverwriteParams; - nTween.onStartScope = onStartScope; - nTween.onUpdateScope = onUpdateScope; - nTween.onCompleteScope = onCompleteScope; - nTween.onOverwriteScope = onOverwriteScope; - nTween.onErrorScope = onErrorScope; - } - nTween.rounded = rounded; - nTween.isPaused = isPaused; - nTween.timePaused = timePaused; - nTween.isCaller = isCaller; - nTween.count = count; - nTween.timesCalled = timesCalled; - nTween.waitFrames = waitFrames; - nTween.hasStarted = hasStarted; - - return nTween; - } - - /** - * Returns this object described as a String. - * - * @return String The description of this object. - */ - public function toString():String { - var returnStr:String = "\n[TweenListObj "; - returnStr += "scope:" + String(scope); - returnStr += ", properties:"; - var isFirst:Boolean = true; - for (var i:String in properties) { - if (!isFirst) returnStr += ","; - returnStr += "[name:"+properties[i].name; - returnStr += ",valueStart:"+properties[i].valueStart; - returnStr += ",valueComplete:"+properties[i].valueComplete; - returnStr += "]"; - isFirst = false; - } - returnStr += ", timeStart:" + String(timeStart); - returnStr += ", timeComplete:" + String(timeComplete); - returnStr += ", useFrames:" + String(useFrames); - returnStr += ", transition:" + String(transition); - returnStr += ", transitionParams:" + String(transitionParams); - - if (skipUpdates) returnStr += ", skipUpdates:" + String(skipUpdates); - if (updatesSkipped) returnStr += ", updatesSkipped:" + String(updatesSkipped); - - if (Boolean(onStart)) returnStr += ", onStart:" + String(onStart); - if (Boolean(onUpdate)) returnStr += ", onUpdate:" + String(onUpdate); - if (Boolean(onComplete)) returnStr += ", onComplete:" + String(onComplete); - if (Boolean(onOverwrite)) returnStr += ", onOverwrite:" + String(onOverwrite); - if (Boolean(onError)) returnStr += ", onError:" + String(onError); - - if (onStartParams) returnStr += ", onStartParams:" + String(onStartParams); - if (onUpdateParams) returnStr += ", onUpdateParams:" + String(onUpdateParams); - if (onCompleteParams) returnStr += ", onCompleteParams:" + String(onCompleteParams); - if (onOverwriteParams) returnStr += ", onOverwriteParams:" + String(onOverwriteParams); - - if (onStartScope) returnStr += ", onStartScope:" + String(onStartScope); - if (onUpdateScope) returnStr += ", onUpdateScope:" + String(onUpdateScope); - if (onCompleteScope) returnStr += ", onCompleteScope:" + String(onCompleteScope); - if (onOverwriteScope) returnStr += ", onOverwriteScope:" + String(onOverwriteScope); - if (onErrorScope) returnStr += ", onErrorScope:" + String(onErrorScope); - - if (rounded) returnStr += ", rounded:" + String(rounded); - if (isPaused) returnStr += ", isPaused:" + String(isPaused); - if (timePaused) returnStr += ", timePaused:" + String(timePaused); - if (isCaller) returnStr += ", isCaller:" + String(isCaller); - if (count) returnStr += ", count:" + String(count); - if (timesCalled) returnStr += ", timesCalled:" + String(timesCalled); - if (waitFrames) returnStr += ", waitFrames:" + String(waitFrames); - if (hasStarted) returnStr += ", hasStarted:" + String(hasStarted); - - returnStr += "]\n"; - return returnStr; - } - - /** - * Checks if p_obj "inherits" properties from other objects, as set by the "base" property. Will create a new object, leaving others intact. - * o_bj.base can be an object or an array of objects. Properties are collected from the first to the last element of the "base" filed, with higher - * indexes overwritting smaller ones. Does not modify any of the passed objects, but makes a shallow copy of all properties. - * - * @param p_obj Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects - * @return Object A new object with all properties from the p_obj and p_obj.base. - */ - - public static function makePropertiesChain(p_obj : Object) : Object{ - // Is this object inheriting properties from another object? - var baseObject : Object = p_obj.base; - if(baseObject){ - // object inherits. Are we inheriting from an object or an array - var chainedObject : Object = {}; - var chain : Object; - if (baseObject is Array){ - // Inheritance chain is the base array - chain = []; - // make a shallow copy - for (var k : Number = 0 ; k< baseObject.length; k++) chain.push(baseObject[k]); - }else{ - // Only one object to be added to the array - chain = [baseObject]; - } - // add the final object to the array, so it's properties are added last - chain.push(p_obj); - var currChainObj : Object; - // Loops through each object adding it's property to the final object - var len : Number = chain.length; - for(var i : Number = 0; i < len ; i ++){ - if(chain[i]["base"]){ - // deal with recursion: watch the order! "parent" base must be concatenated first! - currChainObj = AuxFunctions.concatObjects( makePropertiesChain(chain[i]["base"] ), chain[i]); - }else{ - currChainObj = chain[i] ; - } - chainedObject = AuxFunctions.concatObjects(chainedObject, currChainObj ); - } - if( chainedObject["base"]){ - delete chainedObject["base"]; - } - return chainedObject; - }else{ - // No inheritance, just return the object it self - return p_obj; - } - } - - - } - - - - -} +package caurina.transitions { + import caurina.transitions.AuxFunctions; + /** + * The tween list object. Stores all of the properties and information that pertain to individual tweens. + * + * @author Nate Chatellier, Zeh Fernando + * @version 1.0.4 + * @private + */ + + public class TweenListObj { + + public var scope :Object; // Object affected by this tweening + public var properties :Object; // List of properties that are tweened (PropertyInfoObj instances) + // .valueStart :Number // Initial value of the property + // .valueComplete :Number // The value the property should have when completed + public var timeStart :Number; // Time when this tweening should start + public var timeComplete :Number; // Time when this tweening should end + public var useFrames :Boolean; // Whether or not to use frames instead of time + public var transition :Function; // Equation to control the transition animation + public var transitionParams :Object; // Additional parameters for the transition + public var onStart :Function; // Function to be executed on the object when the tween starts (once) + public var onUpdate :Function; // Function to be executed on the object when the tween updates (several times) + public var onComplete :Function; // Function to be executed on the object when the tween completes (once) + public var onOverwrite :Function; // Function to be executed on the object when the tween is overwritten + public var onError :Function; // Function to be executed if an error is thrown when tweener exectues a callback (onComplete, onUpdate etc) + public var onStartParams :Array; // Array of parameters to be passed for the event + public var onUpdateParams :Array; // Array of parameters to be passed for the event + public var onCompleteParams :Array; // Array of parameters to be passed for the event + public var onOverwriteParams :Array; // Array of parameters to be passed for the event + public var onStartScope :Object; // Scope in which the event function is ran + public var onUpdateScope :Object; // Scope in which the event function is ran + public var onCompleteScope :Object; // Scope in which the event function is ran + public var onOverwriteScope :Object; // Scope in which the event function is ran + public var onErrorScope :Object; // Scope in which the event function is ran + public var rounded :Boolean; // Use rounded values when updating + public var isPaused :Boolean; // Whether or not this tween is paused + public var timePaused :Number; // Time when this tween was paused + public var isCaller :Boolean; // Whether or not this tween is a "caller" tween + public var count :Number; // Number of times this caller should be called + public var timesCalled :Number; // How many times the caller has already been called ("caller" tweens only) + public var waitFrames :Boolean; // Whether or not this caller should wait at least one frame for each call execution ("caller" tweens only) + public var skipUpdates :Number; // How many updates should be skipped (default = 0; 1 = update-skip-update-skip...) + public var updatesSkipped :Number; // How many updates have already been skipped + public var hasStarted :Boolean; // Whether or not this tween has already started + + // ================================================================================================================================== + // CONSTRUCTOR function ------------------------------------------------------------------------------------------------------------- + + /** + * Initializes the basic TweenListObj. + * + * @param p_scope Object Object affected by this tweening + * @param p_timeStart Number Time when this tweening should start + * @param p_timeComplete Number Time when this tweening should end + * @param p_useFrames Boolean Whether or not to use frames instead of time + * @param p_transition Function Equation to control the transition animation + */ + function TweenListObj(p_scope:Object, p_timeStart:Number, p_timeComplete:Number, p_useFrames:Boolean, p_transition:Function, p_transitionParams:Object) { + scope = p_scope; + timeStart = p_timeStart; + timeComplete = p_timeComplete; + useFrames = p_useFrames; + transition = p_transition; + transitionParams = p_transitionParams; + + // Other default information + properties = new Object(); + isPaused = false; + timePaused = undefined; + isCaller = false; + updatesSkipped = 0; + timesCalled = 0; + skipUpdates = 0; + hasStarted = false; + } + + + // ================================================================================================================================== + // OTHER functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Clones this tweening and returns the new TweenListObj + * + * @param omitEvents Boolean Whether or not events such as onStart (and its parameters) should be omitted + * @return TweenListObj A copy of this object + */ + public function clone(omitEvents:Boolean):TweenListObj { + var nTween:TweenListObj = new TweenListObj(scope, timeStart, timeComplete, useFrames, transition, transitionParams); + nTween.properties = new Array(); + for (var pName:String in properties) { + nTween.properties[pName] = properties[pName].clone(); + } + nTween.skipUpdates = skipUpdates; + nTween.updatesSkipped = updatesSkipped; + if (!omitEvents) { + nTween.onStart = onStart; + nTween.onUpdate = onUpdate; + nTween.onComplete = onComplete; + nTween.onOverwrite = onOverwrite; + nTween.onError = onError; + nTween.onStartParams = onStartParams; + nTween.onUpdateParams = onUpdateParams; + nTween.onCompleteParams = onCompleteParams; + nTween.onOverwriteParams = onOverwriteParams; + nTween.onStartScope = onStartScope; + nTween.onUpdateScope = onUpdateScope; + nTween.onCompleteScope = onCompleteScope; + nTween.onOverwriteScope = onOverwriteScope; + nTween.onErrorScope = onErrorScope; + } + nTween.rounded = rounded; + nTween.isPaused = isPaused; + nTween.timePaused = timePaused; + nTween.isCaller = isCaller; + nTween.count = count; + nTween.timesCalled = timesCalled; + nTween.waitFrames = waitFrames; + nTween.hasStarted = hasStarted; + + return nTween; + } + + /** + * Returns this object described as a String. + * + * @return String The description of this object. + */ + public function toString():String { + var returnStr:String = "\n[TweenListObj "; + returnStr += "scope:" + String(scope); + returnStr += ", properties:"; + var isFirst:Boolean = true; + for (var i:String in properties) { + if (!isFirst) returnStr += ","; + returnStr += "[name:"+properties[i].name; + returnStr += ",valueStart:"+properties[i].valueStart; + returnStr += ",valueComplete:"+properties[i].valueComplete; + returnStr += "]"; + isFirst = false; + } + returnStr += ", timeStart:" + String(timeStart); + returnStr += ", timeComplete:" + String(timeComplete); + returnStr += ", useFrames:" + String(useFrames); + returnStr += ", transition:" + String(transition); + returnStr += ", transitionParams:" + String(transitionParams); + + if (skipUpdates) returnStr += ", skipUpdates:" + String(skipUpdates); + if (updatesSkipped) returnStr += ", updatesSkipped:" + String(updatesSkipped); + + if (Boolean(onStart)) returnStr += ", onStart:" + String(onStart); + if (Boolean(onUpdate)) returnStr += ", onUpdate:" + String(onUpdate); + if (Boolean(onComplete)) returnStr += ", onComplete:" + String(onComplete); + if (Boolean(onOverwrite)) returnStr += ", onOverwrite:" + String(onOverwrite); + if (Boolean(onError)) returnStr += ", onError:" + String(onError); + + if (onStartParams) returnStr += ", onStartParams:" + String(onStartParams); + if (onUpdateParams) returnStr += ", onUpdateParams:" + String(onUpdateParams); + if (onCompleteParams) returnStr += ", onCompleteParams:" + String(onCompleteParams); + if (onOverwriteParams) returnStr += ", onOverwriteParams:" + String(onOverwriteParams); + + if (onStartScope) returnStr += ", onStartScope:" + String(onStartScope); + if (onUpdateScope) returnStr += ", onUpdateScope:" + String(onUpdateScope); + if (onCompleteScope) returnStr += ", onCompleteScope:" + String(onCompleteScope); + if (onOverwriteScope) returnStr += ", onOverwriteScope:" + String(onOverwriteScope); + if (onErrorScope) returnStr += ", onErrorScope:" + String(onErrorScope); + + if (rounded) returnStr += ", rounded:" + String(rounded); + if (isPaused) returnStr += ", isPaused:" + String(isPaused); + if (timePaused) returnStr += ", timePaused:" + String(timePaused); + if (isCaller) returnStr += ", isCaller:" + String(isCaller); + if (count) returnStr += ", count:" + String(count); + if (timesCalled) returnStr += ", timesCalled:" + String(timesCalled); + if (waitFrames) returnStr += ", waitFrames:" + String(waitFrames); + if (hasStarted) returnStr += ", hasStarted:" + String(hasStarted); + + returnStr += "]\n"; + return returnStr; + } + + /** + * Checks if p_obj "inherits" properties from other objects, as set by the "base" property. Will create a new object, leaving others intact. + * o_bj.base can be an object or an array of objects. Properties are collected from the first to the last element of the "base" filed, with higher + * indexes overwritting smaller ones. Does not modify any of the passed objects, but makes a shallow copy of all properties. + * + * @param p_obj Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @return Object A new object with all properties from the p_obj and p_obj.base. + */ + + public static function makePropertiesChain(p_obj : Object) : Object{ + // Is this object inheriting properties from another object? + var baseObject : Object = p_obj.base; + if(baseObject){ + // object inherits. Are we inheriting from an object or an array + var chainedObject : Object = {}; + var chain : Object; + if (baseObject is Array){ + // Inheritance chain is the base array + chain = []; + // make a shallow copy + for (var k : Number = 0 ; k< baseObject.length; k++) chain.push(baseObject[k]); + }else{ + // Only one object to be added to the array + chain = [baseObject]; + } + // add the final object to the array, so it's properties are added last + chain.push(p_obj); + var currChainObj : Object; + // Loops through each object adding it's property to the final object + var len : Number = chain.length; + for(var i : Number = 0; i < len ; i ++){ + if(chain[i]["base"]){ + // deal with recursion: watch the order! "parent" base must be concatenated first! + currChainObj = AuxFunctions.concatObjects( makePropertiesChain(chain[i]["base"] ), chain[i]); + }else{ + currChainObj = chain[i] ; + } + chainedObject = AuxFunctions.concatObjects(chainedObject, currChainObj ); + } + if( chainedObject["base"]){ + delete chainedObject["base"]; + } + return chainedObject; + }else{ + // No inheritance, just return the object it self + return p_obj; + } + } + + + } + + + + +} diff --git a/docviewerflex/src/caurina/transitions/Tweener.as b/docviewerflex/src/caurina/transitions/Tweener.as index 99b958b..1df2f3f 100644 --- a/docviewerflex/src/caurina/transitions/Tweener.as +++ b/docviewerflex/src/caurina/transitions/Tweener.as @@ -1,1143 +1,1108 @@ -/** - * Tweener - * Transition controller for movieclips, sounds, textfields and other objects - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert, Francis Turmel - * @version 1.33.74 - */ - -/* -Licensed under the MIT License - -Copyright (c) 2006-2008 Zeh Fernando, Nate Chatellier, Arthur Debert and Francis -Turmel - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -http://code.google.com/p/tweener/ -http://code.google.com/p/tweener/wiki/License -*/ - -package caurina.transitions { - - import flash.display.*; - import flash.events.Event; - import flash.utils.getTimer; - - public class Tweener { - - private static var __tweener_controller__:MovieClip; // Used to ensure the stage copy is always accessible (garbage collection) - - private static var _engineExists:Boolean = false; // Whether or not the engine is currently running - private static var _inited:Boolean = false; // Whether or not the class has been initiated - private static var _currentTime:Number; // The current time. This is generic for all tweenings for a "time grid" based update - private static var _currentTimeFrame:Number; // The current frame. Used on frame-based tweenings - - private static var _tweenList:Array; // List of active tweens - - private static var _timeScale:Number = 1; // Time scale (default = 1) - - private static var _transitionList:Object; // List of "pre-fetched" transition functions - private static var _specialPropertyList:Object; // List of special properties - private static var _specialPropertyModifierList:Object; // List of special property modifiers - private static var _specialPropertySplitterList:Object; // List of special property splitters - - public static var autoOverwrite:Boolean = true; // If true, auto overwrite on new tweens is on unless declared as false - - /** - * There's no constructor. - * @private - */ - public function Tweener () { - trace ("Tweener is a static class and should not be instantiated."); - } - - // ================================================================================================================================== - // TWEENING CONTROL functions ------------------------------------------------------------------------------------------------------- - - /** - * Adds a new tweening. - * - * @param (first-n param) Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects - * @param (last param) Object Object containing the specified parameters in any order, as well as the properties that should be tweened and their values - * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) - * @param .delay Number Delay time (defaults 0) - * @param .useFrames Boolean Whether to use frames instead of seconds for time control (defaults false) - * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") - * @param .onStart Function * Direct property, See the TweenListObj class - * @param .onUpdate Function * Direct property, See the TweenListObj class - * @param .onComplete Function * Direct property, See the TweenListObj class - * @param .onOverwrite Function * Direct property, See the TweenListObj class - * @param .onStartParams Array * Direct property, See the TweenListObj class - * @param .onUpdateParams Array * Direct property, See the TweenListObj class - * @param .onCompleteParams Array * Direct property, See the TweenListObj class - * @param .onOverwriteParams Array * Direct property, See the TweenListObj class - * @param .rounded Boolean * Direct property, See the TweenListObj class - * @param .skipUpdates Number * Direct property, See the TweenListObj class - * @return Boolean TRUE if the tween was successfully added, FALSE if otherwise - */ - public static function addTween (p_scopes:Object = null, p_parameters:Object = null):Boolean { - if (!Boolean(p_scopes)) return false; - - var i:Number, j:Number, istr:String; - - var rScopes:Array; // List of objects to tween - if (p_scopes is Array) { - // The first argument is an array - rScopes = p_scopes.concat(); - } else { - // The first argument(s) is(are) object(s) - rScopes = [p_scopes]; - } - - // make properties chain ("inheritance") - var p_obj:Object = TweenListObj.makePropertiesChain(p_parameters); - - // Creates the main engine if it isn't active - if (!_inited) init(); - if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... - - // Creates a "safer", more strict tweening object - var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time - var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay - - // Creates the property list; everything that isn't a hardcoded variable - var rProperties:Array = new Array(); // Object containing a list of PropertyInfoObj instances - var restrictedWords:Object = {overwrite:true, time:true, delay:true, useFrames:true, skipUpdates:true, transition:true, transitionParams:true, onStart:true, onUpdate:true, onComplete:true, onOverwrite:true, onError:true, rounded:true, onStartParams:true, onUpdateParams:true, onCompleteParams:true, onOverwriteParams:true, onStartScope:true, onUpdateScope:true, onCompleteScope:true, onOverwriteScope:true, onErrorScope:true}; - var modifiedProperties:Object = new Object(); - for (istr in p_obj) { - if (!restrictedWords[istr]) { - // It's an additional pair, so adds - if (_specialPropertySplitterList[istr]) { - // Special property splitter - var splitProperties:Array = _specialPropertySplitterList[istr].splitValues(p_obj[istr], _specialPropertySplitterList[istr].parameters); - for (i = 0; i < splitProperties.length; i++) { - if (_specialPropertySplitterList[splitProperties[i].name]) { - var splitProperties2:Array = _specialPropertySplitterList[splitProperties[i].name].splitValues(splitProperties[i].value, _specialPropertySplitterList[splitProperties[i].name].parameters); - for (j = 0; j < splitProperties2.length; j++) { - rProperties[splitProperties2[j].name] = {valueStart:undefined, valueComplete:splitProperties2[j].value, arrayIndex:splitProperties2[j].arrayIndex, isSpecialProperty:false}; - } - } else { - rProperties[splitProperties[i].name] = {valueStart:undefined, valueComplete:splitProperties[i].value, arrayIndex:splitProperties[i].arrayIndex, isSpecialProperty:false}; - } - } - } else if (_specialPropertyModifierList[istr] != undefined) { - // Special property modifier - var tempModifiedProperties:Array = _specialPropertyModifierList[istr].modifyValues(p_obj[istr]); - for (i = 0; i < tempModifiedProperties.length; i++) { - modifiedProperties[tempModifiedProperties[i].name] = {modifierParameters:tempModifiedProperties[i].parameters, modifierFunction:_specialPropertyModifierList[istr].getValue}; - } - } else { - // Regular property or special property, just add the property normally - rProperties[istr] = {valueStart:undefined, valueComplete:p_obj[istr]}; - } - } - } - - // Verifies whether the properties exist or not, for warning messages - for (istr in rProperties) { - if (_specialPropertyList[istr] != undefined) { - rProperties[istr].isSpecialProperty = true; - } else { - if (rScopes[0][istr] == undefined) { - printError("The property '" + istr + "' doesn't seem to be a normal object property of " + String(rScopes[0]) + " or a registered special property."); - } - } - } - - // Adds the modifiers to the list of properties - for (istr in modifiedProperties) { - if (rProperties[istr] != undefined) { - rProperties[istr].modifierParameters = modifiedProperties[istr].modifierParameters; - rProperties[istr].modifierFunction = modifiedProperties[istr].modifierFunction; - } - - } - - var rTransition:Function; // Real transition - - if (typeof p_obj.transition == "string") { - // String parameter, transition names - var trans:String = p_obj.transition.toLowerCase(); - rTransition = _transitionList[trans]; - } else { - // Proper transition function - rTransition = p_obj.transition; - } - if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; - - var nProperties:Object; - var nTween:TweenListObj; - var myT:Number; - - for (i = 0; i < rScopes.length; i++) { - // Makes a copy of the properties - nProperties = new Object(); - for (istr in rProperties) { - nProperties[istr] = new PropertyInfoObj(rProperties[istr].valueStart, rProperties[istr].valueComplete, rProperties[istr].valueComplete, rProperties[istr].arrayIndex, {}, rProperties[istr].isSpecialProperty, rProperties[istr].modifierFunction, rProperties[istr].modifierParameters); - } - - if (p_obj.useFrames == true) { - nTween = new TweenListObj( - /* scope */ rScopes[i], - /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), - /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), - /* useFrames */ true, - /* transition */ rTransition, - p_obj.transitionParams - ); - } else { - nTween = new TweenListObj( - /* scope */ rScopes[i], - /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), - /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), - /* useFrames */ false, - /* transition */ rTransition, - p_obj.transitionParams - ); - } - - nTween.properties = nProperties; - nTween.onStart = p_obj.onStart; - nTween.onUpdate = p_obj.onUpdate; - nTween.onComplete = p_obj.onComplete; - nTween.onOverwrite = p_obj.onOverwrite; - nTween.onError = p_obj.onError; - nTween.onStartParams = p_obj.onStartParams; - nTween.onUpdateParams = p_obj.onUpdateParams; - nTween.onCompleteParams = p_obj.onCompleteParams; - nTween.onOverwriteParams = p_obj.onOverwriteParams; - nTween.onStartScope = p_obj.onStartScope; - nTween.onUpdateScope = p_obj.onUpdateScope; - nTween.onCompleteScope = p_obj.onCompleteScope; - nTween.onOverwriteScope = p_obj.onOverwriteScope; - nTween.onErrorScope = p_obj.onErrorScope; - nTween.rounded = p_obj.rounded; - nTween.skipUpdates = p_obj.skipUpdates; - - // Remove other tweenings that occur at the same time - if (p_obj.overwrite == undefined ? autoOverwrite : p_obj.overwrite) removeTweensByTime(nTween.scope, nTween.properties, nTween.timeStart, nTween.timeComplete); // Changed on 1.32.74 - - // And finally adds it to the list - _tweenList.push(nTween); - - // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution - if (rTime == 0 && rDelay == 0) { - myT = _tweenList.length-1; - updateTweenByIndex(myT); - removeTweenByIndex(myT); - } - } - - return true; - } - - // A "caller" is like this: [ | | | ||] got it? :) - // this function is crap - should be fixed later/extend on addTween() - - /** - * Adds a new caller tweening. - * - * @param (first-n param) Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects - * @param (last param) Object containing the specified parameters in any order, as well as the properties that should be tweened and their values - * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) - * @param .delay Number Delay time (defaults 0) - * @param .count Number Number of times this caller should be called - * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") - * @param .onStart Function Event called when tween starts - * @param .onUpdate Function Event called when tween updates - * @param .onComplete Function Event called when tween ends - * @param .waitFrames Boolean Whether to wait (or not) one frame for each call - * @return true if the tween was successfully added, false if otherwise. - */ - public static function addCaller (p_scopes:Object = null, p_parameters:Object = null):Boolean { - if (!Boolean(p_scopes)) return false; - - var i:Number; - - var rScopes:Array; // List of objects to tween - if (p_scopes is Array) { - // The first argument is an array - rScopes = p_scopes.concat(); - } else { - // The first argument(s) is(are) object(s) - rScopes = [p_scopes]; - } - - var p_obj:Object = p_parameters; - - // Creates the main engine if it isn't active - if (!_inited) init(); - if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... - - // Creates a "safer", more strict tweening object - var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time - var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay - - var rTransition:Function; // Real transition - if (typeof p_obj.transition == "string") { - // String parameter, transition names - var trans:String = p_obj.transition.toLowerCase(); - rTransition = _transitionList[trans]; - } else { - // Proper transition function - rTransition = p_obj.transition; - } - if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; - - var nTween:TweenListObj; - var myT:Number; - for (i = 0; i < rScopes.length; i++) { - - if (p_obj.useFrames == true) { - nTween = new TweenListObj( - /* scope */ rScopes[i], - /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), - /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), - /* useFrames */ true, - /* transition */ rTransition, - p_obj.transitionParams - ); - } else { - nTween = new TweenListObj( - /* scope */ rScopes[i], - /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), - /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), - /* useFrames */ false, - /* transition */ rTransition, - p_obj.transitionParams - ); - } - - nTween.properties = null; - nTween.onStart = p_obj.onStart; - nTween.onUpdate = p_obj.onUpdate; - nTween.onComplete = p_obj.onComplete; - nTween.onOverwrite = p_obj.onOverwrite; - nTween.onStartParams = p_obj.onStartParams; - nTween.onUpdateParams = p_obj.onUpdateParams; - nTween.onCompleteParams = p_obj.onCompleteParams; - nTween.onOverwriteParams = p_obj.onOverwriteParams; - nTween.onStartScope = p_obj.onStartScope; - nTween.onUpdateScope = p_obj.onUpdateScope; - nTween.onCompleteScope = p_obj.onCompleteScope; - nTween.onOverwriteScope = p_obj.onOverwriteScope; - nTween.onErrorScope = p_obj.onErrorScope; - nTween.isCaller = true; - nTween.count = p_obj.count; - nTween.waitFrames = p_obj.waitFrames; - - // And finally adds it to the list - _tweenList.push(nTween); - - // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution - if (rTime == 0 && rDelay == 0) { - myT = _tweenList.length-1; - updateTweenByIndex(myT); - removeTweenByIndex(myT); - } - } - - return true; - } - - /** - * Remove an specified tweening of a specified object the tweening list, if it conflicts with the given time. - * - * @param p_scope Object List of objects affected - * @param p_properties Object List of properties affected (PropertyInfoObj instances) - * @param p_timeStart Number Time when the new tween starts - * @param p_timeComplete Number Time when the new tween ends - * @return Boolean Whether or not it actually deleted something - */ - public static function removeTweensByTime (p_scope:Object, p_properties:Object, p_timeStart:Number, p_timeComplete:Number):Boolean { - var removed:Boolean = false; - var removedLocally:Boolean; - - var i:uint; - var tl:uint = _tweenList.length; - var pName:String; - - for (i = 0; i < tl; i++) { - if (Boolean(_tweenList[i]) && p_scope == _tweenList[i].scope) { - // Same object... - if (p_timeComplete > _tweenList[i].timeStart && p_timeStart < _tweenList[i].timeComplete) { - // New time should override the old one... - removedLocally = false; - for (pName in _tweenList[i].properties) { - if (Boolean(p_properties[pName])) { - // Same object, same property - // Finally, remove this old tweening and use the new one - if (Boolean(_tweenList[i].onOverwrite)) { - var eventScope:Object = Boolean(_tweenList[i].onOverwriteScope) ? _tweenList[i].onOverwriteScope : _tweenList[i].scope; - try { - _tweenList[i].onOverwrite.apply(eventScope, _tweenList[i].onOverwriteParams); - } catch(e:Error) { - handleError(_tweenList[i], e, "onOverwrite"); - } - } - _tweenList[i].properties[pName] = undefined; - delete _tweenList[i].properties[pName]; - removedLocally = true; - removed = true; - } - } - if (removedLocally) { - // Verify if this can be deleted - if (AuxFunctions.getObjectLength(_tweenList[i].properties) == 0) removeTweenByIndex(i); - } - } - } - } - - return removed; - } - - /* - public static function removeTweens (p_scope:Object, ...args):Boolean { - // Create the property list - var properties:Array = new Array(); - var i:uint; - for (i = 0; i < args.length; i++) { - if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); - } - // Call the affect function on the specified properties - return affectTweens(removeTweenByIndex, p_scope, properties); - } - */ - - /** - * Remove tweenings from a given object from the tweening list. - * - * @param p_tween Object Object that must have its tweens removed - * @param (2nd-last params) Object Property(ies) that must be removed - * @return Boolean Whether or not it successfully removed this tweening - */ - public static function removeTweens (p_scope:Object, ...args):Boolean { - // Create the property list - var properties:Array = new Array(); - var i:uint; - for (i = 0; i < args.length; i++) { - if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1){ - if (_specialPropertySplitterList[args[i]]){ - //special property, get splitter array first - var sps:SpecialPropertySplitter = _specialPropertySplitterList[args[i]]; - var specialProps:Array = sps.splitValues(p_scope, null); - for (var j:uint = 0; jtrue if it successfully removed any tweening, false if otherwise. - */ - public static function removeAllTweens ():Boolean { - if (!Boolean(_tweenList)) return false; - var removed:Boolean = false; - var i:uint; - for (i = 0; i<_tweenList.length; i++) { - removeTweenByIndex(i); - removed = true; - } - return removed; - } - - /** - * Pause tweenings for a given object. - * - * @param p_scope Object that must have its tweens paused - * @param (2nd-last params) Property(ies) that must be paused - * @return true if it successfully paused any tweening, false if otherwise. - */ - public static function pauseTweens (p_scope:Object, ...args):Boolean { - // Create the property list - var properties:Array = new Array(); - var i:uint; - for (i = 0; i < args.length; i++) { - if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); - } - // Call the affect function on the specified properties - return affectTweens(pauseTweenByIndex, p_scope, properties); - } - - /** - * Pause all tweenings on the engine. - * - * @return true if it successfully paused any tweening, false if otherwise. - * @see #resumeAllTweens() - */ - public static function pauseAllTweens ():Boolean { - if (!Boolean(_tweenList)) return false; - var paused:Boolean = false; - var i:uint; - for (i = 0; i < _tweenList.length; i++) { - pauseTweenByIndex(i); - paused = true; - } - return paused; - } - - /** - * Resume tweenings from a given object. - * - * @param p_scope Object Object that must have its tweens resumed - * @param (2nd-last params) Object Property(ies) that must be resumed - * @return Boolean Whether or not it successfully resumed something - */ - public static function resumeTweens (p_scope:Object, ...args):Boolean { - // Create the property list - var properties:Array = new Array(); - var i:uint; - for (i = 0; i < args.length; i++) { - if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); - } - // Call the affect function on the specified properties - return affectTweens(resumeTweenByIndex, p_scope, properties); - } - - /** - * Resume all tweenings on the engine. - * - * @return true if it successfully resumed any tweening, false if otherwise. - * @see #pauseAllTweens() - */ - public static function resumeAllTweens ():Boolean { - if (!Boolean(_tweenList)) return false; - var resumed:Boolean = false; - var i:uint; - for (i = 0; i < _tweenList.length; i++) { - resumeTweenByIndex(i); - resumed = true; - } - return resumed; - } - - /** - * Do some generic action on specific tweenings (pause, resume, remove, more?) - * - * @param p_function Function Function to run on the tweenings that match - * @param p_scope Object Object that must have its tweens affected by the function - * @param p_properties Array Array of strings that must be affected - * @return Boolean Whether or not it successfully affected something - */ - private static function affectTweens (p_affectFunction:Function, p_scope:Object, p_properties:Array):Boolean { - var affected:Boolean = false; - var i:uint; - - if (!Boolean(_tweenList)) return false; - - for (i = 0; i < _tweenList.length; i++) { - if (_tweenList[i] && _tweenList[i].scope == p_scope) { - if (p_properties.length == 0) { - // Can affect everything - p_affectFunction(i); - affected = true; - } else { - // Must check whether this tween must have specific properties affected - var affectedProperties:Array = new Array(); - var j:uint; - for (j = 0; j < p_properties.length; j++) { - if (Boolean(_tweenList[i].properties[p_properties[j]])) { - affectedProperties.push(p_properties[j]); - } - } - if (affectedProperties.length > 0) { - // This tween has some properties that need to be affected - var objectProperties:uint = AuxFunctions.getObjectLength(_tweenList[i].properties); - if (objectProperties == affectedProperties.length) { - // The list of properties is the same as all properties, so affect it all - p_affectFunction(i); - affected = true; - } else { - // The properties are mixed, so split the tween and affect only certain specific properties - var slicedTweenIndex:uint = splitTweens(i, affectedProperties); - p_affectFunction(slicedTweenIndex); - affected = true; - } - } - } - } - } - return affected; - } - - /** - * Splits a tweening in two - * - * @param p_tween Number Object that must have its tweens split - * @param p_properties Array Array of strings containing the list of properties that must be separated - * @return Number The index number of the new tween - */ - public static function splitTweens (p_tween:Number, p_properties:Array):uint { - // First, duplicates - var originalTween:TweenListObj = _tweenList[p_tween]; - var newTween:TweenListObj = originalTween.clone(false); - - // Now, removes tweenings where needed - var i:uint; - var pName:String; - - // Removes the specified properties from the old one - for (i = 0; i < p_properties.length; i++) { - pName = p_properties[i]; - if (Boolean(originalTween.properties[pName])) { - originalTween.properties[pName] = undefined; - delete originalTween.properties[pName]; - } - } - - // Removes the unspecified properties from the new one - var found:Boolean; - for (pName in newTween.properties) { - found = false; - for (i = 0; i < p_properties.length; i++) { - if (p_properties[i] == pName) { - found = true; - break; - } - } - if (!found) { - newTween.properties[pName] = undefined; - delete newTween.properties[pName]; - } - } - - // If there are empty property lists, a cleanup is done on the next updateTweens() cycle - _tweenList.push(newTween); - return (_tweenList.length - 1); - - } - - // ================================================================================================================================== - // ENGINE functions ----------------------------------------------------------------------------------------------------------------- - - /** - * Updates all existing tweenings. - * - * @return Boolean FALSE if no update was made because there's no tweening (even delayed ones) - */ - private static function updateTweens ():Boolean { - if (_tweenList.length == 0) return false; - var i:int; - for (i = 0; i < _tweenList.length; i++) { - // Looping throught each Tweening and updating the values accordingly - if (_tweenList[i] == undefined || !_tweenList[i].isPaused) { - if (!updateTweenByIndex(i)) removeTweenByIndex(i); - if (_tweenList[i] == null) { - removeTweenByIndex(i, true); - i--; - } - } - } - - return true; - } - - /** - * Remove a specific tweening from the tweening list. - * - * @param p_tween Number Index of the tween to be removed on the tweenings list - * @return Boolean Whether or not it successfully removed this tweening - */ - public static function removeTweenByIndex (i:Number, p_finalRemoval:Boolean = false):Boolean { - _tweenList[i] = null; - if (p_finalRemoval) _tweenList.splice(i, 1); - return true; - } - - /** - * Pauses a specific tween. - * - * @param p_tween Number Index of the tween to be paused - * @return Boolean Whether or not it successfully paused this tweening - */ - public static function pauseTweenByIndex (p_tween:Number):Boolean { - var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening - if (tTweening == null || tTweening.isPaused) return false; - tTweening.timePaused = getCurrentTweeningTime(tTweening); - tTweening.isPaused = true; - - return true; - } - - /** - * Resumes a specific tween. - * - * @param p_tween Number Index of the tween to be resumed - * @return Boolean Whether or not it successfully resumed this tweening - */ - public static function resumeTweenByIndex (p_tween:Number):Boolean { - var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening - if (tTweening == null || !tTweening.isPaused) return false; - var cTime:Number = getCurrentTweeningTime(tTweening); - tTweening.timeStart += cTime - tTweening.timePaused; - tTweening.timeComplete += cTime - tTweening.timePaused; - tTweening.timePaused = undefined; - tTweening.isPaused = false; - - return true; - } - - /** - * Updates a specific tween. - * - * @param i Number Index (from the tween list) of the tween that should be updated - * @return Boolean FALSE if it's already finished and should be deleted, TRUE if otherwise - */ - private static function updateTweenByIndex (i:Number):Boolean { - - var tTweening:TweenListObj = _tweenList[i]; // Shortcut to this tweening - - if (tTweening == null || !Boolean(tTweening.scope)) return false; - - var isOver:Boolean = false; // Whether or not it's over the update time - var mustUpdate:Boolean; // Whether or not it should be updated (skipped if false) - - var nv:Number; // New value for each property - - var t:Number; // current time (frames, seconds) - var b:Number; // beginning value - var c:Number; // change in value - var d:Number; // duration (frames, seconds) - - var pName:String; // Property name, used in loops - var eventScope:Object; // Event scope, used to call functions - - // Shortcut stuff for speed - var tScope:Object; // Current scope - var cTime:Number = getCurrentTweeningTime(tTweening); - var tProperty:Object; // Property being checked - - if (cTime >= tTweening.timeStart) { - // Can already start - - tScope = tTweening.scope; - - if (tTweening.isCaller) { - // It's a 'caller' tween - if (!tTweening.hasStarted) { - if (Boolean(tTweening.onStart)) { - eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; - try { - tTweening.onStart.apply(eventScope, tTweening.onStartParams); - } catch(e2:Error) { - handleError(tTweening, e2, "onStart"); - } - } - tTweening.hasStarted = true; - } - do { - t = ((tTweening.timeComplete - tTweening.timeStart)/tTweening.count) * (tTweening.timesCalled+1); - b = tTweening.timeStart; - c = tTweening.timeComplete - tTweening.timeStart; - d = tTweening.timeComplete - tTweening.timeStart; - nv = tTweening.transition(t, b, c, d); - - if (cTime >= nv) { - if (Boolean(tTweening.onUpdate)) { - eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; - try { - tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); - } catch(e1:Error) { - handleError(tTweening, e1, "onUpdate"); - } - } - - tTweening.timesCalled++; - if (tTweening.timesCalled >= tTweening.count) { - isOver = true; - break; - } - if (tTweening.waitFrames) break; - } - - } while (cTime >= nv); - } else { - // It's a normal transition tween - - mustUpdate = tTweening.skipUpdates < 1 || !tTweening.skipUpdates || tTweening.updatesSkipped >= tTweening.skipUpdates; - - if (cTime >= tTweening.timeComplete) { - isOver = true; - mustUpdate = true; - } - - if (!tTweening.hasStarted) { - // First update, read all default values (for proper filter tweening) - if (Boolean(tTweening.onStart)) { - eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; - try { - tTweening.onStart.apply(eventScope, tTweening.onStartParams); - } catch(e2:Error) { - handleError(tTweening, e2, "onStart"); - } - } - var pv:Number; - for (pName in tTweening.properties) { - if (tTweening.properties[pName].isSpecialProperty) { - // It's a special property, tunnel via the special property function - if (Boolean(_specialPropertyList[pName].preProcess)) { - tTweening.properties[pName].valueComplete = _specialPropertyList[pName].preProcess(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].originalValueComplete, tTweening.properties[pName].extra); - } - pv = _specialPropertyList[pName].getValue(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); - } else { - // Directly read property - pv = tScope[pName]; - } - tTweening.properties[pName].valueStart = isNaN(pv) ? tTweening.properties[pName].valueComplete : pv; - } - mustUpdate = true; - tTweening.hasStarted = true; - } - - if (mustUpdate) { - for (pName in tTweening.properties) { - tProperty = tTweening.properties[pName]; - - if (isOver) { - // Tweening time has finished, just set it to the final value - nv = tProperty.valueComplete; - } else { - if (tProperty.hasModifier) { - // Modified - t = cTime - tTweening.timeStart; - d = tTweening.timeComplete - tTweening.timeStart; - nv = tTweening.transition(t, 0, 1, d, tTweening.transitionParams); - nv = tProperty.modifierFunction(tProperty.valueStart, tProperty.valueComplete, nv, tProperty.modifierParameters); - } else { - // Normal update - t = cTime - tTweening.timeStart; - b = tProperty.valueStart; - c = tProperty.valueComplete - tProperty.valueStart; - d = tTweening.timeComplete - tTweening.timeStart; - nv = tTweening.transition(t, b, c, d, tTweening.transitionParams); - } - } - - if (tTweening.rounded) nv = Math.round(nv); - if (tProperty.isSpecialProperty) { - // It's a special property, tunnel via the special property method - _specialPropertyList[pName].setValue(tScope, nv, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); - } else { - // Directly set property - tScope[pName] = nv; - } - } - - tTweening.updatesSkipped = 0; - - if (Boolean(tTweening.onUpdate)) { - eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; - try { - tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); - } catch(e3:Error) { - handleError(tTweening, e3, "onUpdate"); - } - } - } else { - tTweening.updatesSkipped++; - } - } - - if (isOver && Boolean(tTweening.onComplete)) { - eventScope = Boolean(tTweening.onCompleteScope) ? tTweening.onCompleteScope : tScope; - try { - tTweening.onComplete.apply(eventScope, tTweening.onCompleteParams); - } catch(e4:Error) { - handleError(tTweening, e4, "onComplete"); - } - } - - return (!isOver); - } - - // On delay, hasn't started, so returns true - return (true); - - } - - /** - * Initiates the Tweener--should only be ran once. - */ - public static function init(...rest):void { - _inited = true; - - // Registers all default equations - _transitionList = new Object(); - Equations.init(); - - // Registers all default special properties - _specialPropertyList = new Object(); - _specialPropertyModifierList = new Object(); - _specialPropertySplitterList = new Object(); - } - - /** - * Adds a new function to the available transition list "shortcuts". - * - * @param p_name String Shorthand transition name - * @param p_function Function The proper equation function - */ - public static function registerTransition(p_name:String, p_function:Function): void { - if (!_inited) init(); - _transitionList[p_name] = p_function; - } - - /** - * Adds a new special property to the available special property list. - * - * @param p_name Name of the "special" property. - * @param p_getFunction Function that gets the value. - * @param p_setFunction Function that sets the value. - */ - public static function registerSpecialProperty(p_name:String, p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null): void { - if (!_inited) init(); - var sp:SpecialProperty = new SpecialProperty(p_getFunction, p_setFunction, p_parameters, p_preProcessFunction); - _specialPropertyList[p_name] = sp; - } - - /** - * Adds a new special property modifier to the available modifier list. - * - * @param p_name Name of the "special" property modifier. - * @param p_modifyFunction Function that modifies the value. - * @param p_getFunction Function that gets the value. - */ - public static function registerSpecialPropertyModifier(p_name:String, p_modifyFunction:Function, p_getFunction:Function): void { - if (!_inited) init(); - var spm:SpecialPropertyModifier = new SpecialPropertyModifier(p_modifyFunction, p_getFunction); - _specialPropertyModifierList[p_name] = spm; - } - - /** - * Adds a new special property splitter to the available splitter list. - * - * @param p_name Name of the "special" property splitter. - * @param p_splitFunction Function that splits the value. - */ - public static function registerSpecialPropertySplitter(p_name:String, p_splitFunction:Function, p_parameters:Array = null): void { - if (!_inited) init(); - var sps:SpecialPropertySplitter = new SpecialPropertySplitter(p_splitFunction, p_parameters); - _specialPropertySplitterList[p_name] = sps; - } - - /** - * Starts the Tweener class engine. It is supposed to be running every time a tween exists. - */ - private static function startEngine():void { - _engineExists = true; - _tweenList = new Array(); - - __tweener_controller__ = new MovieClip(); - __tweener_controller__.addEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); - - _currentTimeFrame = 0; - updateTime(); - } - - /** - * Stops the Tweener class engine. - */ - private static function stopEngine():void { - _engineExists = false; - _tweenList = null; - _currentTime = 0; - _currentTimeFrame = 0; - __tweener_controller__.removeEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); - __tweener_controller__ = null; - } - - /** - * Updates the time to enforce time grid-based updates. - */ - public static function updateTime():void { - _currentTime = getTimer(); - } - - /** - * Updates the current frame count - */ - public static function updateFrame():void { - _currentTimeFrame++; - } - - /** - * Ran once every frame. It's the main engine; updates all existing tweenings. - */ - public static function onEnterFrame(e:Event):void { - updateTime(); - updateFrame(); - var hasUpdated:Boolean = false; - hasUpdated = updateTweens(); - if (!hasUpdated) stopEngine(); // There's no tweening to update or wait, so it's better to stop the engine - } - - /** - * Sets the new time scale. - * - * @param p_time Number New time scale (0.5 = slow, 1 = normal, 2 = 2x fast forward, etc) - */ - public static function setTimeScale(p_time:Number):void { - var i:Number; - var cTime:Number; - - if (isNaN(p_time)) p_time = 1; - if (p_time < 0.00001) p_time = 0.00001; - if (p_time != _timeScale) { - if (_tweenList != null) { - // Multiplies all existing tween times accordingly - for (i = 0; i<_tweenList.length; i++) { - cTime = getCurrentTweeningTime(_tweenList[i]); - _tweenList[i].timeStart = cTime - ((cTime - _tweenList[i].timeStart) * _timeScale / p_time); - _tweenList[i].timeComplete = cTime - ((cTime - _tweenList[i].timeComplete) * _timeScale / p_time); - if (_tweenList[i].timePaused != undefined) _tweenList[i].timePaused = cTime - ((cTime - _tweenList[i].timePaused) * _timeScale / p_time); - } - } - // Sets the new timescale value (for new tweenings) - _timeScale = p_time; - } - } - - - // ================================================================================================================================== - // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- - - /** - * Finds whether or not an object has any tweening. - * - * @param p_scope Target object. - * @return true if there's a tweening occuring on this object (paused, delayed, or active), false if otherwise. - */ - public static function isTweening (p_scope:Object):Boolean { - if (!Boolean(_tweenList)) return false; - var i:uint; - - for (i = 0; i<_tweenList.length; i++) { - if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { - return true; - } - } - return false; - } - - /** - * Returns an array containing a list of the properties being tweened for this object. - * - * @param p_scope Target object. - * @return Total number of properties being tweened (including delayed or paused tweens). - */ - public static function getTweens (p_scope:Object):Array { - if (!Boolean(_tweenList)) return []; - var i:uint; - var pName:String; - var tList:Array = new Array(); - - for (i = 0; i<_tweenList.length; i++) { - if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { - for (pName in _tweenList[i].properties) tList.push(pName); - } - } - return tList; - } - - /** - * Returns the number of properties being tweened for a given object. - * - * @param p_scope Target object. - * @return Total number of properties being tweened (including delayed or paused tweens). - */ - public static function getTweenCount (p_scope:Object):Number { - if (!Boolean(_tweenList)) return 0; - var i:uint; - var c:Number = 0; - - for (i = 0; i<_tweenList.length; i++) { - if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { - c += AuxFunctions.getObjectLength(_tweenList[i].properties); - } - } - return c; - } - - - /* Handles errors when Tweener executes any callbacks (onStart, onUpdate, etc) - * If the TweenListObj specifies an onError callback it well get called, passing the Error object and the current scope as parameters. If no onError callback is specified, it will trace a stackTrace. - */ - private static function handleError(pTweening : TweenListObj, pError : Error, pCallBackName : String) : void{ - // do we have an error handler? - if (Boolean(pTweening.onError) && (pTweening.onError is Function)){ - // yup, there's a handler. Wrap this in a try catch in case the onError throws an error itself. - var eventScope:Object = Boolean(pTweening.onErrorScope) ? pTweening.onErrorScope : pTweening.scope; - try { - pTweening.onError.apply(eventScope, [pTweening.scope, pError]); - } catch (metaError : Error){ - printError(String(pTweening.scope) + " raised an error while executing the 'onError' handler. Original error:\n " + pError.getStackTrace() + "\nonError error: " + metaError.getStackTrace()); - } - } else { - // no handler, simply trace the stack trace: - if (!Boolean(pTweening.onError)){ - printError(String(pTweening.scope) + " raised an error while executing the '" + pCallBackName + "'handler. \n" + pError.getStackTrace() ); - } - } - } - - /** - * Get the current tweening time (no matter if it uses frames or time as basis), given a specific tweening - * - * @param p_tweening TweenListObj Tween information - */ - public static function getCurrentTweeningTime(p_tweening:Object):Number { - return p_tweening.useFrames ? _currentTimeFrame : _currentTime; - } - - /** - * Return the current tweener version - * - * @return String The number of the current Tweener version - */ - public static function getVersion():String { - return "AS3 1.33.74"; - } - - - // ================================================================================================================================== - // DEBUG functions ------------------------------------------------------------------------------------------------------------------ - - /** - * Output an error message - * - * @param p_message String The error message to output - */ - public static function printError(p_message:String): void { - // - trace("## [Tweener] Error: "+p_message); - } - - } -} +package caurina.transitions { + + import flash.display.*; + import flash.events.Event; + import flash.utils.getTimer; + + public class Tweener { + + private static var __tweener_controller__:MovieClip; // Used to ensure the stage copy is always accessible (garbage collection) + + private static var _engineExists:Boolean = false; // Whether or not the engine is currently running + private static var _inited:Boolean = false; // Whether or not the class has been initiated + private static var _currentTime:Number; // The current time. This is generic for all tweenings for a "time grid" based update + private static var _currentTimeFrame:Number; // The current frame. Used on frame-based tweenings + + private static var _tweenList:Array; // List of active tweens + + private static var _timeScale:Number = 1; // Time scale (default = 1) + + private static var _transitionList:Object; // List of "pre-fetched" transition functions + private static var _specialPropertyList:Object; // List of special properties + private static var _specialPropertyModifierList:Object; // List of special property modifiers + private static var _specialPropertySplitterList:Object; // List of special property splitters + + public static var autoOverwrite:Boolean = true; // If true, auto overwrite on new tweens is on unless declared as false + + /** + * There's no constructor. + * @private + */ + public function Tweener () { + trace ("Tweener is a static class and should not be instantiated."); + } + + // ================================================================================================================================== + // TWEENING CONTROL functions ------------------------------------------------------------------------------------------------------- + + /** + * Adds a new tweening. + * + * @param (first-n param) Object Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @param (last param) Object Object containing the specified parameters in any order, as well as the properties that should be tweened and their values + * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) + * @param .delay Number Delay time (defaults 0) + * @param .useFrames Boolean Whether to use frames instead of seconds for time control (defaults false) + * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") + * @param .onStart Function * Direct property, See the TweenListObj class + * @param .onUpdate Function * Direct property, See the TweenListObj class + * @param .onComplete Function * Direct property, See the TweenListObj class + * @param .onOverwrite Function * Direct property, See the TweenListObj class + * @param .onStartParams Array * Direct property, See the TweenListObj class + * @param .onUpdateParams Array * Direct property, See the TweenListObj class + * @param .onCompleteParams Array * Direct property, See the TweenListObj class + * @param .onOverwriteParams Array * Direct property, See the TweenListObj class + * @param .rounded Boolean * Direct property, See the TweenListObj class + * @param .skipUpdates Number * Direct property, See the TweenListObj class + * @return Boolean TRUE if the tween was successfully added, FALSE if otherwise + */ + public static function addTween (p_scopes:Object = null, p_parameters:Object = null):Boolean { + if (!Boolean(p_scopes)) return false; + + var i:Number, j:Number, istr:String; + + var rScopes:Array; // List of objects to tween + if (p_scopes is Array) { + // The first argument is an array + rScopes = p_scopes.concat(); + } else { + // The first argument(s) is(are) object(s) + rScopes = [p_scopes]; + } + + // make properties chain ("inheritance") + var p_obj:Object = TweenListObj.makePropertiesChain(p_parameters); + + // Creates the main engine if it isn't active + if (!_inited) init(); + if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... + + // Creates a "safer", more strict tweening object + var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time + var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay + + // Creates the property list; everything that isn't a hardcoded variable + var rProperties:Array = new Array(); // Object containing a list of PropertyInfoObj instances + var restrictedWords:Object = {overwrite:true, time:true, delay:true, useFrames:true, skipUpdates:true, transition:true, transitionParams:true, onStart:true, onUpdate:true, onComplete:true, onOverwrite:true, onError:true, rounded:true, onStartParams:true, onUpdateParams:true, onCompleteParams:true, onOverwriteParams:true, onStartScope:true, onUpdateScope:true, onCompleteScope:true, onOverwriteScope:true, onErrorScope:true}; + var modifiedProperties:Object = new Object(); + for (istr in p_obj) { + if (!restrictedWords[istr]) { + // It's an additional pair, so adds + if (_specialPropertySplitterList[istr]) { + // Special property splitter + var splitProperties:Array = _specialPropertySplitterList[istr].splitValues(p_obj[istr], _specialPropertySplitterList[istr].parameters); + for (i = 0; i < splitProperties.length; i++) { + if (_specialPropertySplitterList[splitProperties[i].name]) { + var splitProperties2:Array = _specialPropertySplitterList[splitProperties[i].name].splitValues(splitProperties[i].value, _specialPropertySplitterList[splitProperties[i].name].parameters); + for (j = 0; j < splitProperties2.length; j++) { + rProperties[splitProperties2[j].name] = {valueStart:undefined, valueComplete:splitProperties2[j].value, arrayIndex:splitProperties2[j].arrayIndex, isSpecialProperty:false}; + } + } else { + rProperties[splitProperties[i].name] = {valueStart:undefined, valueComplete:splitProperties[i].value, arrayIndex:splitProperties[i].arrayIndex, isSpecialProperty:false}; + } + } + } else if (_specialPropertyModifierList[istr] != undefined) { + // Special property modifier + var tempModifiedProperties:Array = _specialPropertyModifierList[istr].modifyValues(p_obj[istr]); + for (i = 0; i < tempModifiedProperties.length; i++) { + modifiedProperties[tempModifiedProperties[i].name] = {modifierParameters:tempModifiedProperties[i].parameters, modifierFunction:_specialPropertyModifierList[istr].getValue}; + } + } else { + // Regular property or special property, just add the property normally + rProperties[istr] = {valueStart:undefined, valueComplete:p_obj[istr]}; + } + } + } + + // Verifies whether the properties exist or not, for warning messages + for (istr in rProperties) { + if (_specialPropertyList[istr] != undefined) { + rProperties[istr].isSpecialProperty = true; + } else { + if (rScopes[0][istr] == undefined) { + printError("The property '" + istr + "' doesn't seem to be a normal object property of " + String(rScopes[0]) + " or a registered special property."); + } + } + } + + // Adds the modifiers to the list of properties + for (istr in modifiedProperties) { + if (rProperties[istr] != undefined) { + rProperties[istr].modifierParameters = modifiedProperties[istr].modifierParameters; + rProperties[istr].modifierFunction = modifiedProperties[istr].modifierFunction; + } + + } + + var rTransition:Function; // Real transition + + if (typeof p_obj.transition == "string") { + // String parameter, transition names + var trans:String = p_obj.transition.toLowerCase(); + rTransition = _transitionList[trans]; + } else { + // Proper transition function + rTransition = p_obj.transition; + } + if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; + + var nProperties:Object; + var nTween:TweenListObj; + var myT:Number; + + for (i = 0; i < rScopes.length; i++) { + // Makes a copy of the properties + nProperties = new Object(); + for (istr in rProperties) { + nProperties[istr] = new PropertyInfoObj(rProperties[istr].valueStart, rProperties[istr].valueComplete, rProperties[istr].valueComplete, rProperties[istr].arrayIndex, {}, rProperties[istr].isSpecialProperty, rProperties[istr].modifierFunction, rProperties[istr].modifierParameters); + } + + if (p_obj.useFrames == true) { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), + /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), + /* useFrames */ true, + /* transition */ rTransition, + p_obj.transitionParams + ); + } else { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), + /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), + /* useFrames */ false, + /* transition */ rTransition, + p_obj.transitionParams + ); + } + + nTween.properties = nProperties; + nTween.onStart = p_obj.onStart; + nTween.onUpdate = p_obj.onUpdate; + nTween.onComplete = p_obj.onComplete; + nTween.onOverwrite = p_obj.onOverwrite; + nTween.onError = p_obj.onError; + nTween.onStartParams = p_obj.onStartParams; + nTween.onUpdateParams = p_obj.onUpdateParams; + nTween.onCompleteParams = p_obj.onCompleteParams; + nTween.onOverwriteParams = p_obj.onOverwriteParams; + nTween.onStartScope = p_obj.onStartScope; + nTween.onUpdateScope = p_obj.onUpdateScope; + nTween.onCompleteScope = p_obj.onCompleteScope; + nTween.onOverwriteScope = p_obj.onOverwriteScope; + nTween.onErrorScope = p_obj.onErrorScope; + nTween.rounded = p_obj.rounded; + nTween.skipUpdates = p_obj.skipUpdates; + + // Remove other tweenings that occur at the same time + if (p_obj.overwrite == undefined ? autoOverwrite : p_obj.overwrite) removeTweensByTime(nTween.scope, nTween.properties, nTween.timeStart, nTween.timeComplete); // Changed on 1.32.74 + + // And finally adds it to the list + _tweenList.push(nTween); + + // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution + if (rTime == 0 && rDelay == 0) { + myT = _tweenList.length-1; + updateTweenByIndex(myT); + removeTweenByIndex(myT); + } + } + + return true; + } + + // A "caller" is like this: [ | | | ||] got it? :) + // this function is crap - should be fixed later/extend on addTween() + + /** + * Adds a new caller tweening. + * + * @param (first-n param) Object that should be tweened: a movieclip, textfield, etc.. OR an array of objects + * @param (last param) Object containing the specified parameters in any order, as well as the properties that should be tweened and their values + * @param .time Number Time in seconds or frames for the tweening to take (defaults 2) + * @param .delay Number Delay time (defaults 0) + * @param .count Number Number of times this caller should be called + * @param .transition String/Function Type of transition equation... (defaults to "easeoutexpo") + * @param .onStart Function Event called when tween starts + * @param .onUpdate Function Event called when tween updates + * @param .onComplete Function Event called when tween ends + * @param .waitFrames Boolean Whether to wait (or not) one frame for each call + * @return true if the tween was successfully added, false if otherwise. + */ + public static function addCaller (p_scopes:Object = null, p_parameters:Object = null):Boolean { + if (!Boolean(p_scopes)) return false; + + var i:Number; + + var rScopes:Array; // List of objects to tween + if (p_scopes is Array) { + // The first argument is an array + rScopes = p_scopes.concat(); + } else { + // The first argument(s) is(are) object(s) + rScopes = [p_scopes]; + } + + var p_obj:Object = p_parameters; + + // Creates the main engine if it isn't active + if (!_inited) init(); + if (!_engineExists || !Boolean(__tweener_controller__)) startEngine(); // Quick fix for Flash not resetting the vars on double ctrl+enter... + + // Creates a "safer", more strict tweening object + var rTime:Number = (isNaN(p_obj.time) ? 0 : p_obj.time); // Real time + var rDelay:Number = (isNaN(p_obj.delay) ? 0 : p_obj.delay); // Real delay + + var rTransition:Function; // Real transition + if (typeof p_obj.transition == "string") { + // String parameter, transition names + var trans:String = p_obj.transition.toLowerCase(); + rTransition = _transitionList[trans]; + } else { + // Proper transition function + rTransition = p_obj.transition; + } + if (!Boolean(rTransition)) rTransition = _transitionList["easeoutexpo"]; + + var nTween:TweenListObj; + var myT:Number; + for (i = 0; i < rScopes.length; i++) { + + if (p_obj.useFrames == true) { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTimeFrame + (rDelay / _timeScale), + /* timeComplete */ _currentTimeFrame + ((rDelay + rTime) / _timeScale), + /* useFrames */ true, + /* transition */ rTransition, + p_obj.transitionParams + ); + } else { + nTween = new TweenListObj( + /* scope */ rScopes[i], + /* timeStart */ _currentTime + ((rDelay * 1000) / _timeScale), + /* timeComplete */ _currentTime + (((rDelay * 1000) + (rTime * 1000)) / _timeScale), + /* useFrames */ false, + /* transition */ rTransition, + p_obj.transitionParams + ); + } + + nTween.properties = null; + nTween.onStart = p_obj.onStart; + nTween.onUpdate = p_obj.onUpdate; + nTween.onComplete = p_obj.onComplete; + nTween.onOverwrite = p_obj.onOverwrite; + nTween.onStartParams = p_obj.onStartParams; + nTween.onUpdateParams = p_obj.onUpdateParams; + nTween.onCompleteParams = p_obj.onCompleteParams; + nTween.onOverwriteParams = p_obj.onOverwriteParams; + nTween.onStartScope = p_obj.onStartScope; + nTween.onUpdateScope = p_obj.onUpdateScope; + nTween.onCompleteScope = p_obj.onCompleteScope; + nTween.onOverwriteScope = p_obj.onOverwriteScope; + nTween.onErrorScope = p_obj.onErrorScope; + nTween.isCaller = true; + nTween.count = p_obj.count; + nTween.waitFrames = p_obj.waitFrames; + + // And finally adds it to the list + _tweenList.push(nTween); + + // Immediate update and removal if it's an immediate tween -- if not deleted, it executes at the end of this frame execution + if (rTime == 0 && rDelay == 0) { + myT = _tweenList.length-1; + updateTweenByIndex(myT); + removeTweenByIndex(myT); + } + } + + return true; + } + + /** + * Remove an specified tweening of a specified object the tweening list, if it conflicts with the given time. + * + * @param p_scope Object List of objects affected + * @param p_properties Object List of properties affected (PropertyInfoObj instances) + * @param p_timeStart Number Time when the new tween starts + * @param p_timeComplete Number Time when the new tween ends + * @return Boolean Whether or not it actually deleted something + */ + public static function removeTweensByTime (p_scope:Object, p_properties:Object, p_timeStart:Number, p_timeComplete:Number):Boolean { + var removed:Boolean = false; + var removedLocally:Boolean; + + var i:uint; + var tl:uint = _tweenList.length; + var pName:String; + + for (i = 0; i < tl; i++) { + if (Boolean(_tweenList[i]) && p_scope == _tweenList[i].scope) { + // Same object... + if (p_timeComplete > _tweenList[i].timeStart && p_timeStart < _tweenList[i].timeComplete) { + // New time should override the old one... + removedLocally = false; + for (pName in _tweenList[i].properties) { + if (Boolean(p_properties[pName])) { + // Same object, same property + // Finally, remove this old tweening and use the new one + if (Boolean(_tweenList[i].onOverwrite)) { + var eventScope:Object = Boolean(_tweenList[i].onOverwriteScope) ? _tweenList[i].onOverwriteScope : _tweenList[i].scope; + try { + _tweenList[i].onOverwrite.apply(eventScope, _tweenList[i].onOverwriteParams); + } catch(e:Error) { + handleError(_tweenList[i], e, "onOverwrite"); + } + } + _tweenList[i].properties[pName] = undefined; + delete _tweenList[i].properties[pName]; + removedLocally = true; + removed = true; + } + } + if (removedLocally) { + // Verify if this can be deleted + if (AuxFunctions.getObjectLength(_tweenList[i].properties) == 0) removeTweenByIndex(i); + } + } + } + } + + return removed; + } + + /* + public static function removeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(removeTweenByIndex, p_scope, properties); + } + */ + + /** + * Remove tweenings from a given object from the tweening list. + * + * @param p_tween Object Object that must have its tweens removed + * @param (2nd-last params) Object Property(ies) that must be removed + * @return Boolean Whether or not it successfully removed this tweening + */ + public static function removeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1){ + if (_specialPropertySplitterList[args[i]]){ + //special property, get splitter array first + var sps:SpecialPropertySplitter = _specialPropertySplitterList[args[i]]; + var specialProps:Array = sps.splitValues(p_scope, null); + for (var j:uint = 0; jtrue if it successfully removed any tweening, false if otherwise. + */ + public static function removeAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var removed:Boolean = false; + var i:uint; + for (i = 0; i<_tweenList.length; i++) { + removeTweenByIndex(i); + removed = true; + } + return removed; + } + + /** + * Pause tweenings for a given object. + * + * @param p_scope Object that must have its tweens paused + * @param (2nd-last params) Property(ies) that must be paused + * @return true if it successfully paused any tweening, false if otherwise. + */ + public static function pauseTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(pauseTweenByIndex, p_scope, properties); + } + + /** + * Pause all tweenings on the engine. + * + * @return true if it successfully paused any tweening, false if otherwise. + * @see #resumeAllTweens() + */ + public static function pauseAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var paused:Boolean = false; + var i:uint; + for (i = 0; i < _tweenList.length; i++) { + pauseTweenByIndex(i); + paused = true; + } + return paused; + } + + /** + * Resume tweenings from a given object. + * + * @param p_scope Object Object that must have its tweens resumed + * @param (2nd-last params) Object Property(ies) that must be resumed + * @return Boolean Whether or not it successfully resumed something + */ + public static function resumeTweens (p_scope:Object, ...args):Boolean { + // Create the property list + var properties:Array = new Array(); + var i:uint; + for (i = 0; i < args.length; i++) { + if (typeof(args[i]) == "string" && properties.indexOf(args[i]) == -1) properties.push(args[i]); + } + // Call the affect function on the specified properties + return affectTweens(resumeTweenByIndex, p_scope, properties); + } + + /** + * Resume all tweenings on the engine. + * + * @return true if it successfully resumed any tweening, false if otherwise. + * @see #pauseAllTweens() + */ + public static function resumeAllTweens ():Boolean { + if (!Boolean(_tweenList)) return false; + var resumed:Boolean = false; + var i:uint; + for (i = 0; i < _tweenList.length; i++) { + resumeTweenByIndex(i); + resumed = true; + } + return resumed; + } + + /** + * Do some generic action on specific tweenings (pause, resume, remove, more?) + * + * @param p_function Function Function to run on the tweenings that match + * @param p_scope Object Object that must have its tweens affected by the function + * @param p_properties Array Array of strings that must be affected + * @return Boolean Whether or not it successfully affected something + */ + private static function affectTweens (p_affectFunction:Function, p_scope:Object, p_properties:Array):Boolean { + var affected:Boolean = false; + var i:uint; + + if (!Boolean(_tweenList)) return false; + + for (i = 0; i < _tweenList.length; i++) { + if (_tweenList[i] && _tweenList[i].scope == p_scope) { + if (p_properties.length == 0) { + // Can affect everything + p_affectFunction(i); + affected = true; + } else { + // Must check whether this tween must have specific properties affected + var affectedProperties:Array = new Array(); + var j:uint; + for (j = 0; j < p_properties.length; j++) { + if (Boolean(_tweenList[i].properties[p_properties[j]])) { + affectedProperties.push(p_properties[j]); + } + } + if (affectedProperties.length > 0) { + // This tween has some properties that need to be affected + var objectProperties:uint = AuxFunctions.getObjectLength(_tweenList[i].properties); + if (objectProperties == affectedProperties.length) { + // The list of properties is the same as all properties, so affect it all + p_affectFunction(i); + affected = true; + } else { + // The properties are mixed, so split the tween and affect only certain specific properties + var slicedTweenIndex:uint = splitTweens(i, affectedProperties); + p_affectFunction(slicedTweenIndex); + affected = true; + } + } + } + } + } + return affected; + } + + /** + * Splits a tweening in two + * + * @param p_tween Number Object that must have its tweens split + * @param p_properties Array Array of strings containing the list of properties that must be separated + * @return Number The index number of the new tween + */ + public static function splitTweens (p_tween:Number, p_properties:Array):uint { + // First, duplicates + var originalTween:TweenListObj = _tweenList[p_tween]; + var newTween:TweenListObj = originalTween.clone(false); + + // Now, removes tweenings where needed + var i:uint; + var pName:String; + + // Removes the specified properties from the old one + for (i = 0; i < p_properties.length; i++) { + pName = p_properties[i]; + if (Boolean(originalTween.properties[pName])) { + originalTween.properties[pName] = undefined; + delete originalTween.properties[pName]; + } + } + + // Removes the unspecified properties from the new one + var found:Boolean; + for (pName in newTween.properties) { + found = false; + for (i = 0; i < p_properties.length; i++) { + if (p_properties[i] == pName) { + found = true; + break; + } + } + if (!found) { + newTween.properties[pName] = undefined; + delete newTween.properties[pName]; + } + } + + // If there are empty property lists, a cleanup is done on the next updateTweens() cycle + _tweenList.push(newTween); + return (_tweenList.length - 1); + + } + + // ================================================================================================================================== + // ENGINE functions ----------------------------------------------------------------------------------------------------------------- + + /** + * Updates all existing tweenings. + * + * @return Boolean FALSE if no update was made because there's no tweening (even delayed ones) + */ + private static function updateTweens ():Boolean { + if (_tweenList.length == 0) return false; + var i:int; + for (i = 0; i < _tweenList.length; i++) { + // Looping throught each Tweening and updating the values accordingly + if (_tweenList[i] == undefined || !_tweenList[i].isPaused) { + if (!updateTweenByIndex(i)) removeTweenByIndex(i); + if (_tweenList[i] == null) { + removeTweenByIndex(i, true); + i--; + } + } + } + + return true; + } + + /** + * Remove a specific tweening from the tweening list. + * + * @param p_tween Number Index of the tween to be removed on the tweenings list + * @return Boolean Whether or not it successfully removed this tweening + */ + public static function removeTweenByIndex (i:Number, p_finalRemoval:Boolean = false):Boolean { + _tweenList[i] = null; + if (p_finalRemoval) _tweenList.splice(i, 1); + return true; + } + + /** + * Pauses a specific tween. + * + * @param p_tween Number Index of the tween to be paused + * @return Boolean Whether or not it successfully paused this tweening + */ + public static function pauseTweenByIndex (p_tween:Number):Boolean { + var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening + if (tTweening == null || tTweening.isPaused) return false; + tTweening.timePaused = getCurrentTweeningTime(tTweening); + tTweening.isPaused = true; + + return true; + } + + /** + * Resumes a specific tween. + * + * @param p_tween Number Index of the tween to be resumed + * @return Boolean Whether or not it successfully resumed this tweening + */ + public static function resumeTweenByIndex (p_tween:Number):Boolean { + var tTweening:TweenListObj = _tweenList[p_tween]; // Shortcut to this tweening + if (tTweening == null || !tTweening.isPaused) return false; + var cTime:Number = getCurrentTweeningTime(tTweening); + tTweening.timeStart += cTime - tTweening.timePaused; + tTweening.timeComplete += cTime - tTweening.timePaused; + tTweening.timePaused = undefined; + tTweening.isPaused = false; + + return true; + } + + /** + * Updates a specific tween. + * + * @param i Number Index (from the tween list) of the tween that should be updated + * @return Boolean FALSE if it's already finished and should be deleted, TRUE if otherwise + */ + private static function updateTweenByIndex (i:Number):Boolean { + + var tTweening:TweenListObj = _tweenList[i]; // Shortcut to this tweening + + if (tTweening == null || !Boolean(tTweening.scope)) return false; + + var isOver:Boolean = false; // Whether or not it's over the update time + var mustUpdate:Boolean; // Whether or not it should be updated (skipped if false) + + var nv:Number; // New value for each property + + var t:Number; // current time (frames, seconds) + var b:Number; // beginning value + var c:Number; // change in value + var d:Number; // duration (frames, seconds) + + var pName:String; // Property name, used in loops + var eventScope:Object; // Event scope, used to call functions + + // Shortcut stuff for speed + var tScope:Object; // Current scope + var cTime:Number = getCurrentTweeningTime(tTweening); + var tProperty:Object; // Property being checked + + if (cTime >= tTweening.timeStart) { + // Can already start + + tScope = tTweening.scope; + + if (tTweening.isCaller) { + // It's a 'caller' tween + if (!tTweening.hasStarted) { + if (Boolean(tTweening.onStart)) { + eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; + try { + tTweening.onStart.apply(eventScope, tTweening.onStartParams); + } catch(e2:Error) { + handleError(tTweening, e2, "onStart"); + } + } + tTweening.hasStarted = true; + } + do { + t = ((tTweening.timeComplete - tTweening.timeStart)/tTweening.count) * (tTweening.timesCalled+1); + b = tTweening.timeStart; + c = tTweening.timeComplete - tTweening.timeStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, b, c, d); + + if (cTime >= nv) { + if (Boolean(tTweening.onUpdate)) { + eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; + try { + tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); + } catch(e1:Error) { + handleError(tTweening, e1, "onUpdate"); + } + } + + tTweening.timesCalled++; + if (tTweening.timesCalled >= tTweening.count) { + isOver = true; + break; + } + if (tTweening.waitFrames) break; + } + + } while (cTime >= nv); + } else { + // It's a normal transition tween + + mustUpdate = tTweening.skipUpdates < 1 || !tTweening.skipUpdates || tTweening.updatesSkipped >= tTweening.skipUpdates; + + if (cTime >= tTweening.timeComplete) { + isOver = true; + mustUpdate = true; + } + + if (!tTweening.hasStarted) { + // First update, read all default values (for proper filter tweening) + if (Boolean(tTweening.onStart)) { + eventScope = Boolean(tTweening.onStartScope) ? tTweening.onStartScope : tScope; + try { + tTweening.onStart.apply(eventScope, tTweening.onStartParams); + } catch(e2:Error) { + handleError(tTweening, e2, "onStart"); + } + } + var pv:Number; + for (pName in tTweening.properties) { + if (tTweening.properties[pName].isSpecialProperty) { + // It's a special property, tunnel via the special property function + if (Boolean(_specialPropertyList[pName].preProcess)) { + tTweening.properties[pName].valueComplete = _specialPropertyList[pName].preProcess(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].originalValueComplete, tTweening.properties[pName].extra); + } + pv = _specialPropertyList[pName].getValue(tScope, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); + } else { + // Directly read property + pv = tScope[pName]; + } + tTweening.properties[pName].valueStart = isNaN(pv) ? tTweening.properties[pName].valueComplete : pv; + } + mustUpdate = true; + tTweening.hasStarted = true; + } + + if (mustUpdate) { + for (pName in tTweening.properties) { + tProperty = tTweening.properties[pName]; + + if (isOver) { + // Tweening time has finished, just set it to the final value + nv = tProperty.valueComplete; + } else { + if (tProperty.hasModifier) { + // Modified + t = cTime - tTweening.timeStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, 0, 1, d, tTweening.transitionParams); + nv = tProperty.modifierFunction(tProperty.valueStart, tProperty.valueComplete, nv, tProperty.modifierParameters); + } else { + // Normal update + t = cTime - tTweening.timeStart; + b = tProperty.valueStart; + c = tProperty.valueComplete - tProperty.valueStart; + d = tTweening.timeComplete - tTweening.timeStart; + nv = tTweening.transition(t, b, c, d, tTweening.transitionParams); + } + } + + if (tTweening.rounded) nv = Math.round(nv); + if (tProperty.isSpecialProperty) { + // It's a special property, tunnel via the special property method + _specialPropertyList[pName].setValue(tScope, nv, _specialPropertyList[pName].parameters, tTweening.properties[pName].extra); + } else { + // Directly set property + tScope[pName] = nv; + } + } + + tTweening.updatesSkipped = 0; + + if (Boolean(tTweening.onUpdate)) { + eventScope = Boolean(tTweening.onUpdateScope) ? tTweening.onUpdateScope : tScope; + try { + tTweening.onUpdate.apply(eventScope, tTweening.onUpdateParams); + } catch(e3:Error) { + handleError(tTweening, e3, "onUpdate"); + } + } + } else { + tTweening.updatesSkipped++; + } + } + + if (isOver && Boolean(tTweening.onComplete)) { + eventScope = Boolean(tTweening.onCompleteScope) ? tTweening.onCompleteScope : tScope; + try { + tTweening.onComplete.apply(eventScope, tTweening.onCompleteParams); + } catch(e4:Error) { + handleError(tTweening, e4, "onComplete"); + } + } + + return (!isOver); + } + + // On delay, hasn't started, so returns true + return (true); + + } + + /** + * Initiates the Tweener--should only be ran once. + */ + public static function init(...rest):void { + _inited = true; + + // Registers all default equations + _transitionList = new Object(); + Equations.init(); + + // Registers all default special properties + _specialPropertyList = new Object(); + _specialPropertyModifierList = new Object(); + _specialPropertySplitterList = new Object(); + } + + /** + * Adds a new function to the available transition list "shortcuts". + * + * @param p_name String Shorthand transition name + * @param p_function Function The proper equation function + */ + public static function registerTransition(p_name:String, p_function:Function): void { + if (!_inited) init(); + _transitionList[p_name] = p_function; + } + + /** + * Adds a new special property to the available special property list. + * + * @param p_name Name of the "special" property. + * @param p_getFunction Function that gets the value. + * @param p_setFunction Function that sets the value. + */ + public static function registerSpecialProperty(p_name:String, p_getFunction:Function, p_setFunction:Function, p_parameters:Array = null, p_preProcessFunction:Function = null): void { + if (!_inited) init(); + var sp:SpecialProperty = new SpecialProperty(p_getFunction, p_setFunction, p_parameters, p_preProcessFunction); + _specialPropertyList[p_name] = sp; + } + + /** + * Adds a new special property modifier to the available modifier list. + * + * @param p_name Name of the "special" property modifier. + * @param p_modifyFunction Function that modifies the value. + * @param p_getFunction Function that gets the value. + */ + public static function registerSpecialPropertyModifier(p_name:String, p_modifyFunction:Function, p_getFunction:Function): void { + if (!_inited) init(); + var spm:SpecialPropertyModifier = new SpecialPropertyModifier(p_modifyFunction, p_getFunction); + _specialPropertyModifierList[p_name] = spm; + } + + /** + * Adds a new special property splitter to the available splitter list. + * + * @param p_name Name of the "special" property splitter. + * @param p_splitFunction Function that splits the value. + */ + public static function registerSpecialPropertySplitter(p_name:String, p_splitFunction:Function, p_parameters:Array = null): void { + if (!_inited) init(); + var sps:SpecialPropertySplitter = new SpecialPropertySplitter(p_splitFunction, p_parameters); + _specialPropertySplitterList[p_name] = sps; + } + + /** + * Starts the Tweener class engine. It is supposed to be running every time a tween exists. + */ + private static function startEngine():void { + _engineExists = true; + _tweenList = new Array(); + + __tweener_controller__ = new MovieClip(); + __tweener_controller__.addEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); + + _currentTimeFrame = 0; + updateTime(); + } + + /** + * Stops the Tweener class engine. + */ + private static function stopEngine():void { + _engineExists = false; + _tweenList = null; + _currentTime = 0; + _currentTimeFrame = 0; + __tweener_controller__.removeEventListener(Event.ENTER_FRAME, Tweener.onEnterFrame); + __tweener_controller__ = null; + } + + /** + * Updates the time to enforce time grid-based updates. + */ + public static function updateTime():void { + _currentTime = getTimer(); + } + + /** + * Updates the current frame count + */ + public static function updateFrame():void { + _currentTimeFrame++; + } + + /** + * Ran once every frame. It's the main engine; updates all existing tweenings. + */ + public static function onEnterFrame(e:Event):void { + updateTime(); + updateFrame(); + var hasUpdated:Boolean = false; + hasUpdated = updateTweens(); + if (!hasUpdated) stopEngine(); // There's no tweening to update or wait, so it's better to stop the engine + } + + /** + * Sets the new time scale. + * + * @param p_time Number New time scale (0.5 = slow, 1 = normal, 2 = 2x fast forward, etc) + */ + public static function setTimeScale(p_time:Number):void { + var i:Number; + var cTime:Number; + + if (isNaN(p_time)) p_time = 1; + if (p_time < 0.00001) p_time = 0.00001; + if (p_time != _timeScale) { + if (_tweenList != null) { + // Multiplies all existing tween times accordingly + for (i = 0; i<_tweenList.length; i++) { + cTime = getCurrentTweeningTime(_tweenList[i]); + _tweenList[i].timeStart = cTime - ((cTime - _tweenList[i].timeStart) * _timeScale / p_time); + _tweenList[i].timeComplete = cTime - ((cTime - _tweenList[i].timeComplete) * _timeScale / p_time); + if (_tweenList[i].timePaused != undefined) _tweenList[i].timePaused = cTime - ((cTime - _tweenList[i].timePaused) * _timeScale / p_time); + } + } + // Sets the new timescale value (for new tweenings) + _timeScale = p_time; + } + } + + + // ================================================================================================================================== + // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- + + /** + * Finds whether or not an object has any tweening. + * + * @param p_scope Target object. + * @return true if there's a tweening occuring on this object (paused, delayed, or active), false if otherwise. + */ + public static function isTweening (p_scope:Object):Boolean { + if (!Boolean(_tweenList)) return false; + var i:uint; + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + return true; + } + } + return false; + } + + /** + * Returns an array containing a list of the properties being tweened for this object. + * + * @param p_scope Target object. + * @return Total number of properties being tweened (including delayed or paused tweens). + */ + public static function getTweens (p_scope:Object):Array { + if (!Boolean(_tweenList)) return []; + var i:uint; + var pName:String; + var tList:Array = new Array(); + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + for (pName in _tweenList[i].properties) tList.push(pName); + } + } + return tList; + } + + /** + * Returns the number of properties being tweened for a given object. + * + * @param p_scope Target object. + * @return Total number of properties being tweened (including delayed or paused tweens). + */ + public static function getTweenCount (p_scope:Object):Number { + if (!Boolean(_tweenList)) return 0; + var i:uint; + var c:Number = 0; + + for (i = 0; i<_tweenList.length; i++) { + if (Boolean(_tweenList[i]) && _tweenList[i].scope == p_scope) { + c += AuxFunctions.getObjectLength(_tweenList[i].properties); + } + } + return c; + } + + + /* Handles errors when Tweener executes any callbacks (onStart, onUpdate, etc) + * If the TweenListObj specifies an onError callback it well get called, passing the Error object and the current scope as parameters. If no onError callback is specified, it will trace a stackTrace. + */ + private static function handleError(pTweening : TweenListObj, pError : Error, pCallBackName : String) : void{ + // do we have an error handler? + if (Boolean(pTweening.onError) && (pTweening.onError is Function)){ + // yup, there's a handler. Wrap this in a try catch in case the onError throws an error itself. + var eventScope:Object = Boolean(pTweening.onErrorScope) ? pTweening.onErrorScope : pTweening.scope; + try { + pTweening.onError.apply(eventScope, [pTweening.scope, pError]); + } catch (metaError : Error){ + printError(String(pTweening.scope) + " raised an error while executing the 'onError' handler. Original error:\n " + pError.getStackTrace() + "\nonError error: " + metaError.getStackTrace()); + } + } else { + // no handler, simply trace the stack trace: + if (!Boolean(pTweening.onError)){ + printError(String(pTweening.scope) + " raised an error while executing the '" + pCallBackName + "'handler. \n" + pError.getStackTrace() ); + } + } + } + + /** + * Get the current tweening time (no matter if it uses frames or time as basis), given a specific tweening + * + * @param p_tweening TweenListObj Tween information + */ + public static function getCurrentTweeningTime(p_tweening:Object):Number { + return p_tweening.useFrames ? _currentTimeFrame : _currentTime; + } + + /** + * Return the current tweener version + * + * @return String The number of the current Tweener version + */ + public static function getVersion():String { + return "AS3 1.33.74"; + } + + + // ================================================================================================================================== + // DEBUG functions ------------------------------------------------------------------------------------------------------------------ + + /** + * Output an error message + * + * @param p_message String The error message to output + */ + public static function printError(p_message:String): void { + // + trace("## [Tweener] Error: "+p_message); + } + + } +} diff --git a/docviewerflex/src/caurina/transitions/properties/ColorShortcuts.as b/docviewerflex/src/caurina/transitions/properties/ColorShortcuts.as index 01e7d74..4c1c614 100644 --- a/docviewerflex/src/caurina/transitions/properties/ColorShortcuts.as +++ b/docviewerflex/src/caurina/transitions/properties/ColorShortcuts.as @@ -1,471 +1,471 @@ -package caurina.transitions.properties { - - /** - * properties.ColorShortcuts - * List of default special color properties (normal and splitter properties) for the Tweener class - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import flash.geom.ColorTransform; - import flash.filters.ColorMatrixFilter; - - import caurina.transitions.Tweener; - import caurina.transitions.AuxFunctions; - - public class ColorShortcuts { - - // Sources: - // http://www.graficaobscura.com/matrix/index.html - // And mario Klingemann's ColorMatrix class as mentioned on the credits: - // http://www.quasimondo.com/archives/000565.php - - // Defines luminance using sRGB luminance - private static var LUMINANCE_R:Number = 0.212671; - private static var LUMINANCE_G:Number = 0.715160; - private static var LUMINANCE_B:Number = 0.072169; - - /** - * There's no constructor. - */ - public function ColorShortcuts () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init(): void { - - // Normal properties - Tweener.registerSpecialProperty("_color_ra", _oldColor_property_get, _oldColor_property_set, ["redMultiplier"]); - Tweener.registerSpecialProperty("_color_rb", _color_property_get, _color_property_set, ["redOffset"]); - Tweener.registerSpecialProperty("_color_ga", _oldColor_property_get, _oldColor_property_set, ["greenMultiplier"]); - Tweener.registerSpecialProperty("_color_gb", _color_property_get, _color_property_set, ["greenOffset"]); - Tweener.registerSpecialProperty("_color_ba", _oldColor_property_get, _oldColor_property_set, ["blueMultiplier"]); - Tweener.registerSpecialProperty("_color_bb", _color_property_get, _color_property_set, ["blueOffset"]); - Tweener.registerSpecialProperty("_color_aa", _oldColor_property_get, _oldColor_property_set, ["alphaMultiplier"]); - Tweener.registerSpecialProperty("_color_ab", _color_property_get, _color_property_set, ["alphaOffset"]); - - Tweener.registerSpecialProperty("_color_redMultiplier", _color_property_get, _color_property_set, ["redMultiplier"]); - Tweener.registerSpecialProperty("_color_redOffset", _color_property_get, _color_property_set, ["redOffset"]); - Tweener.registerSpecialProperty("_color_greenMultiplier", _color_property_get, _color_property_set, ["greenMultiplier"]); - Tweener.registerSpecialProperty("_color_greenOffset", _color_property_get, _color_property_set, ["greenOffset"]); - Tweener.registerSpecialProperty("_color_blueMultiplier", _color_property_get, _color_property_set, ["blueMultiplier"]); - Tweener.registerSpecialProperty("_color_blueOffset", _color_property_get, _color_property_set, ["blueOffset"]); - Tweener.registerSpecialProperty("_color_alphaMultiplier", _color_property_get, _color_property_set, ["alphaMultiplier"]); - Tweener.registerSpecialProperty("_color_alphaOffset", _color_property_get, _color_property_set, ["alphaOffset"]); - - // Normal splitter properties - Tweener.registerSpecialPropertySplitter("_color", _color_splitter); - Tweener.registerSpecialPropertySplitter("_colorTransform", _colorTransform_splitter); - - // Color changes that depend on the ColorMatrixFilter - Tweener.registerSpecialProperty("_brightness", _brightness_get, _brightness_set, [false]); - Tweener.registerSpecialProperty("_tintBrightness", _brightness_get, _brightness_set, [true]); - Tweener.registerSpecialProperty("_contrast", _contrast_get, _contrast_set); - Tweener.registerSpecialProperty("_hue", _hue_get, _hue_set); - Tweener.registerSpecialProperty("_saturation", _saturation_get, _saturation_set, [false]); - Tweener.registerSpecialProperty("_dumbSaturation", _saturation_get, _saturation_set, [true]); - - } - - - // ================================================================================================================================== - // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _color - - /** - * Splits the _color parameter into specific color variables - * - * @param p_value Number The original _color value - * @return Array An array containing the .name and .value of all new properties - */ - public static function _color_splitter (p_value:*, p_parameters:Array):Array { - var nArray:Array = new Array(); - if (p_value == null) { - // No parameter passed, so just resets the color - nArray.push({name:"_color_redMultiplier", value:1}); - nArray.push({name:"_color_redOffset", value:0}); - nArray.push({name:"_color_greenMultiplier", value:1}); - nArray.push({name:"_color_greenOffset", value:0}); - nArray.push({name:"_color_blueMultiplier", value:1}); - nArray.push({name:"_color_blueOffset", value:0}); - } else { - // A color tinting is passed, so converts it to the object values - nArray.push({name:"_color_redMultiplier", value:0}); - nArray.push({name:"_color_redOffset", value:AuxFunctions.numberToR(p_value)}); - nArray.push({name:"_color_greenMultiplier", value:0}); - nArray.push({name:"_color_greenOffset", value:AuxFunctions.numberToG(p_value)}); - nArray.push({name:"_color_blueMultiplier", value:0}); - nArray.push({name:"_color_blueOffset", value:AuxFunctions.numberToB(p_value)}); - } - return nArray; - } - - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _colorTransform - - /** - * Splits the _colorTransform parameter into specific color variables - * - * @param p_value Number The original _colorTransform value - * @return Array An array containing the .name and .value of all new properties - */ - public static function _colorTransform_splitter (p_value:Object, p_parameters:Array):Array { - var nArray:Array = new Array(); - if (p_value == null) { - // No parameter passed, so just resets the color - nArray.push({name:"_color_redMultiplier", value:1}); - nArray.push({name:"_color_redOffset", value:0}); - nArray.push({name:"_color_greenMultiplier", value:1}); - nArray.push({name:"_color_greenOffset", value:0}); - nArray.push({name:"_color_blueMultiplier", value:1}); - nArray.push({name:"_color_blueOffset", value:0}); - } else { - // A color transformation object is passed, so converts it to the object values - nArray.push({name:"_color_redMultiplier", value:p_value.redMultiplier}); - nArray.push({name:"_color_redOffset", value:p_value.redOffset}); - nArray.push({name:"_color_blueMultiplier", value:p_value.blueMultiplier}); - nArray.push({name:"_color_blueOffset", value:p_value.blueOffset}); - nArray.push({name:"_color_greenMultiplier", value:p_value.greenMultiplier}); - nArray.push({name:"_color_greenOffset", value:p_value.greenOffset}); - nArray.push({name:"_color_alphaMultiplier", value:p_value.alphaMultiplier}); - nArray.push({name:"_color_alphaOffset", value:p_value.alphaOffset}); - } - return nArray; - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _color_* - - /** - * _color_* - * Generic function for the ra/rb/etc components of the deprecated colorTransform object - */ - public static function _oldColor_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.transform.colorTransform[p_parameters[0]] * 100; - } - public static function _oldColor_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - var tf:ColorTransform = p_obj.transform.colorTransform; - tf[p_parameters[0]] = p_value / 100; - p_obj.transform.colorTransform = tf; - } - - /** - * _color_* - * Generic function for the redMultiplier/redOffset/etc components of the new colorTransform - */ - public static function _color_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.transform.colorTransform[p_parameters[0]]; - } - public static function _color_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - var cfm:ColorTransform = p_obj.transform.colorTransform; - cfm[p_parameters[0]] = p_value; - p_obj.transform.colorTransform = cfm; - } - - // ---------------------------------------------------------------------------------------------------------------------------------- - // Special coloring - - /** - * _brightness - * Brightness of an object: -1 -> [0] -> +1 - */ - public static function _brightness_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - - var isTint:Boolean = p_parameters[0]; - - /* - // Using ColorMatrix: - - var mtx:Array = getObjectMatrix(p_obj); - - var mc:Number = 1 - ((mtx[0] + mtx[6] + mtx[12]) / 3); // Brightness as determined by the main channels - var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3; // Brightness as determined by the offset channels - */ - - var cfm:ColorTransform = p_obj.transform.colorTransform; - var mc:Number = 1 - ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3); // Brightness as determined by the main channels - var co:Number = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3; - - if (isTint) { - // Tint style - //return (mc+(co/255))/2; - return co > 0 ? co / 255 : -mc; - } else { - // Native, Flash "Adjust Color" and Photoshop style - return co / 100; - } - } - public static function _brightness_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - //var mtx:Array = getObjectMatrix(p_obj); - - var isTint:Boolean = p_parameters[0]; - - var mc:Number; // Main channel - var co:Number; // Channel offset - - if (isTint) { - // Tint style - mc = 1 - Math.abs(p_value); - co = p_value > 0 ? Math.round(p_value*255) : 0; - } else { - // Native, Flash "Adjust Color" and Photoshop style - mc = 1; - co = Math.round(p_value*100); - } - - /* - // Using ColorMatrix: - var mtx:Array = [ - mc, cc, cc, cc, co, - cc, mc, cc, cc, co, - cc, cc, mc, cc, co, - 0, 0, 0, 1, 0 - ]; - setObjectMatrix(p_obj, mtx); - */ - var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); - p_obj.transform.colorTransform = cfm; - } - - /** - * _saturation - * Saturation of an object: 0 -> [1] -> 2 - */ - public static function _saturation_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - - var mtx:Array = getObjectMatrix(p_obj); - - var isDumb:Boolean = p_parameters[0]; - var rl:Number = isDumb ? 1/3 : LUMINANCE_R; - var gl:Number = isDumb ? 1/3 : LUMINANCE_G; - var bl:Number = isDumb ? 1/3 : LUMINANCE_B; - - var mc:Number = ((mtx[0]-rl)/(1-rl) + (mtx[6]-gl)/(1-gl) + (mtx[12]-bl)/(1-bl)) / 3; // Color saturation as determined by the main channels - var cc:Number = 1 - ((mtx[1]/gl + mtx[2]/bl + mtx[5]/rl + mtx[7]/bl + mtx[10]/rl + mtx[11]/gl) / 6); // Color saturation as determined by the other channels - return (mc + cc) / 2; - } - public static function _saturation_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - - var isDumb:Boolean = p_parameters[0]; - var rl:Number = isDumb ? 1/3 : LUMINANCE_R; - var gl:Number = isDumb ? 1/3 : LUMINANCE_G; - var bl:Number = isDumb ? 1/3 : LUMINANCE_B; - - var sf:Number = p_value; - var nf:Number = 1-sf; - var nr:Number = rl * nf; - var ng:Number = gl * nf; - var nb:Number = bl * nf; - - var mtx:Array = [ - nr+sf, ng, nb, 0, 0, - nr, ng+sf, nb, 0, 0, - nr, ng, nb+sf, 0, 0, - 0, 0, 0, 1, 0 - ]; - setObjectMatrix(p_obj, mtx); - } - - /** - * _contrast - * Contrast of an object: -1 -> [0] -> +1 - */ - public static function _contrast_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - - /* - // Using ColorMatrix: - var mtx:Array = getObjectMatrix(p_obj); - - var mc:Number = ((mtx[0] + mtx[6] + mtx[12]) / 3) - 1; // Contrast as determined by the main channels - var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3 / -128; // Contrast as determined by the offset channel - */ - var cfm:ColorTransform = p_obj.transform.colorTransform; - var mc:Number; // Contrast as determined by the main channels - var co:Number; // Contrast as determined by the offset channel - mc = ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3) - 1; - co = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3 / -128; - /* - if (cfm.ra < 100) { - // Low contrast - mc = ((cfm.ra + cfm.ga + cfm.ba) / 300) - 1; - co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -128; - } else { - // High contrast - mc = (((cfm.ra + cfm.ga + cfm.ba) / 300) - 1) / 37; - co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -3840; - } - */ - - return (mc+co)/2; - } - public static function _contrast_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - - var mc:Number; // Main channel - var co:Number; // Channel offset - mc = p_value + 1; - co = Math.round(p_value*-128); - - /* - if (p_value < 0) { - // Low contrast - mc = p_value + 1; - co = Math.round(p_value*-128); - } else { - // High contrast - mc = (p_value * 37) + 1; - co = Math.round(p_value*-3840); - } - */ - - // Flash: * 8, * -512 - - /* - // Using ColorMatrix: - var mtx:Array = [ - mc, 0, 0, 0, co, - 0, mc, 0, 0, co, - 0, 0, mc, 0, co, - 0, 0, 0, 1, 0 - ]; - setObjectMatrix(p_obj, mtx); - */ - var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); - p_obj.transform.colorTransform = cfm; - } - - /** - * _hue - * Hue of an object: -180 -> [0] -> 180 - */ - public static function _hue_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - - var mtx:Array = getObjectMatrix(p_obj); - - // Find the current Hue based on a given matrix. - // This is a kind of a brute force method by sucessive division until a close enough angle is found. - // Reverse-engineering the hue equation would be is a better choice, but it's hard to find material - // on the correct calculation employed by Flash. - // This code has to run only once (before the tween starts), so it's good enough. - - var hues:Array = []; - var i:Number; - - hues[0] = {angle:-179.9, matrix:getHueMatrix(-179.9)}; - hues[1] = {angle:180, matrix:getHueMatrix(180)}; - - for (i = 0; i < hues.length; i++) { - hues[i].distance = getHueDistance(mtx, hues[i].matrix); - } - - var maxTries:Number = 15; // Number o maximum divisions until the hue is found - var angleToSplit:Number; - - for (i = 0; i < maxTries; i++) { - // Find the nearest angle - if (hues[0].distance < hues[1].distance) { - // First is closer - angleToSplit = 1; - } else { - // Second is closer - angleToSplit = 0; - } - hues[angleToSplit].angle = (hues[0].angle + hues[1].angle)/2; - hues[angleToSplit].matrix = getHueMatrix(hues[angleToSplit].angle) - hues[angleToSplit].distance = getHueDistance(mtx, hues[angleToSplit].matrix); - } - - return hues[angleToSplit].angle; - } - - public static function _hue_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - setObjectMatrix(p_obj, getHueMatrix(p_value)); - } - - public static function getHueDistance (mtx1:Array, mtx2:Array): Number { - return (Math.abs(mtx1[0] - mtx2[0]) + Math.abs(mtx1[1] - mtx2[1]) + Math.abs(mtx1[2] - mtx2[2])); - } - - public static function getHueMatrix (hue:Number): Array { - var ha:Number = hue * Math.PI/180; // Hue angle, to radians - - var rl:Number = LUMINANCE_R; - var gl:Number = LUMINANCE_G; - var bl:Number = LUMINANCE_B; - - var c:Number = Math.cos(ha); - var s:Number = Math.sin(ha); - - var mtx:Array = [ - (rl + (c * (1 - rl))) + (s * (-rl)), - (gl + (c * (-gl))) + (s * (-gl)), - (bl + (c * (-bl))) + (s * (1 - bl)), - 0, 0, - - (rl + (c * (-rl))) + (s * 0.143), - (gl + (c * (1 - gl))) + (s * 0.14), - (bl + (c * (-bl))) + (s * -0.283), - 0, 0, - - (rl + (c * (-rl))) + (s * (-(1 - rl))), - (gl + (c * (-gl))) + (s * gl), - (bl + (c * (1 - bl))) + (s * bl), - 0, 0, - - 0, 0, 0, 1, 0 - ]; - - return mtx; - } - - - // ================================================================================================================================== - // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- - - private static function getObjectMatrix(p_obj:Object): Array { - // Get the current color matrix of an object - for (var i:Number = 0; i < p_obj.filters.length; i++) { - if (p_obj.filters[i] is ColorMatrixFilter) { - return p_obj.filters[i].matrix.concat(); - } - } - return [ - 1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0 - ]; - } - - private static function setObjectMatrix(p_obj:Object, p_matrix:Array): void { - // Set the current color matrix of an object - var objFilters:Array = p_obj.filters.concat(); - var found:Boolean = false; - for (var i:Number = 0; i < objFilters.length; i++) { - if (objFilters[i] is ColorMatrixFilter) { - objFilters[i].matrix = p_matrix.concat(); - found = true; - } - } - if (!found) { - // Has to create a new color matrix filter - var cmtx:ColorMatrixFilter = new ColorMatrixFilter(p_matrix); - objFilters[objFilters.length] = cmtx; - } - p_obj.filters = objFilters; - } - - } - -} +package caurina.transitions.properties { + + /** + * properties.ColorShortcuts + * List of default special color properties (normal and splitter properties) for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.geom.ColorTransform; + import flash.filters.ColorMatrixFilter; + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + public class ColorShortcuts { + + // Sources: + // http://www.graficaobscura.com/matrix/index.html + // And mario Klingemann's ColorMatrix class as mentioned on the credits: + // http://www.quasimondo.com/archives/000565.php + + // Defines luminance using sRGB luminance + private static var LUMINANCE_R:Number = 0.212671; + private static var LUMINANCE_G:Number = 0.715160; + private static var LUMINANCE_B:Number = 0.072169; + + /** + * There's no constructor. + */ + public function ColorShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Normal properties + Tweener.registerSpecialProperty("_color_ra", _oldColor_property_get, _oldColor_property_set, ["redMultiplier"]); + Tweener.registerSpecialProperty("_color_rb", _color_property_get, _color_property_set, ["redOffset"]); + Tweener.registerSpecialProperty("_color_ga", _oldColor_property_get, _oldColor_property_set, ["greenMultiplier"]); + Tweener.registerSpecialProperty("_color_gb", _color_property_get, _color_property_set, ["greenOffset"]); + Tweener.registerSpecialProperty("_color_ba", _oldColor_property_get, _oldColor_property_set, ["blueMultiplier"]); + Tweener.registerSpecialProperty("_color_bb", _color_property_get, _color_property_set, ["blueOffset"]); + Tweener.registerSpecialProperty("_color_aa", _oldColor_property_get, _oldColor_property_set, ["alphaMultiplier"]); + Tweener.registerSpecialProperty("_color_ab", _color_property_get, _color_property_set, ["alphaOffset"]); + + Tweener.registerSpecialProperty("_color_redMultiplier", _color_property_get, _color_property_set, ["redMultiplier"]); + Tweener.registerSpecialProperty("_color_redOffset", _color_property_get, _color_property_set, ["redOffset"]); + Tweener.registerSpecialProperty("_color_greenMultiplier", _color_property_get, _color_property_set, ["greenMultiplier"]); + Tweener.registerSpecialProperty("_color_greenOffset", _color_property_get, _color_property_set, ["greenOffset"]); + Tweener.registerSpecialProperty("_color_blueMultiplier", _color_property_get, _color_property_set, ["blueMultiplier"]); + Tweener.registerSpecialProperty("_color_blueOffset", _color_property_get, _color_property_set, ["blueOffset"]); + Tweener.registerSpecialProperty("_color_alphaMultiplier", _color_property_get, _color_property_set, ["alphaMultiplier"]); + Tweener.registerSpecialProperty("_color_alphaOffset", _color_property_get, _color_property_set, ["alphaOffset"]); + + // Normal splitter properties + Tweener.registerSpecialPropertySplitter("_color", _color_splitter); + Tweener.registerSpecialPropertySplitter("_colorTransform", _colorTransform_splitter); + + // Color changes that depend on the ColorMatrixFilter + Tweener.registerSpecialProperty("_brightness", _brightness_get, _brightness_set, [false]); + Tweener.registerSpecialProperty("_tintBrightness", _brightness_get, _brightness_set, [true]); + Tweener.registerSpecialProperty("_contrast", _contrast_get, _contrast_set); + Tweener.registerSpecialProperty("_hue", _hue_get, _hue_set); + Tweener.registerSpecialProperty("_saturation", _saturation_get, _saturation_set, [false]); + Tweener.registerSpecialProperty("_dumbSaturation", _saturation_get, _saturation_set, [true]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _color + + /** + * Splits the _color parameter into specific color variables + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _color_splitter (p_value:*, p_parameters:Array):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so just resets the color + nArray.push({name:"_color_redMultiplier", value:1}); + nArray.push({name:"_color_redOffset", value:0}); + nArray.push({name:"_color_greenMultiplier", value:1}); + nArray.push({name:"_color_greenOffset", value:0}); + nArray.push({name:"_color_blueMultiplier", value:1}); + nArray.push({name:"_color_blueOffset", value:0}); + } else { + // A color tinting is passed, so converts it to the object values + nArray.push({name:"_color_redMultiplier", value:0}); + nArray.push({name:"_color_redOffset", value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:"_color_greenMultiplier", value:0}); + nArray.push({name:"_color_greenOffset", value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:"_color_blueMultiplier", value:0}); + nArray.push({name:"_color_blueOffset", value:AuxFunctions.numberToB(p_value)}); + } + return nArray; + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _colorTransform + + /** + * Splits the _colorTransform parameter into specific color variables + * + * @param p_value Number The original _colorTransform value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _colorTransform_splitter (p_value:Object, p_parameters:Array):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so just resets the color + nArray.push({name:"_color_redMultiplier", value:1}); + nArray.push({name:"_color_redOffset", value:0}); + nArray.push({name:"_color_greenMultiplier", value:1}); + nArray.push({name:"_color_greenOffset", value:0}); + nArray.push({name:"_color_blueMultiplier", value:1}); + nArray.push({name:"_color_blueOffset", value:0}); + } else { + // A color transformation object is passed, so converts it to the object values + nArray.push({name:"_color_redMultiplier", value:p_value.redMultiplier}); + nArray.push({name:"_color_redOffset", value:p_value.redOffset}); + nArray.push({name:"_color_blueMultiplier", value:p_value.blueMultiplier}); + nArray.push({name:"_color_blueOffset", value:p_value.blueOffset}); + nArray.push({name:"_color_greenMultiplier", value:p_value.greenMultiplier}); + nArray.push({name:"_color_greenOffset", value:p_value.greenOffset}); + nArray.push({name:"_color_alphaMultiplier", value:p_value.alphaMultiplier}); + nArray.push({name:"_color_alphaOffset", value:p_value.alphaOffset}); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _color_* + + /** + * _color_* + * Generic function for the ra/rb/etc components of the deprecated colorTransform object + */ + public static function _oldColor_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.transform.colorTransform[p_parameters[0]] * 100; + } + public static function _oldColor_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var tf:ColorTransform = p_obj.transform.colorTransform; + tf[p_parameters[0]] = p_value / 100; + p_obj.transform.colorTransform = tf; + } + + /** + * _color_* + * Generic function for the redMultiplier/redOffset/etc components of the new colorTransform + */ + public static function _color_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.transform.colorTransform[p_parameters[0]]; + } + public static function _color_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var cfm:ColorTransform = p_obj.transform.colorTransform; + cfm[p_parameters[0]] = p_value; + p_obj.transform.colorTransform = cfm; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // Special coloring + + /** + * _brightness + * Brightness of an object: -1 -> [0] -> +1 + */ + public static function _brightness_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var isTint:Boolean = p_parameters[0]; + + /* + // Using ColorMatrix: + + var mtx:Array = getObjectMatrix(p_obj); + + var mc:Number = 1 - ((mtx[0] + mtx[6] + mtx[12]) / 3); // Brightness as determined by the main channels + var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3; // Brightness as determined by the offset channels + */ + + var cfm:ColorTransform = p_obj.transform.colorTransform; + var mc:Number = 1 - ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3); // Brightness as determined by the main channels + var co:Number = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3; + + if (isTint) { + // Tint style + //return (mc+(co/255))/2; + return co > 0 ? co / 255 : -mc; + } else { + // Native, Flash "Adjust Color" and Photoshop style + return co / 100; + } + } + public static function _brightness_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + //var mtx:Array = getObjectMatrix(p_obj); + + var isTint:Boolean = p_parameters[0]; + + var mc:Number; // Main channel + var co:Number; // Channel offset + + if (isTint) { + // Tint style + mc = 1 - Math.abs(p_value); + co = p_value > 0 ? Math.round(p_value*255) : 0; + } else { + // Native, Flash "Adjust Color" and Photoshop style + mc = 1; + co = Math.round(p_value*100); + } + + /* + // Using ColorMatrix: + var mtx:Array = [ + mc, cc, cc, cc, co, + cc, mc, cc, cc, co, + cc, cc, mc, cc, co, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + */ + var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); + p_obj.transform.colorTransform = cfm; + } + + /** + * _saturation + * Saturation of an object: 0 -> [1] -> 2 + */ + public static function _saturation_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var mtx:Array = getObjectMatrix(p_obj); + + var isDumb:Boolean = p_parameters[0]; + var rl:Number = isDumb ? 1/3 : LUMINANCE_R; + var gl:Number = isDumb ? 1/3 : LUMINANCE_G; + var bl:Number = isDumb ? 1/3 : LUMINANCE_B; + + var mc:Number = ((mtx[0]-rl)/(1-rl) + (mtx[6]-gl)/(1-gl) + (mtx[12]-bl)/(1-bl)) / 3; // Color saturation as determined by the main channels + var cc:Number = 1 - ((mtx[1]/gl + mtx[2]/bl + mtx[5]/rl + mtx[7]/bl + mtx[10]/rl + mtx[11]/gl) / 6); // Color saturation as determined by the other channels + return (mc + cc) / 2; + } + public static function _saturation_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + + var isDumb:Boolean = p_parameters[0]; + var rl:Number = isDumb ? 1/3 : LUMINANCE_R; + var gl:Number = isDumb ? 1/3 : LUMINANCE_G; + var bl:Number = isDumb ? 1/3 : LUMINANCE_B; + + var sf:Number = p_value; + var nf:Number = 1-sf; + var nr:Number = rl * nf; + var ng:Number = gl * nf; + var nb:Number = bl * nf; + + var mtx:Array = [ + nr+sf, ng, nb, 0, 0, + nr, ng+sf, nb, 0, 0, + nr, ng, nb+sf, 0, 0, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + } + + /** + * _contrast + * Contrast of an object: -1 -> [0] -> +1 + */ + public static function _contrast_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + /* + // Using ColorMatrix: + var mtx:Array = getObjectMatrix(p_obj); + + var mc:Number = ((mtx[0] + mtx[6] + mtx[12]) / 3) - 1; // Contrast as determined by the main channels + var co:Number = (mtx[4] + mtx[9] + mtx[14]) / 3 / -128; // Contrast as determined by the offset channel + */ + var cfm:ColorTransform = p_obj.transform.colorTransform; + var mc:Number; // Contrast as determined by the main channels + var co:Number; // Contrast as determined by the offset channel + mc = ((cfm.redMultiplier + cfm.greenMultiplier + cfm.blueMultiplier) / 3) - 1; + co = (cfm.redOffset + cfm.greenOffset + cfm.blueOffset) / 3 / -128; + /* + if (cfm.ra < 100) { + // Low contrast + mc = ((cfm.ra + cfm.ga + cfm.ba) / 300) - 1; + co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -128; + } else { + // High contrast + mc = (((cfm.ra + cfm.ga + cfm.ba) / 300) - 1) / 37; + co = (cfm.rb + cfm.gb + cfm.bb) / 3 / -3840; + } + */ + + return (mc+co)/2; + } + public static function _contrast_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + + var mc:Number; // Main channel + var co:Number; // Channel offset + mc = p_value + 1; + co = Math.round(p_value*-128); + + /* + if (p_value < 0) { + // Low contrast + mc = p_value + 1; + co = Math.round(p_value*-128); + } else { + // High contrast + mc = (p_value * 37) + 1; + co = Math.round(p_value*-3840); + } + */ + + // Flash: * 8, * -512 + + /* + // Using ColorMatrix: + var mtx:Array = [ + mc, 0, 0, 0, co, + 0, mc, 0, 0, co, + 0, 0, mc, 0, co, + 0, 0, 0, 1, 0 + ]; + setObjectMatrix(p_obj, mtx); + */ + var cfm:ColorTransform = new ColorTransform(mc, mc, mc, 1, co, co, co, 0); + p_obj.transform.colorTransform = cfm; + } + + /** + * _hue + * Hue of an object: -180 -> [0] -> 180 + */ + public static function _hue_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + + var mtx:Array = getObjectMatrix(p_obj); + + // Find the current Hue based on a given matrix. + // This is a kind of a brute force method by sucessive division until a close enough angle is found. + // Reverse-engineering the hue equation would be is a better choice, but it's hard to find material + // on the correct calculation employed by Flash. + // This code has to run only once (before the tween starts), so it's good enough. + + var hues:Array = []; + var i:Number; + + hues[0] = {angle:-179.9, matrix:getHueMatrix(-179.9)}; + hues[1] = {angle:180, matrix:getHueMatrix(180)}; + + for (i = 0; i < hues.length; i++) { + hues[i].distance = getHueDistance(mtx, hues[i].matrix); + } + + var maxTries:Number = 15; // Number o maximum divisions until the hue is found + var angleToSplit:Number; + + for (i = 0; i < maxTries; i++) { + // Find the nearest angle + if (hues[0].distance < hues[1].distance) { + // First is closer + angleToSplit = 1; + } else { + // Second is closer + angleToSplit = 0; + } + hues[angleToSplit].angle = (hues[0].angle + hues[1].angle)/2; + hues[angleToSplit].matrix = getHueMatrix(hues[angleToSplit].angle) + hues[angleToSplit].distance = getHueDistance(mtx, hues[angleToSplit].matrix); + } + + return hues[angleToSplit].angle; + } + + public static function _hue_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + setObjectMatrix(p_obj, getHueMatrix(p_value)); + } + + public static function getHueDistance (mtx1:Array, mtx2:Array): Number { + return (Math.abs(mtx1[0] - mtx2[0]) + Math.abs(mtx1[1] - mtx2[1]) + Math.abs(mtx1[2] - mtx2[2])); + } + + public static function getHueMatrix (hue:Number): Array { + var ha:Number = hue * Math.PI/180; // Hue angle, to radians + + var rl:Number = LUMINANCE_R; + var gl:Number = LUMINANCE_G; + var bl:Number = LUMINANCE_B; + + var c:Number = Math.cos(ha); + var s:Number = Math.sin(ha); + + var mtx:Array = [ + (rl + (c * (1 - rl))) + (s * (-rl)), + (gl + (c * (-gl))) + (s * (-gl)), + (bl + (c * (-bl))) + (s * (1 - bl)), + 0, 0, + + (rl + (c * (-rl))) + (s * 0.143), + (gl + (c * (1 - gl))) + (s * 0.14), + (bl + (c * (-bl))) + (s * -0.283), + 0, 0, + + (rl + (c * (-rl))) + (s * (-(1 - rl))), + (gl + (c * (-gl))) + (s * gl), + (bl + (c * (1 - bl))) + (s * bl), + 0, 0, + + 0, 0, 0, 1, 0 + ]; + + return mtx; + } + + + // ================================================================================================================================== + // AUXILIARY functions -------------------------------------------------------------------------------------------------------------- + + private static function getObjectMatrix(p_obj:Object): Array { + // Get the current color matrix of an object + for (var i:Number = 0; i < p_obj.filters.length; i++) { + if (p_obj.filters[i] is ColorMatrixFilter) { + return p_obj.filters[i].matrix.concat(); + } + } + return [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 + ]; + } + + private static function setObjectMatrix(p_obj:Object, p_matrix:Array): void { + // Set the current color matrix of an object + var objFilters:Array = p_obj.filters.concat(); + var found:Boolean = false; + for (var i:Number = 0; i < objFilters.length; i++) { + if (objFilters[i] is ColorMatrixFilter) { + objFilters[i].matrix = p_matrix.concat(); + found = true; + } + } + if (!found) { + // Has to create a new color matrix filter + var cmtx:ColorMatrixFilter = new ColorMatrixFilter(p_matrix); + objFilters[objFilters.length] = cmtx; + } + p_obj.filters = objFilters; + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/properties/CurveModifiers.as b/docviewerflex/src/caurina/transitions/properties/CurveModifiers.as index b004c1f..a5b96df 100644 --- a/docviewerflex/src/caurina/transitions/properties/CurveModifiers.as +++ b/docviewerflex/src/caurina/transitions/properties/CurveModifiers.as @@ -1,109 +1,109 @@ -package caurina.transitions.properties { - - /** - * properties.CurveModifiers - * List of default special properties modifiers for the Tweener class - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import caurina.transitions.Tweener; - - public class CurveModifiers { - - /** - * There's no constructor. - */ - public function CurveModifiers () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init(): void { - - // Bezier modifiers - Tweener.registerSpecialPropertyModifier("_bezier", _bezier_modifier, _bezier_get); - } - - - // ================================================================================================================================== - // SPECIAL PROPERTY MODIFIER functions ---------------------------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _bezier - - /** - * Given the parameter object passed to this special property, return an array listing the properties that should be modified, and their parameters - * - * @param p_obj Object Parameter passed to this property - * @return Array Array listing name and parameter of each property - */ - public static function _bezier_modifier (p_obj:*):Array { - var mList:Array = []; // List of properties to be modified - var pList:Array; // List of parameters passed, normalized as an array - if (p_obj is Array) { - // Complex - pList = p_obj; - } else { - pList = [p_obj]; - } - - var i:uint; - var istr:String; - var mListObj:Object = {}; // Object describing each property name and parameter - - for (i = 0; i < pList.length; i++) { - for (istr in pList[i]) { - if (mListObj[istr] == undefined) mListObj[istr] = []; - mListObj[istr].push(pList[i][istr]); - } - } - for (istr in mListObj) { - mList.push({name:istr, parameters:mListObj[istr]}); - } - return mList; - } - - /** - * Given tweening specifications (beging, end, t), applies the property parameter to it, returning new t - * - * @param b Number Beginning value of the property - * @param e Number Ending (desired) value of the property - * @param t Number Current t of this tweening (0-1), after applying the easing equation - * @param p Array Array of parameters passed to this specific property - * @return Number New t, with the p parameters applied to it - */ - public static function _bezier_get (b:Number, e:Number, t:Number, p:Array):Number { - // This is based on Robert Penner's code - if (p.length == 1) { - // Simple curve with just one bezier control point - return b + t*(2*(1-t)*(p[0]-b) + t*(e - b)); - } else { - // Array of bezier control points, must find the point between each pair of bezier points - var ip:uint = Math.floor(t * p.length); // Position on the bezier list - var it:Number = (t - (ip * (1 / p.length))) * p.length; // t inside this ip - var p1:Number, p2:Number; - if (ip == 0) { - // First part: belongs to the first control point, find second midpoint - p1 = b; - p2 = (p[0]+p[1])/2; - } else if (ip == p.length - 1) { - // Last part: belongs to the last control point, find first midpoint - p1 = (p[ip-1]+p[ip])/2; - p2 = e; - } else { - // Any middle part: find both midpoints - p1 = (p[ip-1]+p[ip])/2; - p2 = (p[ip]+p[ip+1])/2; - } - return p1+it*(2*(1-it)*(p[ip]-p1) + it*(p2 - p1)); - } - } - - } - -} +package caurina.transitions.properties { + + /** + * properties.CurveModifiers + * List of default special properties modifiers for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import caurina.transitions.Tweener; + + public class CurveModifiers { + + /** + * There's no constructor. + */ + public function CurveModifiers () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Bezier modifiers + Tweener.registerSpecialPropertyModifier("_bezier", _bezier_modifier, _bezier_get); + } + + + // ================================================================================================================================== + // SPECIAL PROPERTY MODIFIER functions ---------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _bezier + + /** + * Given the parameter object passed to this special property, return an array listing the properties that should be modified, and their parameters + * + * @param p_obj Object Parameter passed to this property + * @return Array Array listing name and parameter of each property + */ + public static function _bezier_modifier (p_obj:*):Array { + var mList:Array = []; // List of properties to be modified + var pList:Array; // List of parameters passed, normalized as an array + if (p_obj is Array) { + // Complex + pList = p_obj; + } else { + pList = [p_obj]; + } + + var i:uint; + var istr:String; + var mListObj:Object = {}; // Object describing each property name and parameter + + for (i = 0; i < pList.length; i++) { + for (istr in pList[i]) { + if (mListObj[istr] == undefined) mListObj[istr] = []; + mListObj[istr].push(pList[i][istr]); + } + } + for (istr in mListObj) { + mList.push({name:istr, parameters:mListObj[istr]}); + } + return mList; + } + + /** + * Given tweening specifications (beging, end, t), applies the property parameter to it, returning new t + * + * @param b Number Beginning value of the property + * @param e Number Ending (desired) value of the property + * @param t Number Current t of this tweening (0-1), after applying the easing equation + * @param p Array Array of parameters passed to this specific property + * @return Number New t, with the p parameters applied to it + */ + public static function _bezier_get (b:Number, e:Number, t:Number, p:Array):Number { + // This is based on Robert Penner's code + if (p.length == 1) { + // Simple curve with just one bezier control point + return b + t*(2*(1-t)*(p[0]-b) + t*(e - b)); + } else { + // Array of bezier control points, must find the point between each pair of bezier points + var ip:uint = Math.floor(t * p.length); // Position on the bezier list + var it:Number = (t - (ip * (1 / p.length))) * p.length; // t inside this ip + var p1:Number, p2:Number; + if (ip == 0) { + // First part: belongs to the first control point, find second midpoint + p1 = b; + p2 = (p[0]+p[1])/2; + } else if (ip == p.length - 1) { + // Last part: belongs to the last control point, find first midpoint + p1 = (p[ip-1]+p[ip])/2; + p2 = e; + } else { + // Any middle part: find both midpoints + p1 = (p[ip-1]+p[ip])/2; + p2 = (p[ip]+p[ip+1])/2; + } + return p1+it*(2*(1-it)*(p[ip]-p1) + it*(p2 - p1)); + } + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/properties/DisplayShortcuts.as b/docviewerflex/src/caurina/transitions/properties/DisplayShortcuts.as index fff4568..c169f86 100644 --- a/docviewerflex/src/caurina/transitions/properties/DisplayShortcuts.as +++ b/docviewerflex/src/caurina/transitions/properties/DisplayShortcuts.as @@ -1,161 +1,161 @@ -package caurina.transitions.properties { - - /** - * properties.DisplayShortcuts.as - * List of default special MovieClip properties (normal and splitter properties) for the Tweener class - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import flash.geom.Point; - import flash.geom.Rectangle; - - import caurina.transitions.Tweener; - - public class DisplayShortcuts { - - /** - * There's no constructor. - */ - public function DisplayShortcuts () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init(): void { - - // Normal properties - Tweener.registerSpecialProperty("_frame", _frame_get, _frame_set); - Tweener.registerSpecialProperty("_autoAlpha", _autoAlpha_get, _autoAlpha_set); - - // Scale splitter properties - Tweener.registerSpecialPropertySplitter("_scale", _scale_splitter); - - // scrollRect splitter properties - Tweener.registerSpecialPropertySplitter("_scrollRect", _scrollRect_splitter); - - // scrollrect normal properties - Tweener.registerSpecialProperty("_scrollRect_x", _scrollRect_property_get, _scrollRect_property_set, ["x"]); - Tweener.registerSpecialProperty("_scrollRect_y", _scrollRect_property_get, _scrollRect_property_set, ["y"]); - Tweener.registerSpecialProperty("_scrollRect_left", _scrollRect_property_get, _scrollRect_property_set, ["left"]); - Tweener.registerSpecialProperty("_scrollRect_right", _scrollRect_property_get, _scrollRect_property_set, ["right"]); - Tweener.registerSpecialProperty("_scrollRect_top", _scrollRect_property_get, _scrollRect_property_set, ["top"]); - Tweener.registerSpecialProperty("_scrollRect_bottom", _scrollRect_property_get, _scrollRect_property_set, ["bottom"]); - Tweener.registerSpecialProperty("_scrollRect_width", _scrollRect_property_get, _scrollRect_property_set, ["width"]); - Tweener.registerSpecialProperty("_scrollRect_height", _scrollRect_property_get, _scrollRect_property_set, ["height"]); - - } - - - // ================================================================================================================================== - // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------------------------------------------------------- - // scale - public static function _scale_splitter(p_value:Number, p_parameters:Array) : Array{ - var nArray:Array = new Array(); - nArray.push({name:"scaleX", value: p_value}); - nArray.push({name:"scaleY", value: p_value}); - return nArray; - } - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _scrollRect - - /** - * Splits the _scrollRect parameter into specific scrollRect variables - * - * @param p_value Rectangle The original _scrollRect rectangle - * @return Array An array containing the .name and .value of all new properties - */ - public static function _scrollRect_splitter (p_value:Rectangle, p_parameters:Array, p_extra:Object = null):Array { - var nArray:Array = new Array(); - if (p_value == null) { - // No parameter passed, so try any rectangle :/ - nArray.push({name:"_scrollRect_x", value:0}); - nArray.push({name:"_scrollRect_y", value:0}); - nArray.push({name:"_scrollRect_width", value:100}); - nArray.push({name:"_scrollRect_height", value:100}); - } else { - // A rectangle is passed, so just return the properties - nArray.push({name:"_scrollRect_x", value:p_value.x}); - nArray.push({name:"_scrollRect_y", value:p_value.y}); - nArray.push({name:"_scrollRect_width", value:p_value.width}); - nArray.push({name:"_scrollRect_height", value:p_value.height}); - } - return nArray; - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _frame - - /** - * Returns the current frame number from the movieclip timeline - * - * @param p_obj Object MovieClip object - * @return Number The current frame - */ - public static function _frame_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.currentFrame; - } - - /** - * Sets the timeline frame - * - * @param p_obj Object MovieClip object - * @param p_value Number New frame number - */ - public static function _frame_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - p_obj.gotoAndStop(Math.round(p_value)); - } - - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _autoAlpha - - /** - * Returns the current alpha - * - * @param p_obj Object MovieClip or Textfield object - * @return Number The current alpha - */ - public static function _autoAlpha_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.alpha; - } - - /** - * Sets the current autoAlpha - * - * @param p_obj Object MovieClip or Textfield object - * @param p_value Number New alpha - */ - public static function _autoAlpha_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - p_obj.alpha = p_value; - p_obj.visible = p_value > 0; - } - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _scrollRect_* - - /** - * _scrollRect_* - * Generic function for the properties of the scrollRect object - */ - public static function _scrollRect_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.scrollRect[p_parameters[0]]; - } - public static function _scrollRect_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - var rect:Rectangle = p_obj.scrollRect; - rect[p_parameters[0]] = Math.round(p_value); - p_obj.scrollRect = rect; - } - } -} +package caurina.transitions.properties { + + /** + * properties.DisplayShortcuts.as + * List of default special MovieClip properties (normal and splitter properties) for the Tweener class + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.geom.Point; + import flash.geom.Rectangle; + + import caurina.transitions.Tweener; + + public class DisplayShortcuts { + + /** + * There's no constructor. + */ + public function DisplayShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Normal properties + Tweener.registerSpecialProperty("_frame", _frame_get, _frame_set); + Tweener.registerSpecialProperty("_autoAlpha", _autoAlpha_get, _autoAlpha_set); + + // Scale splitter properties + Tweener.registerSpecialPropertySplitter("_scale", _scale_splitter); + + // scrollRect splitter properties + Tweener.registerSpecialPropertySplitter("_scrollRect", _scrollRect_splitter); + + // scrollrect normal properties + Tweener.registerSpecialProperty("_scrollRect_x", _scrollRect_property_get, _scrollRect_property_set, ["x"]); + Tweener.registerSpecialProperty("_scrollRect_y", _scrollRect_property_get, _scrollRect_property_set, ["y"]); + Tweener.registerSpecialProperty("_scrollRect_left", _scrollRect_property_get, _scrollRect_property_set, ["left"]); + Tweener.registerSpecialProperty("_scrollRect_right", _scrollRect_property_get, _scrollRect_property_set, ["right"]); + Tweener.registerSpecialProperty("_scrollRect_top", _scrollRect_property_get, _scrollRect_property_set, ["top"]); + Tweener.registerSpecialProperty("_scrollRect_bottom", _scrollRect_property_get, _scrollRect_property_set, ["bottom"]); + Tweener.registerSpecialProperty("_scrollRect_width", _scrollRect_property_get, _scrollRect_property_set, ["width"]); + Tweener.registerSpecialProperty("_scrollRect_height", _scrollRect_property_get, _scrollRect_property_set, ["height"]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // scale + public static function _scale_splitter(p_value:Number, p_parameters:Array) : Array{ + var nArray:Array = new Array(); + nArray.push({name:"scaleX", value: p_value}); + nArray.push({name:"scaleY", value: p_value}); + return nArray; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _scrollRect + + /** + * Splits the _scrollRect parameter into specific scrollRect variables + * + * @param p_value Rectangle The original _scrollRect rectangle + * @return Array An array containing the .name and .value of all new properties + */ + public static function _scrollRect_splitter (p_value:Rectangle, p_parameters:Array, p_extra:Object = null):Array { + var nArray:Array = new Array(); + if (p_value == null) { + // No parameter passed, so try any rectangle :/ + nArray.push({name:"_scrollRect_x", value:0}); + nArray.push({name:"_scrollRect_y", value:0}); + nArray.push({name:"_scrollRect_width", value:100}); + nArray.push({name:"_scrollRect_height", value:100}); + } else { + // A rectangle is passed, so just return the properties + nArray.push({name:"_scrollRect_x", value:p_value.x}); + nArray.push({name:"_scrollRect_y", value:p_value.y}); + nArray.push({name:"_scrollRect_width", value:p_value.width}); + nArray.push({name:"_scrollRect_height", value:p_value.height}); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _frame + + /** + * Returns the current frame number from the movieclip timeline + * + * @param p_obj Object MovieClip object + * @return Number The current frame + */ + public static function _frame_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.currentFrame; + } + + /** + * Sets the timeline frame + * + * @param p_obj Object MovieClip object + * @param p_value Number New frame number + */ + public static function _frame_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + p_obj.gotoAndStop(Math.round(p_value)); + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _autoAlpha + + /** + * Returns the current alpha + * + * @param p_obj Object MovieClip or Textfield object + * @return Number The current alpha + */ + public static function _autoAlpha_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.alpha; + } + + /** + * Sets the current autoAlpha + * + * @param p_obj Object MovieClip or Textfield object + * @param p_value Number New alpha + */ + public static function _autoAlpha_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + p_obj.alpha = p_value; + p_obj.visible = p_value > 0; + } + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _scrollRect_* + + /** + * _scrollRect_* + * Generic function for the properties of the scrollRect object + */ + public static function _scrollRect_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.scrollRect[p_parameters[0]]; + } + public static function _scrollRect_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var rect:Rectangle = p_obj.scrollRect; + rect[p_parameters[0]] = Math.round(p_value); + p_obj.scrollRect = rect; + } + } +} diff --git a/docviewerflex/src/caurina/transitions/properties/FilterShortcuts.as b/docviewerflex/src/caurina/transitions/properties/FilterShortcuts.as index 932393a..9936a63 100644 --- a/docviewerflex/src/caurina/transitions/properties/FilterShortcuts.as +++ b/docviewerflex/src/caurina/transitions/properties/FilterShortcuts.as @@ -1,520 +1,520 @@ -package caurina.transitions.properties { - - /** - * properties.FilterShortcuts - * Special properties for the Tweener class to handle MovieClip filters - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import flash.display.BitmapData; - import flash.filters.BevelFilter; - import flash.filters.BitmapFilter; - import flash.filters.BlurFilter; - import flash.filters.ColorMatrixFilter; - import flash.filters.ConvolutionFilter; - import flash.filters.DisplacementMapFilter; - import flash.filters.DropShadowFilter; - import flash.filters.GlowFilter; - import flash.filters.GradientBevelFilter; - import flash.filters.GradientGlowFilter; - import flash.geom.Point; - - import caurina.transitions.Tweener; - import caurina.transitions.AuxFunctions; - - public class FilterShortcuts { - - /** - * There's no constructor. - */ - public function FilterShortcuts () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init(): void { - - // Filter tweening splitter properties - Tweener.registerSpecialPropertySplitter("_filter", _filter_splitter); - - // Shortcuts - BevelFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/BevelFilter.html - Tweener.registerSpecialProperty("_Bevel_angle", _filter_property_get, _filter_property_set, [BevelFilter, "angle"]); - Tweener.registerSpecialProperty("_Bevel_blurX", _filter_property_get, _filter_property_set, [BevelFilter, "blurX"]); - Tweener.registerSpecialProperty("_Bevel_blurY", _filter_property_get, _filter_property_set, [BevelFilter, "blurY"]); - Tweener.registerSpecialProperty("_Bevel_distance", _filter_property_get, _filter_property_set, [BevelFilter, "distance"]); - Tweener.registerSpecialProperty("_Bevel_highlightAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "highlightAlpha"]); - Tweener.registerSpecialPropertySplitter("_Bevel_highlightColor", _generic_color_splitter, ["_Bevel_highlightColor_r", "_Bevel_highlightColor_g", "_Bevel_highlightColor_b"]); - Tweener.registerSpecialProperty("_Bevel_highlightColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "r"]); - Tweener.registerSpecialProperty("_Bevel_highlightColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "g"]); - Tweener.registerSpecialProperty("_Bevel_highlightColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "b"]); - Tweener.registerSpecialProperty("_Bevel_knockout", _filter_property_get, _filter_property_set, [BevelFilter, "knockout"]); - Tweener.registerSpecialProperty("_Bevel_quality", _filter_property_get, _filter_property_set, [BevelFilter, "quality"]); - Tweener.registerSpecialProperty("_Bevel_shadowAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "shadowAlpha"]); - Tweener.registerSpecialPropertySplitter("_Bevel_shadowColor", _generic_color_splitter, ["_Bevel_shadowColor_r", "_Bevel_shadowColor_g", "_Bevel_shadowColor_b"]); - Tweener.registerSpecialProperty("_Bevel_shadowColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "r"]); - Tweener.registerSpecialProperty("_Bevel_shadowColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "g"]); - Tweener.registerSpecialProperty("_Bevel_shadowColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "b"]); - Tweener.registerSpecialProperty("_Bevel_strength", _filter_property_get, _filter_property_set, [BevelFilter, "strength"]); - Tweener.registerSpecialProperty("_Bevel_type", _filter_property_get, _filter_property_set, [BevelFilter, "type"]); - - // Shortcuts - BlurFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/BlurFilter.html - Tweener.registerSpecialProperty("_Blur_blurX", _filter_property_get, _filter_property_set, [BlurFilter, "blurX"]); - Tweener.registerSpecialProperty("_Blur_blurY", _filter_property_get, _filter_property_set, [BlurFilter, "blurY"]); - Tweener.registerSpecialProperty("_Blur_quality", _filter_property_get, _filter_property_set, [BlurFilter, "quality"]); - - // Shortcuts - ColorMatrixFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/ColorMatrixFilter.html - Tweener.registerSpecialPropertySplitter("_ColorMatrix_matrix", _generic_matrix_splitter, [[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], - ["_ColorMatrix_matrix_rr", "_ColorMatrix_matrix_rg", "_ColorMatrix_matrix_rb", "_ColorMatrix_matrix_ra", "_ColorMatrix_matrix_ro", - "_ColorMatrix_matrix_gr", "_ColorMatrix_matrix_gg", "_ColorMatrix_matrix_gb", "_ColorMatrix_matrix_ga", "_ColorMatrix_matrix_go", - "_ColorMatrix_matrix_br", "_ColorMatrix_matrix_bg", "_ColorMatrix_matrix_bb", "_ColorMatrix_matrix_ba", "_ColorMatrix_matrix_bo", - "_ColorMatrix_matrix_ar", "_ColorMatrix_matrix_ag", "_ColorMatrix_matrix_ab", "_ColorMatrix_matrix_aa", "_ColorMatrix_matrix_ao"]]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_rr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 0]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_rg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 1]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_rb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 2]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ra", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 3]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ro", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 4]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_gr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 5]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_gg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 6]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_gb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 7]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ga", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 8]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_go", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 9]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_br", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 10]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_bg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 11]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_bb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 12]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ba", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 13]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_bo", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 14]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ar", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 15]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ag", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 16]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ab", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 17]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_aa", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 18]); - Tweener.registerSpecialProperty("_ColorMatrix_matrix_ao", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 19]); - - // Shortcuts - ConvolutionFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/ConvolutionFilter.html - Tweener.registerSpecialProperty("_Convolution_alpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "alpha"]); - Tweener.registerSpecialProperty("_Convolution_bias", _filter_property_get, _filter_property_set, [ConvolutionFilter, "bias"]); - Tweener.registerSpecialProperty("_Convolution_clamp", _filter_property_get, _filter_property_set, [ConvolutionFilter, "clamp"]); - Tweener.registerSpecialPropertySplitter("_Convolution_color", _generic_color_splitter, ["_Convolution_color_r", "_Convolution_color_g", "_Convolution_color_b"]); - Tweener.registerSpecialProperty("_Convolution_color_r", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "r"]); - Tweener.registerSpecialProperty("_Convolution_color_g", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "g"]); - Tweener.registerSpecialProperty("_Convolution_color_b", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "b"]); - Tweener.registerSpecialProperty("_Convolution_divisor", _filter_property_get, _filter_property_set, [ConvolutionFilter, "divisor"]); - //Tweener.registerSpecialPropertySplitter("_Convolution_matrix", _generic_array_splitter, ["_Convolution_matrix_array"]); - //Tweener.registerSpecialProperty("_Convolution_matrix_array", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrix", "array"]); - Tweener.registerSpecialProperty("_Convolution_matrixX", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixX"]); - Tweener.registerSpecialProperty("_Convolution_matrixY", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixY"]); - Tweener.registerSpecialProperty("_Convolution_preserveAlpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "preserveAlpha"]); - - // Shortcuts - DisplacementMapFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/DisplacementMapFilter.html - Tweener.registerSpecialProperty("_DisplacementMap_alpha", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "alpha"]); - Tweener.registerSpecialPropertySplitter("_DisplacementMap_color", _generic_color_splitter, ["_DisplacementMap_color_r", "_DisplacementMap_color_r", "_DisplacementMap_color_r"]); - Tweener.registerSpecialProperty("_DisplacementMap_color_r", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "r"]); - Tweener.registerSpecialProperty("_DisplacementMap_color_g", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "g"]); - Tweener.registerSpecialProperty("_DisplacementMap_color_b", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "b"]); - Tweener.registerSpecialProperty("_DisplacementMap_componentX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentX"]); - Tweener.registerSpecialProperty("_DisplacementMap_componentY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentY"]); - Tweener.registerSpecialProperty("_DisplacementMap_mapBitmap", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapBitmap"]); - Tweener.registerSpecialPropertySplitter("_DisplacementMap_mapPoint",_generic_point_splitter, ["_DisplacementMap_mapPoint_x", "_DisplacementMap_mapPoint_y"]); - Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_x", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "x"]); - Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_y", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "y"]); - Tweener.registerSpecialProperty("_DisplacementMap_mode", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mode"]); - Tweener.registerSpecialProperty("_DisplacementMap_scaleX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleX"]); - Tweener.registerSpecialProperty("_DisplacementMap_scaleY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleY"]); - - // Shortcuts - DropShadowFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/DropShadowFilter.html - Tweener.registerSpecialProperty("_DropShadow_alpha", _filter_property_get, _filter_property_set, [DropShadowFilter, "alpha"]); - Tweener.registerSpecialProperty("_DropShadow_angle", _filter_property_get, _filter_property_set, [DropShadowFilter, "angle"]); - Tweener.registerSpecialProperty("_DropShadow_blurX", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurX"]); - Tweener.registerSpecialProperty("_DropShadow_blurY", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurY"]); - Tweener.registerSpecialPropertySplitter("_DropShadow_color", _generic_color_splitter, ["_DropShadow_color_r", "_DropShadow_color_g", "_DropShadow_color_b"]); - Tweener.registerSpecialProperty("_DropShadow_color_r", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "r"]); - Tweener.registerSpecialProperty("_DropShadow_color_g", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "g"]); - Tweener.registerSpecialProperty("_DropShadow_color_b", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "b"]); - Tweener.registerSpecialProperty("_DropShadow_distance", _filter_property_get, _filter_property_set, [DropShadowFilter, "distance"]); - Tweener.registerSpecialProperty("_DropShadow_hideObject", _filter_property_get, _filter_property_set, [DropShadowFilter, "hideObject"]); - Tweener.registerSpecialProperty("_DropShadow_inner", _filter_property_get, _filter_property_set, [DropShadowFilter, "inner"]); - Tweener.registerSpecialProperty("_DropShadow_knockout", _filter_property_get, _filter_property_set, [DropShadowFilter, "knockout"]); - Tweener.registerSpecialProperty("_DropShadow_quality", _filter_property_get, _filter_property_set, [DropShadowFilter, "quality"]); - Tweener.registerSpecialProperty("_DropShadow_strength", _filter_property_get, _filter_property_set, [DropShadowFilter, "strength"]); - - // Shortcuts - GlowFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/GlowFilter.html - Tweener.registerSpecialProperty("_Glow_alpha", _filter_property_get, _filter_property_set, [GlowFilter, "alpha"]); - Tweener.registerSpecialProperty("_Glow_blurX", _filter_property_get, _filter_property_set, [GlowFilter, "blurX"]); - Tweener.registerSpecialProperty("_Glow_blurY", _filter_property_get, _filter_property_set, [GlowFilter, "blurY"]); - Tweener.registerSpecialPropertySplitter("_Glow_color", _generic_color_splitter, ["_Glow_color_r", "_Glow_color_g", "_Glow_color_b"]); - Tweener.registerSpecialProperty("_Glow_color_r", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "r"]); - Tweener.registerSpecialProperty("_Glow_color_g", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "g"]); - Tweener.registerSpecialProperty("_Glow_color_b", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "b"]); - Tweener.registerSpecialProperty("_Glow_inner", _filter_property_get, _filter_property_set, [GlowFilter, "inner"]); - Tweener.registerSpecialProperty("_Glow_knockout", _filter_property_get, _filter_property_set, [GlowFilter, "knockout"]); - Tweener.registerSpecialProperty("_Glow_quality", _filter_property_get, _filter_property_set, [GlowFilter, "quality"]); - Tweener.registerSpecialProperty("_Glow_strength", _filter_property_get, _filter_property_set, [GlowFilter, "strength"]); - - // Shortcuts - GradientBevelFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientBevelFilter.html - // .alphas (array) - Tweener.registerSpecialProperty("_GradientBevel_angle", _filter_property_get, _filter_property_set, [GradientBevelFilter, "angle"]); - Tweener.registerSpecialProperty("_GradientBevel_blurX", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurX"]); - Tweener.registerSpecialProperty("_GradientBevel_blurY", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurY"]); - // .colors (array) - Tweener.registerSpecialProperty("_GradientBevel_distance", _filter_property_get, _filter_property_set, [GradientBevelFilter, "distance"]); - Tweener.registerSpecialProperty("_GradientBevel_quality", _filter_property_get, _filter_property_set, [GradientBevelFilter, "quality"]); - // .ratios(array) - Tweener.registerSpecialProperty("_GradientBevel_strength", _filter_property_get, _filter_property_set, [GradientBevelFilter, "strength"]); - Tweener.registerSpecialProperty("_GradientBevel_type", _filter_property_get, _filter_property_set, [GradientBevelFilter, "type"]); - - // Shortcuts - GradientGlowFilter - // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientGlowFilter.html - // .alphas (array) - Tweener.registerSpecialProperty("_GradientGlow_angle", _filter_property_get, _filter_property_set, [GradientGlowFilter, "angle"]); - Tweener.registerSpecialProperty("_GradientGlow_blurX", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurX"]); - Tweener.registerSpecialProperty("_GradientGlow_blurY", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurY"]); - // .colors (array) - Tweener.registerSpecialProperty("_GradientGlow_distance", _filter_property_get, _filter_property_set, [GradientGlowFilter, "distance"]); - Tweener.registerSpecialProperty("_GradientGlow_knockout", _filter_property_get, _filter_property_set, [GradientGlowFilter, "knockout"]); - Tweener.registerSpecialProperty("_GradientGlow_quality", _filter_property_get, _filter_property_set, [GradientGlowFilter, "quality"]); - // .ratios (array) - Tweener.registerSpecialProperty("_GradientGlow_strength", _filter_property_get, _filter_property_set, [GradientGlowFilter, "strength"]); - Tweener.registerSpecialProperty("_GradientGlow_type", _filter_property_get, _filter_property_set, [GradientGlowFilter, "type"]); - - } - - - // ================================================================================================================================== - // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------------------------------------------------------- - // generic splitters - - /** - * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed - * - * @param p_value Number The original _color value - * @return Array An array containing the .name and .value of all new properties - */ - public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { - var nArray:Array = new Array(); - nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); - nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); - nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); - return nArray; - } - - /** - * A generic mapPoint splitter - from Point to x, y with the name of the parameters passed - * - * @param p_value Point The original point - * @return Array An array containing the .name and .value of all new properties - */ - public static function _generic_point_splitter (p_value:Point, p_parameters:Array):Array { - var nArray:Array = new Array(); - nArray.push({name:p_parameters[0], value:p_value.x}); - nArray.push({name:p_parameters[1], value:p_value.y}); - return nArray; - } - - /** - * A generic matrix splitter - from [] to items with the name of the parameters passed - * - * @param p_value Array The original matrix - * @return Array An array containing the .name and .value of all new properties - */ - public static function _generic_matrix_splitter (p_value:Array, p_parameters:Array):Array { - if (p_value == null) p_value = p_parameters[0].concat(); - var nArray:Array = new Array(); - for (var i:Number = 0; i < p_value.length; i++) { - nArray.push({name:p_parameters[1][i], value:p_value[i]}); - } - return nArray; - } - - /** - * A generic array splitter - from [] to items with the index passed back - * - * @param p_value Array The original array value - * @return Array An array containing the .name and .value of all new properties - */ - /* - public static function _generic_array_splitter (p_value:Array, p_parameters:Array):Array { - if (p_value == null) p_value = p_parameters[0].concat(); - var nArray:Array = new Array(); - for (var i:Number = 0; i < p_value.length; i++) { - nArray.push({name:p_parameters[1][i], value:p_value[i], arrayIndex:i}); - } - return nArray; - } - */ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // filters - - /** - * Splits the _filter, _blur, etc parameter into specific filter variables - * - * @param p_value BitmapFilter A BitmapFilter instance - * @return Array An array containing the .name and .value of all new properties - */ - public static function _filter_splitter (p_value:BitmapFilter, p_parameters:Array, p_extra:Object = null):Array { - var nArray:Array = new Array(); - if (p_value is BevelFilter) { - nArray.push({name:"_Bevel_angle", value:BevelFilter(p_value).angle}); - nArray.push({name:"_Bevel_blurX", value:BevelFilter(p_value).blurX}); - nArray.push({name:"_Bevel_blurY", value:BevelFilter(p_value).blurY}); - nArray.push({name:"_Bevel_distance", value:BevelFilter(p_value).distance}); - nArray.push({name:"_Bevel_highlightAlpha", value:BevelFilter(p_value).highlightAlpha}); - nArray.push({name:"_Bevel_highlightColor", value:BevelFilter(p_value).highlightColor}); - nArray.push({name:"_Bevel_knockout", value:BevelFilter(p_value).knockout}); - nArray.push({name:"_Bevel_quality", value:BevelFilter(p_value).quality}); - nArray.push({name:"_Bevel_shadowAlpha", value:BevelFilter(p_value).shadowAlpha}); - nArray.push({name:"_Bevel_shadowColor", value:BevelFilter(p_value).shadowColor}); - nArray.push({name:"_Bevel_strength", value:BevelFilter(p_value).strength}); - nArray.push({name:"_Bevel_type", value:BevelFilter(p_value).type}); - } else if (p_value is BlurFilter) { - nArray.push({name:"_Blur_blurX", value:BlurFilter(p_value).blurX}); - nArray.push({name:"_Blur_blurY", value:BlurFilter(p_value).blurY}); - nArray.push({name:"_Blur_quality", value:BlurFilter(p_value).quality}); - } else if (p_value is ColorMatrixFilter) { - nArray.push({name:"_ColorMatrix_matrix", value:ColorMatrixFilter(p_value).matrix}); - } else if (p_value is ConvolutionFilter) { - nArray.push({name:"_Convolution_alpha", value:ConvolutionFilter(p_value).alpha}); - nArray.push({name:"_Convolution_bias", value:ConvolutionFilter(p_value).bias}); - nArray.push({name:"_Convolution_clamp", value:ConvolutionFilter(p_value).clamp}); - nArray.push({name:"_Convolution_color", value:ConvolutionFilter(p_value).color}); - // .matrix - nArray.push({name:"_Convolution_divisor", value:ConvolutionFilter(p_value).divisor}); - nArray.push({name:"_Convolution_matrixX", value:ConvolutionFilter(p_value).matrixX}); - nArray.push({name:"_Convolution_matrixY", value:ConvolutionFilter(p_value).matrixY}); - nArray.push({name:"_Convolution_preserveAlpha", value:ConvolutionFilter(p_value).preserveAlpha}); - } else if (p_value is DisplacementMapFilter) { - nArray.push({name:"_DisplacementMap_alpha", value:DisplacementMapFilter(p_value).alpha}); - nArray.push({name:"_DisplacementMap_color", value:DisplacementMapFilter(p_value).color}); - nArray.push({name:"_DisplacementMap_componentX", value:DisplacementMapFilter(p_value).componentX}); - nArray.push({name:"_DisplacementMap_componentY", value:DisplacementMapFilter(p_value).componentY}); - nArray.push({name:"_DisplacementMap_mapBitmap", value:DisplacementMapFilter(p_value).mapBitmap}); - nArray.push({name:"_DisplacementMap_mapPoint", value:DisplacementMapFilter(p_value).mapPoint}); - nArray.push({name:"_DisplacementMap_mode", value:DisplacementMapFilter(p_value).mode}); - nArray.push({name:"_DisplacementMap_scaleX", value:DisplacementMapFilter(p_value).scaleX}); - nArray.push({name:"_DisplacementMap_scaleY", value:DisplacementMapFilter(p_value).scaleY}); - } else if (p_value is DropShadowFilter) { - nArray.push({name:"_DropShadow_alpha", value:DropShadowFilter(p_value).alpha}); - nArray.push({name:"_DropShadow_angle", value:DropShadowFilter(p_value).angle}); - nArray.push({name:"_DropShadow_blurX", value:DropShadowFilter(p_value).blurX}); - nArray.push({name:"_DropShadow_blurY", value:DropShadowFilter(p_value).blurY}); - nArray.push({name:"_DropShadow_color", value:DropShadowFilter(p_value).color}); - nArray.push({name:"_DropShadow_distance", value:DropShadowFilter(p_value).distance}); - nArray.push({name:"_DropShadow_hideObject", value:DropShadowFilter(p_value).hideObject}); - nArray.push({name:"_DropShadow_inner", value:DropShadowFilter(p_value).inner}); - nArray.push({name:"_DropShadow_knockout", value:DropShadowFilter(p_value).knockout}); - nArray.push({name:"_DropShadow_quality", value:DropShadowFilter(p_value).quality}); - nArray.push({name:"_DropShadow_strength", value:DropShadowFilter(p_value).strength}); - } else if (p_value is GlowFilter) { - nArray.push({name:"_Glow_alpha", value:GlowFilter(p_value).alpha}); - nArray.push({name:"_Glow_blurX", value:GlowFilter(p_value).blurX}); - nArray.push({name:"_Glow_blurY", value:GlowFilter(p_value).blurY}); - nArray.push({name:"_Glow_color", value:GlowFilter(p_value).color}); - nArray.push({name:"_Glow_inner", value:GlowFilter(p_value).inner}); - nArray.push({name:"_Glow_knockout", value:GlowFilter(p_value).knockout}); - nArray.push({name:"_Glow_quality", value:GlowFilter(p_value).quality}); - nArray.push({name:"_Glow_strength", value:GlowFilter(p_value).strength}); - } else if (p_value is GradientBevelFilter) { - // .alphas (array) - nArray.push({name:"_GradientBevel_angle", value:GradientBevelFilter(p_value).strength}); - nArray.push({name:"_GradientBevel_blurX", value:GradientBevelFilter(p_value).blurX}); - nArray.push({name:"_GradientBevel_blurY", value:GradientBevelFilter(p_value).blurY}); - // .colors (array) - nArray.push({name:"_GradientBevel_distance", value:GradientBevelFilter(p_value).distance}); - nArray.push({name:"_GradientBevel_quality", value:GradientBevelFilter(p_value).quality}); - // .ratios(array) - nArray.push({name:"_GradientBevel_strength", value:GradientBevelFilter(p_value).strength}); - nArray.push({name:"_GradientBevel_type", value:GradientBevelFilter(p_value).type}); - } else if (p_value is GradientGlowFilter) { - // .alphas (array) - nArray.push({name:"_GradientGlow_angle", value:GradientGlowFilter(p_value).strength}); - nArray.push({name:"_GradientGlow_blurX", value:GradientGlowFilter(p_value).blurX}); - nArray.push({name:"_GradientGlow_blurY", value:GradientGlowFilter(p_value).blurY}); - // .colors (array) - nArray.push({name:"_GradientGlow_distance", value:GradientGlowFilter(p_value).distance}); - nArray.push({name:"_GradientGlow_knockout", value:GradientGlowFilter(p_value).knockout}); - nArray.push({name:"_GradientGlow_quality", value:GradientGlowFilter(p_value).quality}); - // .ratios(array) - nArray.push({name:"_GradientGlow_strength", value:GradientGlowFilter(p_value).strength}); - nArray.push({name:"_GradientGlow_type", value:GradientGlowFilter(p_value).type}); - } else { - // ? - trace ("Tweener FilterShortcuts Error :: Unknown filter class used"); - } - return nArray; - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // filters - - /** - * (filters) - * Generic function for the properties of filter objects - */ - public static function _filter_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - var f:Array = p_obj.filters; - var i:Number; - var filterClass:Object = p_parameters[0]; - var propertyName:String = p_parameters[1]; - var splitType:String = p_parameters[2]; - for (i = 0; i < f.length; i++) { - if (f[i] is Class(filterClass)) { - if (splitType == "color") { - // Composite, color channel - var colorComponent:String = p_parameters[3]; - if (colorComponent == "r") return AuxFunctions.numberToR(f[i][propertyName]); - if (colorComponent == "g") return AuxFunctions.numberToG(f[i][propertyName]); - if (colorComponent == "b") return AuxFunctions.numberToB(f[i][propertyName]); - } else if (splitType == "matrix") { - // Composite, some kind of matrix - return f[i][propertyName][p_parameters[3]]; - } else if (splitType == "point") { - // Composite, a point - return f[i][propertyName][p_parameters[3]]; - } else { - // Standard property - return (f[i][propertyName]); - } - } - } - - // No value found for this property - no filter instance found using this class! - // Must return default desired values - var defaultValues:Object; - switch (filterClass) { - case BevelFilter: - defaultValues = {angle:NaN, blurX:0, blurY:0, distance:0, highlightAlpha:1, highlightColor:NaN, knockout:null, quality:NaN, shadowAlpha:1, shadowColor:NaN, strength:2, type:null}; - break; - case BlurFilter: - defaultValues = {blurX:0, blurY:0, quality:NaN}; - break; - case ColorMatrixFilter: - defaultValues = {matrix:[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]}; - break; - case ConvolutionFilter: - defaultValues = {alpha:0, bias:0, clamp:null, color:NaN, divisor:1, matrix:[1], matrixX:1, matrixY:1, preserveAlpha:null}; - break; - case DisplacementMapFilter: - defaultValues = {alpha:0, color:NaN, componentX:null, componentY:null, mapBitmap:null, mapPoint:null, mode:null, scaleX:0, scaleY:0}; - break; - case DropShadowFilter: - defaultValues = {distance:0, angle:NaN, color:NaN, alpha:1, blurX:0, blurY:0, strength:1, quality:NaN, inner:null, knockout:null, hideObject:null}; - break; - case GlowFilter: - defaultValues = {alpha:1, blurX:0, blurY:0, color:NaN, inner:null, knockout:null, quality:NaN, strength:2}; - break; - case GradientBevelFilter: - defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; - break; - case GradientGlowFilter: - defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; - break; - } - // When returning NaN, the Tweener engine sets the starting value as being the same as the final value (if not found) - // When returning null, the Tweener engine doesn't tween it at all, just setting it to the final value - // This is DIFFERENT from the default filter applied as default on _filter_property_set because some values shouldn't be tweened - if (splitType == "color") { - // Composite, color channel; always defaults to target value - return NaN; - } else if (splitType == "matrix") { - // Composite, matrix; always defaults to target value - return defaultValues[propertyName][p_parameters[3]]; - } else if (splitType == "point") { - // Composite, point; always defaults to target value - return defaultValues[propertyName][p_parameters[3]]; - } else { - // Standard property - return defaultValues[propertyName]; - } - } - - public static function _filter_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - var f:Array = p_obj.filters; - var i:Number; - var filterClass:Object = p_parameters[0]; - var propertyName:String = p_parameters[1]; - var splitType:String = p_parameters[2]; - for (i = 0; i < f.length; i++) { - if (f[i] is Class(filterClass)) { - if (splitType == "color") { - // Composite, color channel - var colorComponent:String = p_parameters[3]; - if (colorComponent == "r") f[i][propertyName] = (f[i][propertyName] & 0xffff) | (p_value << 16); - if (colorComponent == "g") f[i][propertyName] = (f[i][propertyName] & 0xff00ff) | (p_value << 8); - if (colorComponent == "b") f[i][propertyName] = (f[i][propertyName] & 0xffff00) | p_value; - } else if (splitType == "matrix") { - var mtx:Array = f[i][propertyName]; - mtx[p_parameters[3]] = p_value; - f[i][propertyName] = mtx; - } else if (splitType == "point") { - var pt:Point = Point(f[i][propertyName]); - pt[p_parameters[3]] = p_value; - f[i][propertyName] = pt; - } else { - // Standard property - f[i][propertyName] = p_value; - } - p_obj.filters = f; - return; - } - } - - // The correct filter class wasn't found, so create a new one that is the equivalent of the object without the filter - if (f == null) f = new Array(); - var fi:BitmapFilter; - switch (filterClass) { - case BevelFilter: - fi = new BevelFilter(0, 45, 0xffffff, 1, 0x000000, 1, 0, 0); - break; - case BlurFilter: - fi = new BlurFilter(0, 0); - break; - case ColorMatrixFilter: - fi = new ColorMatrixFilter([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]); - break; - case ConvolutionFilter: - fi = new ConvolutionFilter(1, 1, [1], 1, 0, true, true, 0x000000, 0); - break; - case DisplacementMapFilter: - // Doesn't make much sense to create a new empty DisplacementMapFilter if there's nothing to tween - fi = new DisplacementMapFilter(new BitmapData(10, 10), new Point(0, 0), 0, 1, 0, 0); - break; - case DropShadowFilter: - fi = new DropShadowFilter(0, 45, 0x000000, 1, 0, 0); - break; - case GlowFilter: - fi = new GlowFilter(0xff0000, 1, 0, 0); - break; - case GradientBevelFilter: - fi = new GradientBevelFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); - break; - case GradientGlowFilter: - fi = new GradientGlowFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); - break; - } - //fi[propertyName] = p_value; - f.push(fi); - p_obj.filters = f; - _filter_property_set(p_obj, p_value, p_parameters); - } - - } - -} +package caurina.transitions.properties { + + /** + * properties.FilterShortcuts + * Special properties for the Tweener class to handle MovieClip filters + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.display.BitmapData; + import flash.filters.BevelFilter; + import flash.filters.BitmapFilter; + import flash.filters.BlurFilter; + import flash.filters.ColorMatrixFilter; + import flash.filters.ConvolutionFilter; + import flash.filters.DisplacementMapFilter; + import flash.filters.DropShadowFilter; + import flash.filters.GlowFilter; + import flash.filters.GradientBevelFilter; + import flash.filters.GradientGlowFilter; + import flash.geom.Point; + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + public class FilterShortcuts { + + /** + * There's no constructor. + */ + public function FilterShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + + // Filter tweening splitter properties + Tweener.registerSpecialPropertySplitter("_filter", _filter_splitter); + + // Shortcuts - BevelFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/BevelFilter.html + Tweener.registerSpecialProperty("_Bevel_angle", _filter_property_get, _filter_property_set, [BevelFilter, "angle"]); + Tweener.registerSpecialProperty("_Bevel_blurX", _filter_property_get, _filter_property_set, [BevelFilter, "blurX"]); + Tweener.registerSpecialProperty("_Bevel_blurY", _filter_property_get, _filter_property_set, [BevelFilter, "blurY"]); + Tweener.registerSpecialProperty("_Bevel_distance", _filter_property_get, _filter_property_set, [BevelFilter, "distance"]); + Tweener.registerSpecialProperty("_Bevel_highlightAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "highlightAlpha"]); + Tweener.registerSpecialPropertySplitter("_Bevel_highlightColor", _generic_color_splitter, ["_Bevel_highlightColor_r", "_Bevel_highlightColor_g", "_Bevel_highlightColor_b"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "r"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "g"]); + Tweener.registerSpecialProperty("_Bevel_highlightColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "highlightColor", "color", "b"]); + Tweener.registerSpecialProperty("_Bevel_knockout", _filter_property_get, _filter_property_set, [BevelFilter, "knockout"]); + Tweener.registerSpecialProperty("_Bevel_quality", _filter_property_get, _filter_property_set, [BevelFilter, "quality"]); + Tweener.registerSpecialProperty("_Bevel_shadowAlpha", _filter_property_get, _filter_property_set, [BevelFilter, "shadowAlpha"]); + Tweener.registerSpecialPropertySplitter("_Bevel_shadowColor", _generic_color_splitter, ["_Bevel_shadowColor_r", "_Bevel_shadowColor_g", "_Bevel_shadowColor_b"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_r", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "r"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_g", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "g"]); + Tweener.registerSpecialProperty("_Bevel_shadowColor_b", _filter_property_get, _filter_property_set, [BevelFilter, "shadowColor", "color", "b"]); + Tweener.registerSpecialProperty("_Bevel_strength", _filter_property_get, _filter_property_set, [BevelFilter, "strength"]); + Tweener.registerSpecialProperty("_Bevel_type", _filter_property_get, _filter_property_set, [BevelFilter, "type"]); + + // Shortcuts - BlurFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/BlurFilter.html + Tweener.registerSpecialProperty("_Blur_blurX", _filter_property_get, _filter_property_set, [BlurFilter, "blurX"]); + Tweener.registerSpecialProperty("_Blur_blurY", _filter_property_get, _filter_property_set, [BlurFilter, "blurY"]); + Tweener.registerSpecialProperty("_Blur_quality", _filter_property_get, _filter_property_set, [BlurFilter, "quality"]); + + // Shortcuts - ColorMatrixFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/ColorMatrixFilter.html + Tweener.registerSpecialPropertySplitter("_ColorMatrix_matrix", _generic_matrix_splitter, [[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], + ["_ColorMatrix_matrix_rr", "_ColorMatrix_matrix_rg", "_ColorMatrix_matrix_rb", "_ColorMatrix_matrix_ra", "_ColorMatrix_matrix_ro", + "_ColorMatrix_matrix_gr", "_ColorMatrix_matrix_gg", "_ColorMatrix_matrix_gb", "_ColorMatrix_matrix_ga", "_ColorMatrix_matrix_go", + "_ColorMatrix_matrix_br", "_ColorMatrix_matrix_bg", "_ColorMatrix_matrix_bb", "_ColorMatrix_matrix_ba", "_ColorMatrix_matrix_bo", + "_ColorMatrix_matrix_ar", "_ColorMatrix_matrix_ag", "_ColorMatrix_matrix_ab", "_ColorMatrix_matrix_aa", "_ColorMatrix_matrix_ao"]]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 0]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 1]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_rb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 2]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ra", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 3]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ro", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 4]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gr", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 5]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 6]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_gb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 7]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ga", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 8]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_go", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 9]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_br", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 10]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bg", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 11]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bb", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 12]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ba", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 13]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_bo", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 14]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ar", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 15]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ag", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 16]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ab", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 17]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_aa", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 18]); + Tweener.registerSpecialProperty("_ColorMatrix_matrix_ao", _filter_property_get, _filter_property_set, [ColorMatrixFilter, "matrix", "matrix", 19]); + + // Shortcuts - ConvolutionFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/ConvolutionFilter.html + Tweener.registerSpecialProperty("_Convolution_alpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "alpha"]); + Tweener.registerSpecialProperty("_Convolution_bias", _filter_property_get, _filter_property_set, [ConvolutionFilter, "bias"]); + Tweener.registerSpecialProperty("_Convolution_clamp", _filter_property_get, _filter_property_set, [ConvolutionFilter, "clamp"]); + Tweener.registerSpecialPropertySplitter("_Convolution_color", _generic_color_splitter, ["_Convolution_color_r", "_Convolution_color_g", "_Convolution_color_b"]); + Tweener.registerSpecialProperty("_Convolution_color_r", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_Convolution_color_g", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_Convolution_color_b", _filter_property_get, _filter_property_set, [ConvolutionFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_Convolution_divisor", _filter_property_get, _filter_property_set, [ConvolutionFilter, "divisor"]); + //Tweener.registerSpecialPropertySplitter("_Convolution_matrix", _generic_array_splitter, ["_Convolution_matrix_array"]); + //Tweener.registerSpecialProperty("_Convolution_matrix_array", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrix", "array"]); + Tweener.registerSpecialProperty("_Convolution_matrixX", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixX"]); + Tweener.registerSpecialProperty("_Convolution_matrixY", _filter_property_get, _filter_property_set, [ConvolutionFilter, "matrixY"]); + Tweener.registerSpecialProperty("_Convolution_preserveAlpha", _filter_property_get, _filter_property_set, [ConvolutionFilter, "preserveAlpha"]); + + // Shortcuts - DisplacementMapFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/DisplacementMapFilter.html + Tweener.registerSpecialProperty("_DisplacementMap_alpha", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "alpha"]); + Tweener.registerSpecialPropertySplitter("_DisplacementMap_color", _generic_color_splitter, ["_DisplacementMap_color_r", "_DisplacementMap_color_r", "_DisplacementMap_color_r"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_r", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_g", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_DisplacementMap_color_b", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_DisplacementMap_componentX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentX"]); + Tweener.registerSpecialProperty("_DisplacementMap_componentY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "componentY"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapBitmap", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapBitmap"]); + Tweener.registerSpecialPropertySplitter("_DisplacementMap_mapPoint",_generic_point_splitter, ["_DisplacementMap_mapPoint_x", "_DisplacementMap_mapPoint_y"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_x", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "x"]); + Tweener.registerSpecialProperty("_DisplacementMap_mapPoint_y", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mapPoint", "point", "y"]); + Tweener.registerSpecialProperty("_DisplacementMap_mode", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "mode"]); + Tweener.registerSpecialProperty("_DisplacementMap_scaleX", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleX"]); + Tweener.registerSpecialProperty("_DisplacementMap_scaleY", _filter_property_get, _filter_property_set, [DisplacementMapFilter, "scaleY"]); + + // Shortcuts - DropShadowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/DropShadowFilter.html + Tweener.registerSpecialProperty("_DropShadow_alpha", _filter_property_get, _filter_property_set, [DropShadowFilter, "alpha"]); + Tweener.registerSpecialProperty("_DropShadow_angle", _filter_property_get, _filter_property_set, [DropShadowFilter, "angle"]); + Tweener.registerSpecialProperty("_DropShadow_blurX", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurX"]); + Tweener.registerSpecialProperty("_DropShadow_blurY", _filter_property_get, _filter_property_set, [DropShadowFilter, "blurY"]); + Tweener.registerSpecialPropertySplitter("_DropShadow_color", _generic_color_splitter, ["_DropShadow_color_r", "_DropShadow_color_g", "_DropShadow_color_b"]); + Tweener.registerSpecialProperty("_DropShadow_color_r", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_DropShadow_color_g", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_DropShadow_color_b", _filter_property_get, _filter_property_set, [DropShadowFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_DropShadow_distance", _filter_property_get, _filter_property_set, [DropShadowFilter, "distance"]); + Tweener.registerSpecialProperty("_DropShadow_hideObject", _filter_property_get, _filter_property_set, [DropShadowFilter, "hideObject"]); + Tweener.registerSpecialProperty("_DropShadow_inner", _filter_property_get, _filter_property_set, [DropShadowFilter, "inner"]); + Tweener.registerSpecialProperty("_DropShadow_knockout", _filter_property_get, _filter_property_set, [DropShadowFilter, "knockout"]); + Tweener.registerSpecialProperty("_DropShadow_quality", _filter_property_get, _filter_property_set, [DropShadowFilter, "quality"]); + Tweener.registerSpecialProperty("_DropShadow_strength", _filter_property_get, _filter_property_set, [DropShadowFilter, "strength"]); + + // Shortcuts - GlowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GlowFilter.html + Tweener.registerSpecialProperty("_Glow_alpha", _filter_property_get, _filter_property_set, [GlowFilter, "alpha"]); + Tweener.registerSpecialProperty("_Glow_blurX", _filter_property_get, _filter_property_set, [GlowFilter, "blurX"]); + Tweener.registerSpecialProperty("_Glow_blurY", _filter_property_get, _filter_property_set, [GlowFilter, "blurY"]); + Tweener.registerSpecialPropertySplitter("_Glow_color", _generic_color_splitter, ["_Glow_color_r", "_Glow_color_g", "_Glow_color_b"]); + Tweener.registerSpecialProperty("_Glow_color_r", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "r"]); + Tweener.registerSpecialProperty("_Glow_color_g", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "g"]); + Tweener.registerSpecialProperty("_Glow_color_b", _filter_property_get, _filter_property_set, [GlowFilter, "color", "color", "b"]); + Tweener.registerSpecialProperty("_Glow_inner", _filter_property_get, _filter_property_set, [GlowFilter, "inner"]); + Tweener.registerSpecialProperty("_Glow_knockout", _filter_property_get, _filter_property_set, [GlowFilter, "knockout"]); + Tweener.registerSpecialProperty("_Glow_quality", _filter_property_get, _filter_property_set, [GlowFilter, "quality"]); + Tweener.registerSpecialProperty("_Glow_strength", _filter_property_get, _filter_property_set, [GlowFilter, "strength"]); + + // Shortcuts - GradientBevelFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientBevelFilter.html + // .alphas (array) + Tweener.registerSpecialProperty("_GradientBevel_angle", _filter_property_get, _filter_property_set, [GradientBevelFilter, "angle"]); + Tweener.registerSpecialProperty("_GradientBevel_blurX", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurX"]); + Tweener.registerSpecialProperty("_GradientBevel_blurY", _filter_property_get, _filter_property_set, [GradientBevelFilter, "blurY"]); + // .colors (array) + Tweener.registerSpecialProperty("_GradientBevel_distance", _filter_property_get, _filter_property_set, [GradientBevelFilter, "distance"]); + Tweener.registerSpecialProperty("_GradientBevel_quality", _filter_property_get, _filter_property_set, [GradientBevelFilter, "quality"]); + // .ratios(array) + Tweener.registerSpecialProperty("_GradientBevel_strength", _filter_property_get, _filter_property_set, [GradientBevelFilter, "strength"]); + Tweener.registerSpecialProperty("_GradientBevel_type", _filter_property_get, _filter_property_set, [GradientBevelFilter, "type"]); + + // Shortcuts - GradientGlowFilter + // http://livedocs.adobe.com/flex/2/langref/flash/filters/GradientGlowFilter.html + // .alphas (array) + Tweener.registerSpecialProperty("_GradientGlow_angle", _filter_property_get, _filter_property_set, [GradientGlowFilter, "angle"]); + Tweener.registerSpecialProperty("_GradientGlow_blurX", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurX"]); + Tweener.registerSpecialProperty("_GradientGlow_blurY", _filter_property_get, _filter_property_set, [GradientGlowFilter, "blurY"]); + // .colors (array) + Tweener.registerSpecialProperty("_GradientGlow_distance", _filter_property_get, _filter_property_set, [GradientGlowFilter, "distance"]); + Tweener.registerSpecialProperty("_GradientGlow_knockout", _filter_property_get, _filter_property_set, [GradientGlowFilter, "knockout"]); + Tweener.registerSpecialProperty("_GradientGlow_quality", _filter_property_get, _filter_property_set, [GradientGlowFilter, "quality"]); + // .ratios (array) + Tweener.registerSpecialProperty("_GradientGlow_strength", _filter_property_get, _filter_property_set, [GradientGlowFilter, "strength"]); + Tweener.registerSpecialProperty("_GradientGlow_type", _filter_property_get, _filter_property_set, [GradientGlowFilter, "type"]); + + } + + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // generic splitters + + /** + * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); + return nArray; + } + + /** + * A generic mapPoint splitter - from Point to x, y with the name of the parameters passed + * + * @param p_value Point The original point + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_point_splitter (p_value:Point, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:p_value.x}); + nArray.push({name:p_parameters[1], value:p_value.y}); + return nArray; + } + + /** + * A generic matrix splitter - from [] to items with the name of the parameters passed + * + * @param p_value Array The original matrix + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_matrix_splitter (p_value:Array, p_parameters:Array):Array { + if (p_value == null) p_value = p_parameters[0].concat(); + var nArray:Array = new Array(); + for (var i:Number = 0; i < p_value.length; i++) { + nArray.push({name:p_parameters[1][i], value:p_value[i]}); + } + return nArray; + } + + /** + * A generic array splitter - from [] to items with the index passed back + * + * @param p_value Array The original array value + * @return Array An array containing the .name and .value of all new properties + */ + /* + public static function _generic_array_splitter (p_value:Array, p_parameters:Array):Array { + if (p_value == null) p_value = p_parameters[0].concat(); + var nArray:Array = new Array(); + for (var i:Number = 0; i < p_value.length; i++) { + nArray.push({name:p_parameters[1][i], value:p_value[i], arrayIndex:i}); + } + return nArray; + } + */ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // filters + + /** + * Splits the _filter, _blur, etc parameter into specific filter variables + * + * @param p_value BitmapFilter A BitmapFilter instance + * @return Array An array containing the .name and .value of all new properties + */ + public static function _filter_splitter (p_value:BitmapFilter, p_parameters:Array, p_extra:Object = null):Array { + var nArray:Array = new Array(); + if (p_value is BevelFilter) { + nArray.push({name:"_Bevel_angle", value:BevelFilter(p_value).angle}); + nArray.push({name:"_Bevel_blurX", value:BevelFilter(p_value).blurX}); + nArray.push({name:"_Bevel_blurY", value:BevelFilter(p_value).blurY}); + nArray.push({name:"_Bevel_distance", value:BevelFilter(p_value).distance}); + nArray.push({name:"_Bevel_highlightAlpha", value:BevelFilter(p_value).highlightAlpha}); + nArray.push({name:"_Bevel_highlightColor", value:BevelFilter(p_value).highlightColor}); + nArray.push({name:"_Bevel_knockout", value:BevelFilter(p_value).knockout}); + nArray.push({name:"_Bevel_quality", value:BevelFilter(p_value).quality}); + nArray.push({name:"_Bevel_shadowAlpha", value:BevelFilter(p_value).shadowAlpha}); + nArray.push({name:"_Bevel_shadowColor", value:BevelFilter(p_value).shadowColor}); + nArray.push({name:"_Bevel_strength", value:BevelFilter(p_value).strength}); + nArray.push({name:"_Bevel_type", value:BevelFilter(p_value).type}); + } else if (p_value is BlurFilter) { + nArray.push({name:"_Blur_blurX", value:BlurFilter(p_value).blurX}); + nArray.push({name:"_Blur_blurY", value:BlurFilter(p_value).blurY}); + nArray.push({name:"_Blur_quality", value:BlurFilter(p_value).quality}); + } else if (p_value is ColorMatrixFilter) { + nArray.push({name:"_ColorMatrix_matrix", value:ColorMatrixFilter(p_value).matrix}); + } else if (p_value is ConvolutionFilter) { + nArray.push({name:"_Convolution_alpha", value:ConvolutionFilter(p_value).alpha}); + nArray.push({name:"_Convolution_bias", value:ConvolutionFilter(p_value).bias}); + nArray.push({name:"_Convolution_clamp", value:ConvolutionFilter(p_value).clamp}); + nArray.push({name:"_Convolution_color", value:ConvolutionFilter(p_value).color}); + // .matrix + nArray.push({name:"_Convolution_divisor", value:ConvolutionFilter(p_value).divisor}); + nArray.push({name:"_Convolution_matrixX", value:ConvolutionFilter(p_value).matrixX}); + nArray.push({name:"_Convolution_matrixY", value:ConvolutionFilter(p_value).matrixY}); + nArray.push({name:"_Convolution_preserveAlpha", value:ConvolutionFilter(p_value).preserveAlpha}); + } else if (p_value is DisplacementMapFilter) { + nArray.push({name:"_DisplacementMap_alpha", value:DisplacementMapFilter(p_value).alpha}); + nArray.push({name:"_DisplacementMap_color", value:DisplacementMapFilter(p_value).color}); + nArray.push({name:"_DisplacementMap_componentX", value:DisplacementMapFilter(p_value).componentX}); + nArray.push({name:"_DisplacementMap_componentY", value:DisplacementMapFilter(p_value).componentY}); + nArray.push({name:"_DisplacementMap_mapBitmap", value:DisplacementMapFilter(p_value).mapBitmap}); + nArray.push({name:"_DisplacementMap_mapPoint", value:DisplacementMapFilter(p_value).mapPoint}); + nArray.push({name:"_DisplacementMap_mode", value:DisplacementMapFilter(p_value).mode}); + nArray.push({name:"_DisplacementMap_scaleX", value:DisplacementMapFilter(p_value).scaleX}); + nArray.push({name:"_DisplacementMap_scaleY", value:DisplacementMapFilter(p_value).scaleY}); + } else if (p_value is DropShadowFilter) { + nArray.push({name:"_DropShadow_alpha", value:DropShadowFilter(p_value).alpha}); + nArray.push({name:"_DropShadow_angle", value:DropShadowFilter(p_value).angle}); + nArray.push({name:"_DropShadow_blurX", value:DropShadowFilter(p_value).blurX}); + nArray.push({name:"_DropShadow_blurY", value:DropShadowFilter(p_value).blurY}); + nArray.push({name:"_DropShadow_color", value:DropShadowFilter(p_value).color}); + nArray.push({name:"_DropShadow_distance", value:DropShadowFilter(p_value).distance}); + nArray.push({name:"_DropShadow_hideObject", value:DropShadowFilter(p_value).hideObject}); + nArray.push({name:"_DropShadow_inner", value:DropShadowFilter(p_value).inner}); + nArray.push({name:"_DropShadow_knockout", value:DropShadowFilter(p_value).knockout}); + nArray.push({name:"_DropShadow_quality", value:DropShadowFilter(p_value).quality}); + nArray.push({name:"_DropShadow_strength", value:DropShadowFilter(p_value).strength}); + } else if (p_value is GlowFilter) { + nArray.push({name:"_Glow_alpha", value:GlowFilter(p_value).alpha}); + nArray.push({name:"_Glow_blurX", value:GlowFilter(p_value).blurX}); + nArray.push({name:"_Glow_blurY", value:GlowFilter(p_value).blurY}); + nArray.push({name:"_Glow_color", value:GlowFilter(p_value).color}); + nArray.push({name:"_Glow_inner", value:GlowFilter(p_value).inner}); + nArray.push({name:"_Glow_knockout", value:GlowFilter(p_value).knockout}); + nArray.push({name:"_Glow_quality", value:GlowFilter(p_value).quality}); + nArray.push({name:"_Glow_strength", value:GlowFilter(p_value).strength}); + } else if (p_value is GradientBevelFilter) { + // .alphas (array) + nArray.push({name:"_GradientBevel_angle", value:GradientBevelFilter(p_value).strength}); + nArray.push({name:"_GradientBevel_blurX", value:GradientBevelFilter(p_value).blurX}); + nArray.push({name:"_GradientBevel_blurY", value:GradientBevelFilter(p_value).blurY}); + // .colors (array) + nArray.push({name:"_GradientBevel_distance", value:GradientBevelFilter(p_value).distance}); + nArray.push({name:"_GradientBevel_quality", value:GradientBevelFilter(p_value).quality}); + // .ratios(array) + nArray.push({name:"_GradientBevel_strength", value:GradientBevelFilter(p_value).strength}); + nArray.push({name:"_GradientBevel_type", value:GradientBevelFilter(p_value).type}); + } else if (p_value is GradientGlowFilter) { + // .alphas (array) + nArray.push({name:"_GradientGlow_angle", value:GradientGlowFilter(p_value).strength}); + nArray.push({name:"_GradientGlow_blurX", value:GradientGlowFilter(p_value).blurX}); + nArray.push({name:"_GradientGlow_blurY", value:GradientGlowFilter(p_value).blurY}); + // .colors (array) + nArray.push({name:"_GradientGlow_distance", value:GradientGlowFilter(p_value).distance}); + nArray.push({name:"_GradientGlow_knockout", value:GradientGlowFilter(p_value).knockout}); + nArray.push({name:"_GradientGlow_quality", value:GradientGlowFilter(p_value).quality}); + // .ratios(array) + nArray.push({name:"_GradientGlow_strength", value:GradientGlowFilter(p_value).strength}); + nArray.push({name:"_GradientGlow_type", value:GradientGlowFilter(p_value).type}); + } else { + // ? + trace ("Tweener FilterShortcuts Error :: Unknown filter class used"); + } + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // filters + + /** + * (filters) + * Generic function for the properties of filter objects + */ + public static function _filter_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + var f:Array = p_obj.filters; + var i:Number; + var filterClass:Object = p_parameters[0]; + var propertyName:String = p_parameters[1]; + var splitType:String = p_parameters[2]; + for (i = 0; i < f.length; i++) { + if (f[i] is Class(filterClass)) { + if (splitType == "color") { + // Composite, color channel + var colorComponent:String = p_parameters[3]; + if (colorComponent == "r") return AuxFunctions.numberToR(f[i][propertyName]); + if (colorComponent == "g") return AuxFunctions.numberToG(f[i][propertyName]); + if (colorComponent == "b") return AuxFunctions.numberToB(f[i][propertyName]); + } else if (splitType == "matrix") { + // Composite, some kind of matrix + return f[i][propertyName][p_parameters[3]]; + } else if (splitType == "point") { + // Composite, a point + return f[i][propertyName][p_parameters[3]]; + } else { + // Standard property + return (f[i][propertyName]); + } + } + } + + // No value found for this property - no filter instance found using this class! + // Must return default desired values + var defaultValues:Object; + switch (filterClass) { + case BevelFilter: + defaultValues = {angle:NaN, blurX:0, blurY:0, distance:0, highlightAlpha:1, highlightColor:NaN, knockout:null, quality:NaN, shadowAlpha:1, shadowColor:NaN, strength:2, type:null}; + break; + case BlurFilter: + defaultValues = {blurX:0, blurY:0, quality:NaN}; + break; + case ColorMatrixFilter: + defaultValues = {matrix:[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]}; + break; + case ConvolutionFilter: + defaultValues = {alpha:0, bias:0, clamp:null, color:NaN, divisor:1, matrix:[1], matrixX:1, matrixY:1, preserveAlpha:null}; + break; + case DisplacementMapFilter: + defaultValues = {alpha:0, color:NaN, componentX:null, componentY:null, mapBitmap:null, mapPoint:null, mode:null, scaleX:0, scaleY:0}; + break; + case DropShadowFilter: + defaultValues = {distance:0, angle:NaN, color:NaN, alpha:1, blurX:0, blurY:0, strength:1, quality:NaN, inner:null, knockout:null, hideObject:null}; + break; + case GlowFilter: + defaultValues = {alpha:1, blurX:0, blurY:0, color:NaN, inner:null, knockout:null, quality:NaN, strength:2}; + break; + case GradientBevelFilter: + defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; + break; + case GradientGlowFilter: + defaultValues = {alphas:null, angle:NaN, blurX:0, blurY:0, colors:null, distance:0, knockout:null, quality:NaN, ratios:NaN, strength:1, type:null}; + break; + } + // When returning NaN, the Tweener engine sets the starting value as being the same as the final value (if not found) + // When returning null, the Tweener engine doesn't tween it at all, just setting it to the final value + // This is DIFFERENT from the default filter applied as default on _filter_property_set because some values shouldn't be tweened + if (splitType == "color") { + // Composite, color channel; always defaults to target value + return NaN; + } else if (splitType == "matrix") { + // Composite, matrix; always defaults to target value + return defaultValues[propertyName][p_parameters[3]]; + } else if (splitType == "point") { + // Composite, point; always defaults to target value + return defaultValues[propertyName][p_parameters[3]]; + } else { + // Standard property + return defaultValues[propertyName]; + } + } + + public static function _filter_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var f:Array = p_obj.filters; + var i:Number; + var filterClass:Object = p_parameters[0]; + var propertyName:String = p_parameters[1]; + var splitType:String = p_parameters[2]; + for (i = 0; i < f.length; i++) { + if (f[i] is Class(filterClass)) { + if (splitType == "color") { + // Composite, color channel + var colorComponent:String = p_parameters[3]; + if (colorComponent == "r") f[i][propertyName] = (f[i][propertyName] & 0xffff) | (p_value << 16); + if (colorComponent == "g") f[i][propertyName] = (f[i][propertyName] & 0xff00ff) | (p_value << 8); + if (colorComponent == "b") f[i][propertyName] = (f[i][propertyName] & 0xffff00) | p_value; + } else if (splitType == "matrix") { + var mtx:Array = f[i][propertyName]; + mtx[p_parameters[3]] = p_value; + f[i][propertyName] = mtx; + } else if (splitType == "point") { + var pt:Point = Point(f[i][propertyName]); + pt[p_parameters[3]] = p_value; + f[i][propertyName] = pt; + } else { + // Standard property + f[i][propertyName] = p_value; + } + p_obj.filters = f; + return; + } + } + + // The correct filter class wasn't found, so create a new one that is the equivalent of the object without the filter + if (f == null) f = new Array(); + var fi:BitmapFilter; + switch (filterClass) { + case BevelFilter: + fi = new BevelFilter(0, 45, 0xffffff, 1, 0x000000, 1, 0, 0); + break; + case BlurFilter: + fi = new BlurFilter(0, 0); + break; + case ColorMatrixFilter: + fi = new ColorMatrixFilter([1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]); + break; + case ConvolutionFilter: + fi = new ConvolutionFilter(1, 1, [1], 1, 0, true, true, 0x000000, 0); + break; + case DisplacementMapFilter: + // Doesn't make much sense to create a new empty DisplacementMapFilter if there's nothing to tween + fi = new DisplacementMapFilter(new BitmapData(10, 10), new Point(0, 0), 0, 1, 0, 0); + break; + case DropShadowFilter: + fi = new DropShadowFilter(0, 45, 0x000000, 1, 0, 0); + break; + case GlowFilter: + fi = new GlowFilter(0xff0000, 1, 0, 0); + break; + case GradientBevelFilter: + fi = new GradientBevelFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); + break; + case GradientGlowFilter: + fi = new GradientGlowFilter(0, 45, [0xffffff, 0x000000], [1, 1], [32, 223], 0, 0); + break; + } + //fi[propertyName] = p_value; + f.push(fi); + p_obj.filters = f; + _filter_property_set(p_obj, p_value, p_parameters); + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/properties/SoundShortcuts.as b/docviewerflex/src/caurina/transitions/properties/SoundShortcuts.as index 6e8b8a7..7051178 100644 --- a/docviewerflex/src/caurina/transitions/properties/SoundShortcuts.as +++ b/docviewerflex/src/caurina/transitions/properties/SoundShortcuts.as @@ -1,93 +1,93 @@ -package caurina.transitions.properties { - - /** - * properties.SoundShortcuts - * List of default special properties for Sounds - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import flash.media.SoundTransform; - - import caurina.transitions.Tweener; - - public class SoundShortcuts { - - /** - * There's no constructor. - */ - public function SoundShortcuts () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init():void { - - // Normal properties - Tweener.registerSpecialProperty("_sound_volume", _sound_volume_get, _sound_volume_set); - Tweener.registerSpecialProperty("_sound_pan", _sound_pan_get, _sound_pan_set); - - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _sound_volume - - /** - * Returns the current sound volume - * - * @param p_obj Object SoundChannel object - * @return Number The current volume - */ - public static function _sound_volume_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.soundTransform.volume; - } - - /** - * Sets the sound volume - * - * @param p_obj Object SoundChannel object - * @param p_value Number New volume - */ - public static function _sound_volume_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { - var sndTransform:SoundTransform = p_obj.soundTransform; - sndTransform.volume = p_value; - p_obj.soundTransform = sndTransform; - } - - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _sound_pan - - /** - * Returns the current sound pan - * - * @param p_obj Object SoundChannel object - * @return Number The current pan - */ - public static function _sound_pan_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - return p_obj.soundTransform.pan; - } - - /** - * Sets the sound volume - * - * @param p_obj Object SoundChannel object - * @param p_value Number New pan - */ - public static function _sound_pan_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { - var sndTransform:SoundTransform = p_obj.soundTransform; - sndTransform.pan = p_value; - p_obj.soundTransform = sndTransform; - } - - } - -} +package caurina.transitions.properties { + + /** + * properties.SoundShortcuts + * List of default special properties for Sounds + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import flash.media.SoundTransform; + + import caurina.transitions.Tweener; + + public class SoundShortcuts { + + /** + * There's no constructor. + */ + public function SoundShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init():void { + + // Normal properties + Tweener.registerSpecialProperty("_sound_volume", _sound_volume_get, _sound_volume_set); + Tweener.registerSpecialProperty("_sound_pan", _sound_pan_get, _sound_pan_set); + + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _sound_volume + + /** + * Returns the current sound volume + * + * @param p_obj Object SoundChannel object + * @return Number The current volume + */ + public static function _sound_volume_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.soundTransform.volume; + } + + /** + * Sets the sound volume + * + * @param p_obj Object SoundChannel object + * @param p_value Number New volume + */ + public static function _sound_volume_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { + var sndTransform:SoundTransform = p_obj.soundTransform; + sndTransform.volume = p_value; + p_obj.soundTransform = sndTransform; + } + + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _sound_pan + + /** + * Returns the current sound pan + * + * @param p_obj Object SoundChannel object + * @return Number The current pan + */ + public static function _sound_pan_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + return p_obj.soundTransform.pan; + } + + /** + * Sets the sound volume + * + * @param p_obj Object SoundChannel object + * @param p_value Number New pan + */ + public static function _sound_pan_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null):void { + var sndTransform:SoundTransform = p_obj.soundTransform; + sndTransform.pan = p_value; + p_obj.soundTransform = sndTransform; + } + + } + +} diff --git a/docviewerflex/src/caurina/transitions/properties/TextShortcuts.as b/docviewerflex/src/caurina/transitions/properties/TextShortcuts.as index 6d8f3f8..4f0226b 100644 --- a/docviewerflex/src/caurina/transitions/properties/TextShortcuts.as +++ b/docviewerflex/src/caurina/transitions/properties/TextShortcuts.as @@ -1,157 +1,157 @@ -package caurina.transitions.properties { - - /** - * properties.TextShortcuts - * Special properties for the Tweener class to handle MovieClip filters - * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. - * - * @author Zeh Fernando, Nate Chatellier, Arthur Debert - * @version 1.0.0 - */ - - import caurina.transitions.Tweener; - import caurina.transitions.AuxFunctions; - - import flash.text.TextFormat; - - public class TextShortcuts { - - /** - * There's no constructor. - */ - public function TextShortcuts () { - trace ("This is an static class and should not be instantiated.") - } - - /** - * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. - */ - public static function init(): void { - // Normal properties - Tweener.registerSpecialProperty("_text", _text_get, _text_set, null, _text_preProcess); - // Tweener.registerSpecialPropertyModifier("_text", _text_modifier, _text_get); - - // TextFormat-based properties - Tweener.registerSpecialPropertySplitter("_text_color", _generic_color_splitter, ["_text_color_r", "_text_color_g", "_text_color_b"]); - Tweener.registerSpecialProperty("_text_color_r", _textFormat_property_get, _textFormat_property_set, ["color", true, "r"]); - Tweener.registerSpecialProperty("_text_color_g", _textFormat_property_get, _textFormat_property_set, ["color", true, "g"]); - Tweener.registerSpecialProperty("_text_color_b", _textFormat_property_get, _textFormat_property_set, ["color", true, "b"]); - Tweener.registerSpecialProperty("_text_indent", _textFormat_property_get, _textFormat_property_set, ["indent"]); - Tweener.registerSpecialProperty("_text_leading", _textFormat_property_get, _textFormat_property_set, ["leading"]); - Tweener.registerSpecialProperty("_text_leftMargin", _textFormat_property_get, _textFormat_property_set, ["leftMargin"]); - Tweener.registerSpecialProperty("_text_letterSpacing", _textFormat_property_get, _textFormat_property_set, ["letterSpacing"]); - Tweener.registerSpecialProperty("_text_rightMargin", _textFormat_property_get, _textFormat_property_set, ["rightMargin"]); - Tweener.registerSpecialProperty("_text_size", _textFormat_property_get, _textFormat_property_set, ["size"]); - - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - // ---------------------------------------------------------------------------------------------------------------------------------- - // _text - - /** - * Returns the current frame number from the movieclip timeline - * - * @param p_obj Object MovieClip object - * @return Number The current frame - */ - public static function _text_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - //return p_obj._currentFrame; - return -p_obj.text.length; - } - - /** - * Sets the timeline frame - * - * @param p_obj Object MovieClip object - * @param p_value Number New frame number - */ - public static function _text_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - //p_obj.gotoAndStop(Math.round(p_value)); - //p_obj.text = - if (p_value < 0) { - // Old text - p_obj.text = p_extra.oldText.substr(0, -Math.round(p_value)); - } else { - // New text - p_obj.text = p_extra.newText.substr(0, Math.round(p_value)); - } - } - - public static function _text_preProcess (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number { - p_extra.oldText = p_obj.text; - p_extra.newText = p_originalValueComplete; - return p_extra.newText.length; - } - - // ================================================================================================================================== - // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------------------------------------------------------------- - // generic splitters - - /** - * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed - * - * @param p_value Number The original _color value - * @return Array An array containing the .name and .value of all new properties - */ - public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { - var nArray:Array = new Array(); - nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); - nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); - nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); - return nArray; - } - - - // ================================================================================================================================== - // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ - - /** - * Generic function for the textformat properties - */ - public static function _textFormat_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { - var fmt:TextFormat = p_obj.getTextFormat(); - var propertyName:String = p_parameters[0]; - var isColor:Boolean = p_parameters[1]; - if (!isColor) { - // Standard property - return (fmt[propertyName]); - } else { - // Composite, color channel - var colorComponent:String = p_parameters[2]; - if (colorComponent == "r") return AuxFunctions.numberToR(fmt[propertyName]); - if (colorComponent == "g") return AuxFunctions.numberToG(fmt[propertyName]); - if (colorComponent == "b") return AuxFunctions.numberToB(fmt[propertyName]); - } - - return NaN; - } - - public static function _textFormat_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { - var fmt:TextFormat = p_obj.getTextFormat(); - var propertyName:String = p_parameters[0]; - var isColor:Boolean = p_parameters[1]; - if (!isColor) { - // Standard property - fmt[propertyName] = p_value; - } else { - // Composite, color channel - var colorComponent:String = p_parameters[2]; - if (colorComponent == "r") fmt[propertyName] = (fmt[propertyName] & 0xffff) | (p_value << 16); - if (colorComponent == "g") fmt[propertyName] = (fmt[propertyName] & 0xff00ff) | (p_value << 8); - if (colorComponent == "b") fmt[propertyName] = (fmt[propertyName] & 0xffff00) | p_value; - } - - p_obj.defaultTextFormat = fmt; - p_obj.setTextFormat(fmt); - - } - - } - -} +package caurina.transitions.properties { + + /** + * properties.TextShortcuts + * Special properties for the Tweener class to handle MovieClip filters + * The function names are strange/inverted because it makes for easier debugging (alphabetic order). They're only for internal use (on this class) anyways. + * + * @author Zeh Fernando, Nate Chatellier, Arthur Debert + * @version 1.0.0 + */ + + import caurina.transitions.Tweener; + import caurina.transitions.AuxFunctions; + + import flash.text.TextFormat; + + public class TextShortcuts { + + /** + * There's no constructor. + */ + public function TextShortcuts () { + trace ("This is an static class and should not be instantiated.") + } + + /** + * Registers all the special properties to the Tweener class, so the Tweener knows what to do with them. + */ + public static function init(): void { + // Normal properties + Tweener.registerSpecialProperty("_text", _text_get, _text_set, null, _text_preProcess); + // Tweener.registerSpecialPropertyModifier("_text", _text_modifier, _text_get); + + // TextFormat-based properties + Tweener.registerSpecialPropertySplitter("_text_color", _generic_color_splitter, ["_text_color_r", "_text_color_g", "_text_color_b"]); + Tweener.registerSpecialProperty("_text_color_r", _textFormat_property_get, _textFormat_property_set, ["color", true, "r"]); + Tweener.registerSpecialProperty("_text_color_g", _textFormat_property_get, _textFormat_property_set, ["color", true, "g"]); + Tweener.registerSpecialProperty("_text_color_b", _textFormat_property_get, _textFormat_property_set, ["color", true, "b"]); + Tweener.registerSpecialProperty("_text_indent", _textFormat_property_get, _textFormat_property_set, ["indent"]); + Tweener.registerSpecialProperty("_text_leading", _textFormat_property_get, _textFormat_property_set, ["leading"]); + Tweener.registerSpecialProperty("_text_leftMargin", _textFormat_property_get, _textFormat_property_set, ["leftMargin"]); + Tweener.registerSpecialProperty("_text_letterSpacing", _textFormat_property_get, _textFormat_property_set, ["letterSpacing"]); + Tweener.registerSpecialProperty("_text_rightMargin", _textFormat_property_get, _textFormat_property_set, ["rightMargin"]); + Tweener.registerSpecialProperty("_text_size", _textFormat_property_get, _textFormat_property_set, ["size"]); + + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + // ---------------------------------------------------------------------------------------------------------------------------------- + // _text + + /** + * Returns the current frame number from the movieclip timeline + * + * @param p_obj Object MovieClip object + * @return Number The current frame + */ + public static function _text_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + //return p_obj._currentFrame; + return -p_obj.text.length; + } + + /** + * Sets the timeline frame + * + * @param p_obj Object MovieClip object + * @param p_value Number New frame number + */ + public static function _text_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + //p_obj.gotoAndStop(Math.round(p_value)); + //p_obj.text = + if (p_value < 0) { + // Old text + p_obj.text = p_extra.oldText.substr(0, -Math.round(p_value)); + } else { + // New text + p_obj.text = p_extra.newText.substr(0, Math.round(p_value)); + } + } + + public static function _text_preProcess (p_obj:Object, p_parameters:Array, p_originalValueComplete:Object, p_extra:Object): Number { + p_extra.oldText = p_obj.text; + p_extra.newText = p_originalValueComplete; + return p_extra.newText.length; + } + + // ================================================================================================================================== + // PROPERTY GROUPING/SPLITTING functions -------------------------------------------------------------------------------------------- + + // ---------------------------------------------------------------------------------------------------------------------------------- + // generic splitters + + /** + * A generic color splitter - from 0xrrggbb to r, g, b with the name of the parameters passed + * + * @param p_value Number The original _color value + * @return Array An array containing the .name and .value of all new properties + */ + public static function _generic_color_splitter (p_value:Number, p_parameters:Array):Array { + var nArray:Array = new Array(); + nArray.push({name:p_parameters[0], value:AuxFunctions.numberToR(p_value)}); + nArray.push({name:p_parameters[1], value:AuxFunctions.numberToG(p_value)}); + nArray.push({name:p_parameters[2], value:AuxFunctions.numberToB(p_value)}); + return nArray; + } + + + // ================================================================================================================================== + // NORMAL SPECIAL PROPERTY functions ------------------------------------------------------------------------------------------------ + + /** + * Generic function for the textformat properties + */ + public static function _textFormat_property_get (p_obj:Object, p_parameters:Array, p_extra:Object = null):Number { + var fmt:TextFormat = p_obj.getTextFormat(); + var propertyName:String = p_parameters[0]; + var isColor:Boolean = p_parameters[1]; + if (!isColor) { + // Standard property + return (fmt[propertyName]); + } else { + // Composite, color channel + var colorComponent:String = p_parameters[2]; + if (colorComponent == "r") return AuxFunctions.numberToR(fmt[propertyName]); + if (colorComponent == "g") return AuxFunctions.numberToG(fmt[propertyName]); + if (colorComponent == "b") return AuxFunctions.numberToB(fmt[propertyName]); + } + + return NaN; + } + + public static function _textFormat_property_set (p_obj:Object, p_value:Number, p_parameters:Array, p_extra:Object = null): void { + var fmt:TextFormat = p_obj.getTextFormat(); + var propertyName:String = p_parameters[0]; + var isColor:Boolean = p_parameters[1]; + if (!isColor) { + // Standard property + fmt[propertyName] = p_value; + } else { + // Composite, color channel + var colorComponent:String = p_parameters[2]; + if (colorComponent == "r") fmt[propertyName] = (fmt[propertyName] & 0xffff) | (p_value << 16); + if (colorComponent == "g") fmt[propertyName] = (fmt[propertyName] & 0xff00ff) | (p_value << 8); + if (colorComponent == "b") fmt[propertyName] = (fmt[propertyName] & 0xffff00) | p_value; + } + + p_obj.defaultTextFormat = fmt; + p_obj.setTextFormat(fmt); + + } + + } + +} diff --git a/docviewerflex/src/com/devaldi/controls/FlowBox.as b/docviewerflex/src/com/devaldi/controls/FlowBox.as index d393b78..3951222 100644 --- a/docviewerflex/src/com/devaldi/controls/FlowBox.as +++ b/docviewerflex/src/com/devaldi/controls/FlowBox.as @@ -18,6 +18,7 @@ along with FlexPaper. If not, see . package com.devaldi.controls { + import com.devaldi.streaming.DupImage; import flash.display.Bitmap; import flash.display.DisplayObject; diff --git a/docviewerflex/src/com/devaldi/controls/FlowLayout.as b/docviewerflex/src/com/devaldi/controls/FlowLayout.as new file mode 100644 index 0000000..4409901 --- /dev/null +++ b/docviewerflex/src/com/devaldi/controls/FlowLayout.as @@ -0,0 +1,56 @@ +package com.devaldi.controls +{ +import mx.core.ILayoutElement; + +import spark.components.supportClasses.GroupBase; +import spark.layouts.supportClasses.LayoutBase; + +public class FlowLayout extends LayoutBase +{ + override public function updateDisplayList(containerWidth:Number, + containerHeight:Number):void + { + // The position for the current element + var x:Number = 0; + var y:Number = 0; + + // loop through the elements + var layoutTarget:GroupBase = target; + var count:int = layoutTarget.numElements; + for (var i:int = 0; i < count; i++) + { + // get the current element, we're going to work with the + // ILayoutElement interface + var element:ILayoutElement = layoutTarget.getElementAt(i); + + // Resize the element to its preferred size by passing + // NaN for the width and height constraints + element.setLayoutBoundsSize(NaN, NaN); + + // Find out the element's dimensions sizes. + // We do this after the element has been already resized + // to its preferred size. + var elementWidth:Number = element.getLayoutBoundsWidth(); + var elementHeight:Number = element.getLayoutBoundsHeight(); + + // Would the element fit on this line, or should we move + // to the next line? + if (x + elementWidth > containerWidth) + { + // Start from the left side + x = 0; + + // Move down by elementHeight, we're assuming all + // elements are of equal height + y += elementHeight; + } + + // Position the element + element.setLayoutBoundsPosition(x, y); + + // Update the current position, add a gap of 10 + x += elementWidth + 10; + } + } +} +} \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/controls/FlowTwoPage.as b/docviewerflex/src/com/devaldi/controls/FlowTwoPage.as new file mode 100644 index 0000000..ff8ca83 --- /dev/null +++ b/docviewerflex/src/com/devaldi/controls/FlowTwoPage.as @@ -0,0 +1,31 @@ +package com.devaldi.controls +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + + import mx.containers.HBox; + import mx.containers.VBox; + import mx.core.Container; + + public class FlowTwoPage extends VBox + { + public function FlowTwoPage() + { + } + + public override function addChild(child:DisplayObject):DisplayObject + { + var hb:HBox; + if(numChildren == 0 || (numChildren > 0 && (getChildAt(numChildren-1) as HBox).numChildren == 2)){ + hb = new HBox(); + hb.setStyle("horizontalGap",1); + super.addChild(hb); + }else{ + hb = (getChildAt(numChildren-1) as HBox); + } + + hb.addChild(child); + return child; + } + } +} \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/controls/FlowVBox.as b/docviewerflex/src/com/devaldi/controls/FlowVBox.as index 9fbeaa9..bf55039 100644 --- a/docviewerflex/src/com/devaldi/controls/FlowVBox.as +++ b/docviewerflex/src/com/devaldi/controls/FlowVBox.as @@ -1,5 +1,6 @@ package com.devaldi.controls { + import com.devaldi.streaming.DupImage; import flash.display.Bitmap; @@ -12,5 +13,7 @@ package com.devaldi.controls { } + + } } \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/controls/TwoPagePlugin.as b/docviewerflex/src/com/devaldi/controls/TwoPagePlugin.as index 0f7c281..e548ea9 100644 --- a/docviewerflex/src/com/devaldi/controls/TwoPagePlugin.as +++ b/docviewerflex/src/com/devaldi/controls/TwoPagePlugin.as @@ -24,13 +24,10 @@ package com.devaldi.controls import com.devaldi.controls.flexpaper.Viewer; import com.devaldi.controls.flexpaper.utils.StreamUtil; import com.devaldi.events.CurrentPageChangedEvent; - import com.devaldi.events.PageLoadingEvent; import com.devaldi.streaming.DupLoader; - import flash.net.URLRequest; import flash.display.DisplayObject; import flash.events.Event; - import flash.events.IOErrorEvent; import flash.events.EventDispatcher; import flash.events.IEventDispatcher; import flash.events.MouseEvent; @@ -76,47 +73,19 @@ package com.devaldi.controls rp = (i % 2 == 0)?0:1; var uloaderidx:int = (i % 2 == 0)?0:1; - if(i==viewer.PageList.length-1 && viewer.PageList.length % 2 == 1) - viewer.DisplayContainer.getChildAt(1).visible = false; - else - viewer.DisplayContainer.getChildAt(1).visible = true; - - if(((!viewer.BusyLoading||viewer.DocLoader.IsSplit)&&(!viewer.DocLoader.LoaderList[uloaderidx].loading)) && viewer.DocLoader.LoaderList!=null && viewer.DocLoader.LoaderList.length>0){ - if( viewer.libMC!=null&& - (viewer.numPagesLoaded>=viewer.PageList[i].dupIndex || viewer.DocLoader.IsSplit) && - (viewer.DocLoader.LoaderList[uloaderidx] != null) && - (viewer.DocLoader.LoaderList[uloaderidx].content==null) || - (viewer.DocLoader.LoaderList[uloaderidx].content!=null&&viewer.DocLoader.IsSplit && viewer.DocLoader.LoaderList[uloaderidx].pageStartIndex != i+1 && !viewer.DocLoader.LoaderList[uloaderidx].loading) || - (viewer.DocLoader.LoaderList[uloaderidx].content!=null&&(viewer.DocLoader.LoaderList[uloaderidx].content.framesLoaded0){ + if(viewer.libMC!=null&&viewer.numPagesLoaded>=viewer.PageList[i].dupIndex && + viewer.DocLoader.LoaderList[uloaderidx] != null && + viewer.DocLoader.LoaderList[uloaderidx].content==null||(viewer.DocLoader.LoaderList[uloaderidx].content!=null&&viewer.DocLoader.LoaderList[uloaderidx].content.framesLoaded viewer.currPage){ + page = page + 1; + }else if(page % 2 == 0 && page < viewer.currPage){ page = page - 1; } @@ -254,7 +225,6 @@ package com.devaldi.controls public function initOnLoading():void{ viewer.BusyLoading = true; - viewer.DocLoader.LoaderList[0].pageStartIndex = 1; viewer.DocLoader.LoaderList[0].loadBytes(viewer.libMC.loaderInfo.bytes,StreamUtil.getExecutionContext()); } } diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/About.mxml b/docviewerflex/src/com/devaldi/controls/flexpaper/About.mxml index c8c3b23..96a1dd9 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/About.mxml +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/About.mxml @@ -23,7 +23,7 @@ - + - + diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml b/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml index a4a88d8..953cbda 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer.mxml @@ -1,11 +1,22 @@ - +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +--> + [ResourceBundle("FlexPaper")] [Event(name="onDocumentLoaded", type="com.devaldi.events.DocumentLoadedEvent")] @@ -21,105 +32,118 @@ 1 && !isNaN(Number(txtPct.text.replace("%","")))){ - paper.Zoom(new Number(txtPct.text.replace("%",""))/100); + paper1.Zoom(new Number(txtPct.text.replace("%",""))/100); } } - + private function txtSearchKeyDown(event:KeyboardEvent):void{ if(event!=null && event.keyCode == Keyboard.ENTER && txtSearch.text.length>0){ - paper.searchText(txtSearch.text); + paper1.searchText(txtSearch.text); } } - + private function txtPageNumKeyDown(event:KeyboardEvent):void{ if(event.keyCode == Keyboard.ENTER && txtPage.text.length>0 && !isNaN(Number(txtPage.text))){ - paper.gotoPage(new Number(txtPage.text)); + paper1.gotoPage(new Number(txtPage.text)); } } - + protected override function onDocumentLoadingProgressHandler(event:ProgressEvent):void{ lblProgress.text = String(Math.round(event.bytesLoaded/event.bytesTotal*100)); super.onDocumentLoadingProgressHandler(event); } - + private function onScaleChanged(event:Event):void{ - txtPct.text = formatPct(paper.Scale); + txtPct.text = formatPct(paper1.Scale); _sliderUserChange = false; - slidPctScale.value = Number(paper.Scale); + slidPctScale.value = Number(paper1.Scale); } - + public override function loadSwf(s:String):void{ bttnInfo.visible = false; spin1.visible = true; @@ -127,7 +151,7 @@ lblProgress.visible = true; super.loadSwf(s); } - + protected override function onViewModeChanged(event:ViewModeChangedEvent):void{ txtPage.text = formatPageNumber(viewer.currPage); super.onViewModeChanged(event); @@ -135,7 +159,7 @@ protected function formatPageNumber(n:Number):String { - if(viewer.ViewMode == ViewModeEnum.TWOPAGE) + if(viewer.ViewMode == ViewModeEnum.TWOPAGE) return viewer.currPage.toString() + "-" + (viewer.currPage+1).toString(); else return n.toString(); @@ -144,48 +168,50 @@ - + - - - - - - + + + + + + - + - + - + - + - - + + - - - + + + - - - + + + - + - + - + onErrorLoadingPage="errorLoadingPageEventHandler(event)" + + SwfFile="{SwfFile}" + Scale="{Scale}" + ZoomTransition="{ZoomTransition}" + ZoomTime="{ZoomTime}" + FitPageOnLoad="{FitPageOnLoad}" + FitWidthOnLoad="{FitWidthOnLoad}" + ProgressiveLoading="{ProgressiveLoading}" + ZoomInterval="{ZoomInterval}" + MinZoomSize="{MinZoomSize}" + MaxZoomSize="{MaxZoomSize}" + SearchMatchAll="{SearchMatchAll}" + SearchServiceUrl="{SearchServiceUrl}" + + addedToStage="MacMouseWheelHandler.init(stage)" + height="100%" width="100%" tabIndex="0" + verticalScrollPolicy="off" + horizontalScrollPolicy="off" + /> diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml b/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml index ab01de1..35fb52a 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/FlexPaperViewer_Base.mxml @@ -1,454 +1,425 @@ - - + + 10){ -// var cmi_about:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "About")+' FlexPaper'); -// cmi_about.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, showInfo); -// contextMenu.customItems.push(cmi_about); -// } - - if (!ReadOnly) { - var cmi_print:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "Print") + " ..."); - cmi_print.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, printPaper); - contextMenu.customItems.push(cmi_print); - } - } - - public function setViewerFocus():void { - viewer.setPaperFocus(); - } - - public function getCurrPage():Number { - return viewer.currPage; - } - - public function getTotalPages():Number { - return viewer.numPages; - } - - public function nextPage():void { - viewer.mvNext(); - } - - public function prevPage():void { - return viewer.mvPrev(); - } - - public function get PluginList():Array { - return viewer.PluginList; - } - - public function set PluginList(p:Array):void { - viewer.PluginList = p; - } - - // public function showInfo(e:Event):void { - // var vabout:About = new About(); - // PopUpManager.addPopUp(vabout, this, true); - // PopUpManager.centerPopUp(vabout); - // } - - private function setFocusTo(e:MouseEvent):void { - stage.stageFocusRect = false; - stage.focus = e.target as InteractiveObject; - } - - public function printPaper(e:Event):void { - if (!ReadOnly) { - if (PrintDialogEnabled) { - prd = new PrintRangeDialog(); - PopUpManager.addPopUp(prd, this, true); - PopUpManager.centerPopUp(prd); - prd["bttnPrint"].addEventListener("click", printHandler); - } else { - viewer.printPaper(); - } - } - } - - protected function printHandler(event:Event):void { - if (prd.PrintRange != "" && prd.validated) { - viewer.printPaperRange(prd.PrintRange); - } else if (prd.validated) { - viewer.printPaper(); - } - } - - private function fullScreenRedraw(event:FullScreenEvent):void { - if (!event.fullScreen && _fixedWidth > 0) { - viewer.setActualSize(_fixedWidth, _fixedHeight); - } - - if (viewer.FitMode == FitModeEnum.FITWIDTH) { - flash.utils.setTimeout(viewer.fitWidth, 200); - } else if (viewer.FitMode == FitModeEnum.FITHEIGHT) { - flash.utils.setTimeout(viewer.fitHeight, 200); - } else { - viewer.PaperVisible = true; - } - - TrueFullScreenActive = event.fullScreen && !FullScreenAsMaxWindow; - } - - private function viewerKeyDown(event:KeyboardEvent):void { - if (event.keyCode == Keyboard.SPACE && !(event.target is mx.core.UITextField)) { - viewer.mvNext(); - } - } - - private function copyHandler(e:Event):void { - if (!ReadOnly) { - try { - Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, viewer.CurrentlySelectedText); - } catch (e:*) { - } - } - } - - protected function toggleFullScreen():void { - try { - if (!FullScreenAsMaxWindow) { - viewer.PaperVisible = false; // to avoid flickering and let it redraw properly - - if (this.stage.displayState == StageDisplayState.NORMAL) { - _fixedWidth = viewer.width; - _fixedHeight = viewer.height; - } - - switch (this.stage.displayState) { - case StageDisplayState.FULL_SCREEN: - this.stage.displayState = StageDisplayState.NORMAL; - break; - default: - this.stage.displayState = StageDisplayState.FULL_SCREEN; - break; - } - } else { - var ur:URLRequest = new URLRequest(this.stage.loaderInfo.url); - var uv:URLVariables = new URLVariables(); - uv.Scale = Scale; - uv.SecretKey = SecretKey; - uv.SwfFile = SwfFile; - uv.ZoomTransition = ZoomTransition; - uv.ZoomTime = ZoomTime; - uv.ZoomInterval = ZoomInterval; - uv.FitPageOnLoad = viewer.FitMode == FitModeEnum.FITHEIGHT; - uv.FitWidthOnLoad = viewer.FitMode == FitModeEnum.FITWIDTH; - uv.ViewModeToolsVisible = ViewModeToolsVisible; - uv.ZoomToolsVisible = ZoomToolsVisible; - uv.NavToolsVisible = NavToolsVisible; - uv.CursorToolsVisible = CursorToolsVisible; - uv.SearchToolsVisible = SearchToolsVisible; - uv.ProgressiveLoading = ProgressiveLoading; - uv.FullScreenAsMaxWindow = FullScreenAsMaxWindow; - uv.localeChain = resourceManager.localeChain; - uv.ReadOnly = ReadOnly; - ur.data = uv; - navigateToURL(ur, "FlexPaperFullScreen"); - } - } catch (err:SecurityError) { - - } - } - - public function fitWidth():void { - viewer.fitWidth(); - } - - public function fitHeight():void { - viewer.fitHeight(); - } - - public function gotoPage(p:Number):void { - viewer.gotoPage(p); - } - - protected function documentLoadedErrorHandler(event:Event):void { - dispatchEvent(event); - } - - protected function onFitModeChanged(event:FitModeChangedEvent):void { - dispatchEvent(event); - } - - protected function onViewModeChanged(event:ViewModeChangedEvent):void { - dispatchEvent(event); - } - - protected function onCurrPageChanged(event:CurrentPageChangedEvent):void { - dispatchEvent(event); - } - - protected function onCursorModeChanged(event:CursorModeChangedEvent):void { - dispatchEvent(event); - } - - protected function onExternalLinkClickedHandler(event:ExternalLinkClickedEvent):void { - dispatchEvent(event); - } - - protected function onDocumentLoadingProgressHandler(event:ProgressEvent):void { - dispatchEvent(event); - } - - protected function papersLoadingHandler(event:Event):void { - dispatchEvent(event); - } - - protected function pageLoadingEventHandler(event:Event):void { - dispatchEvent(event); - } - - protected function documentPrintedHandler(event:DocumentPrintedEvent):void { - dispatchEvent(event); - } - - protected function documentLoadedHandler(event:Event):void { - dispatchEvent(event); - } - - protected function pageLoadedEventHandler(event:Event):void { - dispatchEvent(event); - } - - protected function errorLoadingPageEventHandler(event:ErrorLoadingPageEvent):void { - dispatchEvent(event); - } - - public function Zoom(factor:Number):void { - viewer.Zoom(factor); - } - - public function searchText(text:String):void { - viewer.searchText(text); - } - - public function prevSearchMatch():void { - viewer.prevSearchMatch(); - } - - public function nextSearchMatch(text:String):void { - viewer.nextSearchMatch(text); - } - - public function switchMode(mode:String = null):void { - viewer.switchMode(mode); - } - - public function setCurrentCursor(cursor:String):void { - if (cursor == "TextSelectorCursor") { - viewer.TextSelectEnabled = true; - } else if (cursor == "ArrowCursor") { - viewer.TextSelectEnabled = false; - } - } - - protected function formatPct(item:Object):String { - var spct:String = (Math.round(Number(item) * 100)) + "%"; - return spct; - } - - public function loadSwf(s:String):void { - viewer.SwfFile = s; - } - - public function loadFromBytes(b:ByteArray):void { - viewer.loadFromBytes(b); - } - - override protected function createChildren():void { - super.createChildren(); - - if (viewer == null) - return; - - _browserManager = BrowserManager.getInstance(); - - try { - //if(LicenseKey.validate(_browserManager.url,VersionHandler.version(),Key,true)){ - - - if (StreamUtil.DocLoader == null) { - viewer.DocLoader = new AVM2Loader(StreamUtil.getExecutionContext(), StreamUtil.ProgressiveLoading); - } else { - viewer.DocLoader = StreamUtil.DocLoader; - } - //} - - viewer.DocLoader.addEventListener("onDocumentLoadedError", onLoadedError); - } catch(e:Error) { - Alert.show(e.message, "Error"); - } - } - - protected function onLoadedError(event:ErrorEvent):void { - dispatchEvent(event); - } - - public function highlight(url:String):void { - viewer.highlight(url); - } - - public function postSnapshot(url:String):void { - var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(viewer); - var imageByteArray:ByteArray = imageSnap.data as ByteArray; - - var request:URLRequest = new URLRequest(url); - var loader:URLLoader = new URLLoader(); - request.contentType = 'application/octet-stream'; - request.method = URLRequestMethod.POST; - request.data = imageByteArray; - loader.load(request); - } - - public function getSecretKey():String { - return SecretKey; - } - - public function setSecretKey(value:String):void { - SecretKey = value; - } - ]]> + import com.devaldi.controls.TwoPagePlugin; + import com.log4ic.resources.MenuIcons; + import com.devaldi.controls.flexpaper.utils.StreamUtil; + import com.devaldi.events.CurrentPageChangedEvent; + import com.devaldi.events.CursorModeChangedEvent; + import com.devaldi.events.DocumentLoadedEvent; + import com.devaldi.events.DocumentPrintedEvent; + import com.devaldi.events.ErrorLoadingPageEvent; + import com.devaldi.events.ExternalLinkClickedEvent; + import com.devaldi.events.FitModeChangedEvent; + import com.devaldi.events.ScaleChangedEvent; + import com.devaldi.events.ViewModeChangedEvent; + import com.devaldi.streaming.AVM2Loader; + import com.devaldi.streaming.IDocumentLoader; + + import flash.desktop.Clipboard; + import flash.desktop.ClipboardFormats; + + import mx.core.UITextField; + import mx.graphics.ImageSnapshot; + import mx.managers.BrowserManager; + import mx.managers.IBrowserManager; + import mx.managers.PopUpManager; + + [Bindable] + public var Scale:Number = 1; + + [Bindable] + public var SwfFile:String = ""; + + [Bindable] + public var SearchServiceUrl:String = ""; + + [Bindable] + public var ZoomTransition:String = "easeOut"; + + [Bindable] + public var ZoomTime:Number = 0.6; + + [Bindable] + public var ZoomInterval:Number = 0.1; + + [Bindable] + public var FitPageOnLoad:Boolean = false; + + [Bindable] + public var FitWidthOnLoad:Boolean = false; + + [Bindable] + public var FullScreenAsMaxWindow:Boolean = false; + + [Bindable] + public var ProgressiveLoading:Boolean = false; + + [Bindable] + protected var TrueFullScreenActive:Boolean = false; + + [Bindable] + public var StartAtPage:Number = 1; + + [Bindable] + public var ReadOnly:Boolean = false; + + [Bindable] + public var MinZoomSize:Number = 0.3; + + [Bindable] + public var MaxZoomSize:Number = 5; + + [Bindable] + public var ViewModeToolsVisible:Boolean = true; + + [Bindable] + public var ZoomToolsVisible:Boolean = true; + + [Bindable] + public var NavToolsVisible:Boolean = true; + + [Bindable] + public var CursorToolsVisible:Boolean = true; + + [Bindable] + public var SearchToolsVisible:Boolean = true; + + [Bindable] + public var PrintDialogEnabled:Boolean = true; + + [Bindable] + public var SearchMatchAll:Boolean = false; + + [Bindable] + public var BitmapBasedRendering:Boolean = false; + + private var _fixedWidth:Number = -1; + private var _fixedHeight:Number = -1; + private var prd:PrintRangeDialog; + private var _twopage:TwoPagePlugin; + protected var _browserManager:IBrowserManager; + + public function get viewer():com.devaldi.controls.flexpaper.Viewer{return null;} + + private function preInit():void{ + _twopage = new TwoPagePlugin(); + + if(Viewer.ViewModeExtList==null) + Viewer.ViewModeExtList = new Array(); + + Viewer.ViewModeExtList[Viewer.ViewModeExtList.length] = _twopage; + } + + private function Init():void{ + _browserManager = BrowserManager.getInstance(); + } + + private function bindStageEvents(e:Event):void{ + stage.removeEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw); + stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw); + stage.addEventListener(KeyboardEvent.KEY_DOWN, viewerKeyDown); + this.addEventListener(MouseEvent.CLICK,setFocusTo); + + contextMenu = new ContextMenu(); + contextMenu.hideBuiltInItems(); + + if(!ReadOnly){ + this.addEventListener(Event.COPY,copyHandler); + contextMenu.clipboardMenu = true; + contextMenu.clipboardItems.copy = true; + contextMenu.clipboardItems.selectAll = false; + } + + if(new MenuIcons.SMALL_TRANSPARENT().width > 10){ + var cmi_about:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "About")+' FlexPaper'); + cmi_about.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, showInfo); + contextMenu.customItems.push(cmi_about); + } + + if(!ReadOnly){ + var cmi_print:ContextMenuItem = new ContextMenuItem(resourceManager.getString("FlexPaper", "Print") + " ..."); + cmi_print.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, printPaper); + contextMenu.customItems.push(cmi_print); + } + } + + public function setViewerFocus():void{ + viewer.setPaperFocus(); + } + + public function getCurrPage():Number{ + return viewer.currPage; + } + + public function nextPage():void{ + return viewer.gotoPage(viewer.currPage+1); + } + + public function prevPage():void{ + return viewer.gotoPage(viewer.currPage-1); + } + + public function get PluginList():Array{ + return viewer.PluginList; + } + + public function set PluginList(p:Array):void{ + viewer.PluginList = p; + } + + public function showInfo(e:Event):void { + var vabout:About = new About(); + PopUpManager.addPopUp(vabout, this, true); + PopUpManager.centerPopUp(vabout); + } + + private function setFocusTo(e:MouseEvent):void{ + stage.stageFocusRect = false; + stage.focus = e.target as InteractiveObject; + } + + public function printPaper(e:Event):void{ + if(!ReadOnly){ + if(PrintDialogEnabled){ + prd = new PrintRangeDialog(); + PopUpManager.addPopUp(prd, this, true); + PopUpManager.centerPopUp(prd); + prd["bttnPrint"].addEventListener("click", printHandler); + }else{ + viewer.printPaper(); + } + } + } + + protected function printHandler(event:Event):void{ + if(prd.PrintRange != "" && prd.validated){ + viewer.printPaperRange(prd.PrintRange); + }else if(prd.validated){ + viewer.printPaper(); + } + } + + private function fullScreenRedraw(event:FullScreenEvent):void{ + if(!event.fullScreen && _fixedWidth>0){ + viewer.setActualSize(_fixedWidth,_fixedHeight); + } + + if(viewer.FitMode == FitModeEnum.FITWIDTH){ + flash.utils.setTimeout(viewer.fitWidth,200); + } else if(viewer.FitMode == FitModeEnum.FITHEIGHT){ + flash.utils.setTimeout(viewer.fitHeight,200); + } else { + viewer.PaperVisible = true; + } + + TrueFullScreenActive = event.fullScreen && !FullScreenAsMaxWindow; + } + + private function viewerKeyDown(event:KeyboardEvent):void{ + if(event.keyCode == Keyboard.SPACE && !(event.target is mx.core.UITextField)){ + viewer.mvNext(); + } + } + + private function copyHandler(e:Event):void{ + if(!ReadOnly){ + try{Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, viewer.CurrentlySelectedText);}catch (e:*) {} + } + } + + protected function toggleFullScreen():void { + try { + if(!FullScreenAsMaxWindow){ + viewer.PaperVisible = false; // to avoid flickering and let it redraw properly + + if(this.stage.displayState == StageDisplayState.NORMAL){ + _fixedWidth = viewer.width; + _fixedHeight = viewer.height; + } + + switch (this.stage.displayState) { + case StageDisplayState.FULL_SCREEN: + this.stage.displayState = StageDisplayState.NORMAL; + break; + default: + this.stage.displayState = StageDisplayState.FULL_SCREEN; + break; + } + }else{ + var ur:URLRequest = new URLRequest(this.stage.loaderInfo.url); + var uv:URLVariables = new URLVariables(); + uv.Scale = Scale; + uv.SwfFile = SwfFile; + uv.ZoomTransition = ZoomTransition; + uv.ZoomTime = ZoomTime; + uv.ZoomInterval = ZoomInterval; + uv.FitPageOnLoad = viewer.FitMode == FitModeEnum.FITHEIGHT; + uv.FitWidthOnLoad = viewer.FitMode == FitModeEnum.FITWIDTH; + uv.ViewModeToolsVisible = ViewModeToolsVisible; + uv.ZoomToolsVisible = ZoomToolsVisible; + uv.NavToolsVisible = NavToolsVisible; + uv.CursorToolsVisible = CursorToolsVisible; + uv.SearchToolsVisible = SearchToolsVisible; + uv.ProgressiveLoading = ProgressiveLoading; + uv.FullScreenAsMaxWindow = FullScreenAsMaxWindow; + uv.localeChain = resourceManager.localeChain; + ur.data = uv; + navigateToURL(ur,"FlexPaperFullScreen"); + } + } catch (err:SecurityError) { + + } + } + + public function fitWidth():void{ + viewer.fitWidth(); + } + + public function fitHeight():void{ + viewer.fitHeight(); + } + + public function gotoPage(p:Number):void{ + viewer.gotoPage(p); + } + + protected function documentLoadedErrorHandler(event:Event):void{ + dispatchEvent(event); + } + + protected function onFitModeChanged(event:FitModeChangedEvent):void{ + dispatchEvent(event); + } + + protected function onViewModeChanged(event:ViewModeChangedEvent):void{ + dispatchEvent(event); + } + + protected function onCurrPageChanged(event:CurrentPageChangedEvent):void{ + dispatchEvent(event); + } + + protected function onCursorModeChanged(event:CursorModeChangedEvent):void{ + dispatchEvent(event); + } + + protected function onExternalLinkClickedHandler(event:ExternalLinkClickedEvent):void{ + dispatchEvent(event); + } + + protected function onDocumentLoadingProgressHandler(event:ProgressEvent):void{ + dispatchEvent(event); + } + + protected function papersLoadingHandler(event:Event):void{ + dispatchEvent(event); + } + + protected function pageLoadingEventHandler(event:Event):void{ + dispatchEvent(event); + } + + protected function documentPrintedHandler(event:DocumentPrintedEvent):void{ + dispatchEvent(event); + } + + protected function documentLoadedHandler(event:Event):void{ + dispatchEvent(event); + } + + protected function pageLoadedEventHandler(event:Event):void{ + dispatchEvent(event); + } + + protected function errorLoadingPageEventHandler(event:ErrorLoadingPageEvent):void{ + dispatchEvent(event); + } + + public function Zoom(factor:Number):void{ + viewer.Zoom(factor); + } + + public function searchText(text:String):void{ + viewer.searchText(text); + } + + public function prevSearchMatch():void{ + viewer.prevSearchMatch(); + } + + public function nextSearchMatch(text:String):void{ + viewer.nextSearchMatch(text); + } + + public function switchMode(mode:String=null):void{ + viewer.switchMode(mode); + } + + public function setCurrentCursor(cursor:String):void{ + if(cursor=="TextSelectorCursor"){ + viewer.TextSelectEnabled = true; + }else if (cursor=="ArrowCursor"){ + viewer.TextSelectEnabled = false; + } + } + + protected function formatPct(item:Object):String { + var spct:String = (Math.round(Number(item)*100)) + "%"; + return spct; + } + + public function loadSwf(s:String):void{ + viewer.SwfFile = s; + } + + override protected function createChildren():void { + super.createChildren(); + + if(viewer==null) + return; + + if(StreamUtil.DocLoader==null) + viewer.DocLoader = new AVM2Loader(StreamUtil.getExecutionContext(),StreamUtil.ProgressiveLoading); + else + viewer.DocLoader = StreamUtil.DocLoader; + + viewer.DocLoader.addEventListener("onDocumentLoadedError",onLoadedError); + } + + protected function onLoadedError(event:ErrorEvent):void{ + dispatchEvent(event); + } + + public function highlight(url:String):void{ + viewer.highlight(url); + } + + public function postSnapshot(url:String):void{ + var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(viewer); + var imageByteArray:ByteArray = imageSnap.data as ByteArray; + + var request:URLRequest = new URLRequest ( url ); + var loader: URLLoader = new URLLoader(); + request.contentType = 'application/octet-stream'; + request.method = URLRequestMethod.POST; + request.data = imageByteArray; + loader.load( request ); + } + ]]> diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as b/docviewerflex/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as index c62a428..404a5b6 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/IFlexPaperPluginControl.as @@ -2,7 +2,6 @@ package com.devaldi.controls.flexpaper { public interface IFlexPaperPluginControl { - function get isInitialized():Boolean; - function set isInitialized(b:Boolean):void; + } } \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/Viewer.as b/docviewerflex/src/com/devaldi/controls/flexpaper/Viewer.as index 387b099..ad57855 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/Viewer.as +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/Viewer.as @@ -1,2931 +1,2564 @@ /* - Copyright 2009 Erik Engström - - This file is part of FlexPaper. - - FlexPaper 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, version 3 of the License. - - FlexPaper 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 FlexPaper. If not, see . - */ - -package com.devaldi.controls.flexpaper { -import caurina.transitions.Tweener; - -import com.devaldi.controls.FlowBox; -import com.devaldi.controls.FlowVBox; -import com.devaldi.controls.ZoomCanvas; -import com.devaldi.controls.flexpaper.resources.MenuIcons; -import com.devaldi.controls.flexpaper.utils.StreamUtil; -import com.devaldi.controls.flexpaper.utils.TextMapUtil; -import com.devaldi.events.CurrentPageChangedEvent; -import com.devaldi.events.CursorModeChangedEvent; -import com.devaldi.events.DocumentLoadedEvent; -import com.devaldi.events.DocumentPrintedEvent; -import com.devaldi.events.ErrorLoadingPageEvent; -import com.devaldi.events.ExternalLinkClickedEvent; -import com.devaldi.events.FitModeChangedEvent; -import com.devaldi.events.PageLoadedEvent; -import com.devaldi.events.PageLoadingEvent; -import com.devaldi.events.ScaleChangedEvent; -import com.devaldi.events.SelectionCreatedEvent; -import com.devaldi.events.SwfLoadedEvent; -import com.devaldi.events.ViewModeChangedEvent; -import com.devaldi.streaming.DupImage; -import com.devaldi.streaming.DupLoader; -import com.devaldi.streaming.IDocumentLoader; -import com.devaldi.streaming.IGenericDocument; -import com.devaldi.streaming.SwfDocument; -import com.sinitek.log4ic.utils.security.Security; - -import flash.display.AVM1Movie; -import flash.display.Bitmap; -import flash.display.BitmapData; -import flash.display.DisplayObject; -import flash.display.InteractiveObject; -import flash.display.Loader; -import flash.display.MovieClip; -import flash.display.SimpleButton; -import flash.display.Sprite; -import flash.events.Event; -import flash.events.IOErrorEvent; -import flash.events.KeyboardEvent; -import flash.events.MouseEvent; -import flash.events.ProgressEvent; -import flash.filters.DropShadowFilter; -import flash.geom.Matrix; -import flash.net.URLRequest; -import flash.printing.PrintJob; -import flash.printing.PrintJobOptions; -import flash.system.System; -import flash.text.TextSnapshot; -import flash.ui.Keyboard; -import flash.utils.ByteArray; -import flash.utils.Timer; -import flash.utils.setTimeout; - -import mx.containers.Canvas; -import mx.controls.Alert; -import mx.controls.Image; -import mx.core.Container; -import mx.core.UIComponent; -import mx.events.FlexEvent; -import mx.managers.CursorManager; -import mx.resources.ResourceManager; -import mx.rpc.events.FaultEvent; -import mx.rpc.events.ResultEvent; -import mx.rpc.http.HTTPService; - -[Event(name="onDocumentLoaded", type="com.devaldi.events.DocumentLoadedEvent")] -[Event(name="onPageLoaded", type="com.devaldi.events.PageLoadedEvent")] -[Event(name="onPageLoading", type="com.devaldi.events.PageLoadingEvent")] -[Event(name="onDocumentLoading", type="flash.events.Event")] -[Event(name="onNoMoreSearchResults", type="flash.events.Event")] -[Event(name="onLoadingProgress", type="flash.events.ProgressEvent")] -[Event(name="onScaleChanged", type="com.devaldi.events.ScaleChangedEvent")] -[Event(name="onExternalLinkClicked", type="com.devaldi.events.ExternalLinkClickedEvent")] -[Event(name="onCurrPageChanged", type="com.devaldi.events.CurrentPageChangedEvent")] -[Event(name="onViewModeChanged", type="com.devaldi.events.ViewModeChangedEvent")] -[Event(name="onFitModeChanged", type="com.devaldi.events.FitModeChangedEvent")] -[Event(name="onCursorModeChanged", type="com.devaldi.events.CursorModeChangedEvent")] -[Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] -//[Event(name="onLogoClicked", type="flash.events.Event")] -[Event(name="onSelectionCreated", type="com.devaldi.events.SelectionCreatedEvent")] -[Event(name="onDocumentPrinted", type="com.devaldi.events.DocumentPrintedEvent")] -[Event(name="onErrorLoadingPage", type="com.devaldi.events.ErrorLoadingPageEvent")] - -public class Viewer extends Canvas { - private var _secretKey:String = null; - private var _swfFile:String = ""; - private var _swfFileChanged:Boolean = false; - private var _initialized:Boolean = false; - private var _loaderptr:Loader; - private var _libMC:IGenericDocument; - private var _displayContainer:Container; - private var _paperContainer:ZoomCanvas; - private var _swfContainer:Canvas; - private var _scale:Number = 1; - private var _pscale:Number = 1; - private var _swfLoaded:Boolean = false; - private var _pageList:Array; - private var _viewMode:String = Viewer.InitViewMode; - private var _fitMode:String = FitModeEnum.FITNONE; - public static var InitViewMode:String = ViewModeEnum.PORTRAIT; - private var _scrollToPage:Number = 0; - private var _numPages:Number = 0; - private var _currPage:Number = 0; - private var _tweencount:Number = 0; - private var _bbusyloading:Boolean = true; - private var _zoomtransition:String = "easeOut"; - private var _zoomtime:Number = 0.6; - private var _fitPageOnLoad:Boolean = false; - private var _fitWidthOnLoad:Boolean = false; - private var _dupImageClicked:Boolean = false; - private var _docLoader:IDocumentLoader; - private var _progressiveLoading:Boolean = false; - private var _repaintTimer:Timer; - private var _loadTimer:Timer; - private var _frameLoadCount:int = 0; - private var _adjGotoPage:int = 0; - private var _zoomInterval:Number = 0; - private var _inputBytes:ByteArray; - private var _textSelectEnabled:Boolean = false; - private var _cursorsEnabled:Boolean = true; - private var _grabCursorID:Number = 0; - private var _grabbingCursorID:Number = 0; - private var _pluginList:Array; - public static var ViewModeExtList:Array; - private var _currentExtViewMode:IFlexPaperViewModePlugin; - private var _minZoomSize:Number = 0.3; - private var _maxZoomSize:Number = 5; - private var _searchMatchAll:Boolean = false; - private var _searchServiceUrl:String = ""; - private var _performSearchOnPageLoad:Boolean = false; - private var _pendingSearchPage:int = -1; - private var _skinImg:Bitmap = new MenuIcons.SMALL_TRANSPARENT(); - private var _skinImgc:Bitmap = new MenuIcons.SMALL_TRANSPARENT_COLOR(); - - -// private var _skinImgDo:Image; - - public function Viewer() { - super(); - } - - public function get BusyLoading():Boolean { - return _bbusyloading; - } - - public function set BusyLoading(b:Boolean):void { - _bbusyloading = b; - } - - public function get libMC():IGenericDocument { - return _libMC; - } - - public function get IsInitialized():Boolean { - return _initialized; - } - - public function get SwfLoaded():Boolean { - return _swfLoaded; - } - - public function get DisplayContainer():Container { - return _displayContainer; - } - - public function set DisplayContainer(c:Container):void { - _displayContainer = c; - } - - public function get PaperContainer():ZoomCanvas { - return _paperContainer; - } - - public function get PageList():Array { - return _pageList; - } - - public function get DocLoader():IDocumentLoader { - return _docLoader; - } - - public function set DocLoader(d:IDocumentLoader):void { - _docLoader = d; - } - - [Bindable] - public function get ViewMode():String { - return _viewMode; - } - - [Bindable] - public function get FitMode():String { - return _fitMode; - } - - public function set ViewMode(s:String):void { - if (s != _viewMode) { - for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList) { - if (s == vme.Name) { - _currentExtViewMode = vme; - } - } - - if (s == ViewModeEnum.TILE && ViewMode == ViewModeEnum.PORTRAIT) { - _pscale = _scale; - _scale = 0.23; - _paperContainer.verticalScrollPosition = 0; - _fitMode = FitModeEnum.FITNONE; - } else { - _scale = _pscale; - } - _paperContainer.x = (s == ViewModeEnum.PORTRAIT || s == ViewModeEnum.TILE) ? 2.5 : 0; - - _viewMode = s; - if (_initialized && _swfLoaded) { - createDisplayContainer(); - if (this._progressiveLoading) { - this.addInLoadedPages(true); - } else { - reCreateAllPages(); - } - _displayContainer.visible = true; - } - FitMode = FitModeEnum.FITNONE; - - if (UsingExtViewMode) { - CurrExtViewMode.setViewMode(s); - _viewMode = s; - } - - dispatchEvent(new ViewModeChangedEvent(ViewModeChangedEvent.VIEWMODE_CHANGED, _viewMode)); - dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); - dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED, _fitMode)); - } - } - - public function set FitMode(s:String):void { - if (_viewMode == ViewModeEnum.TILE) { - _fitMode = FitModeEnum.FITNONE; - return - } - - if (s != _fitMode) { - _fitMode = s; - - switch (s) { - case FitModeEnum.FITWIDTH: - fitWidth(); - break; - - case FitModeEnum.FITHEIGHT: - fitHeight(); - break; - } - - dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED, _fitMode)); - } - } - - public function set ProgressiveLoading(b1:Boolean):void { - _progressiveLoading = b1; - } - - [Bindable] - public function get ProgressiveLoading():Boolean { - return _progressiveLoading; - } - - public function set TextSelectEnabled(b1:Boolean):void { - _textSelectEnabled = b1; - - if (_textSelectEnabled && CursorsEnabled) - dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED, "TextSelectorCursor")); - else - dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED, "ArrowCursor")); - } - - [Bindable] - public function get TextSelectEnabled():Boolean { - return _textSelectEnabled; - } - - [Bindable] - public function get CursorsEnabled():Boolean { - return _cursorsEnabled; - } - - public function set CursorsEnabled(b:Boolean):void { - _cursorsEnabled = b; - } - - public function setPaperFocus():void { - _paperContainer.setFocus(); - } - - public function get ZoomTransition():String { - return _zoomtransition; - } - - public function set ZoomTransition(s:String):void { - _zoomtransition = s; - } - - public function get ZoomTime():Number { - return _zoomtime; - } - - public function set ZoomTime(n:Number):void { - _zoomtime = n; - } - - public function get MinZoomSize():Number { - return _minZoomSize; - } - - public function set MinZoomSize(n:Number):void { - _minZoomSize = n; - } - - public function get MaxZoomSize():Number { - return _maxZoomSize; - } - - public function set MaxZoomSize(n:Number):void { - _maxZoomSize = n; - } - - public function get PluginList():Array { - return _pluginList; - } - - public function set PluginList(p:Array):void { - _pluginList = p; - } - - public function get CurrExtViewMode():IFlexPaperViewModePlugin { - if (_currentExtViewMode != null && _currentExtViewMode.Name == ViewMode) - return _currentExtViewMode; - else { - for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList) { - if (ViewMode == vme.Name) { - _currentExtViewMode = vme; - } - } - } - - return _currentExtViewMode; - } - - public function get UsingExtViewMode():Boolean { - if (ViewMode == ViewModeEnum.PORTRAIT || ViewMode == ViewModeEnum.TILE) - return false; - else - return (CurrExtViewMode != null && ViewMode == CurrExtViewMode.Name); - } - - public function get ZoomInterval():Number { - return _zoomInterval; - } - - public function set ZoomInterval(n:Number):void { - _zoomInterval = n; - } - - [Bindable] - public function get numPages():Number { - return _numPages; - } - - public function set numPages(n:Number):void { - _numPages = n; - } - - [Bindable] - public function get numPagesLoaded():Number { - return (_libMC != null) ? _libMC.framesLoaded : 0; - } - - public function set numPagesLoaded(n:Number):void { - - } - - [Bindable] - public function get currPage():Number { - return _currPage; - } - - public function set currPage(n:Number):void { - _currPage = n; - } - - [Bindable] - public function get SearchMatchAll():Boolean { - if (SearchServiceUrl != null && SearchServiceUrl.length > 0) - return false; - else - return _searchMatchAll; - } - - public function set SearchMatchAll(b1:Boolean):void { - _searchMatchAll = b1; - } - - [Bindable] - public function get SearchServiceUrl():String { - return _searchServiceUrl; - } - - public function set SearchServiceUrl(s1:String):void { - _searchServiceUrl = unescape(s1); - } - - public function get FitWidthOnLoad():Boolean { - return _fitWidthOnLoad; - } - - public function set FitWidthOnLoad(b1:Boolean):void { - _fitWidthOnLoad = b1; - } - - public function get FitPageOnLoad():Boolean { - return _fitPageOnLoad; - } - - public function set FitPageOnLoad(b2:Boolean):void { - _fitPageOnLoad = b2; - } - - public function gotoPage(p:Number, adjGotoPage:int = 0):void { - if (adjGotoPage != 0) { - _adjGotoPage = adjGotoPage; - } - - if (p < 1 || p - 1 > _pageList.length) - return; - else { - if (ViewMode == ViewModeEnum.PORTRAIT) { - _paperContainer.verticalScrollPosition = _pageList[p - 1].y + 3 + _adjGotoPage; - } - - if (UsingExtViewMode) - CurrExtViewMode.gotoPage(p, adjGotoPage); - - // retry if y is not set - if (!UsingExtViewMode && p > 1 && _pageList[p - 1].y == 0) { - flash.utils.setTimeout(gotoPage, 200, p); - } - else - _adjGotoPage = 0; - - repaint(); - } - } - - public function mvNext(extmode:Boolean = true):void { - if (UsingExtViewMode && extmode) - CurrExtViewMode.mvNext(); - else - if (currPage < numPages) { - gotoPage(currPage + 1); - } - } - - public function mvPrev(extmode:Boolean = true):void { - if (UsingExtViewMode && extmode) - CurrExtViewMode.mvPrev(); - else { - if (currPage > 1) { - gotoPage(currPage - 1); - } - } - } - - public function switchMode(mode:String = null):void { - if (mode == null) { // no mode passed, just - if (ViewMode == ViewModeEnum.PORTRAIT) { - ViewMode = ViewModeEnum.TILE; - } - else if (ViewMode == ViewModeEnum.TILE) { - _scale = _pscale; - ViewMode = ViewModeEnum.PORTRAIT; - } - } else { - if (ViewMode == mode && ViewMode != ViewModeEnum.PORTRAIT) { - ViewMode = ViewModeEnum.PORTRAIT; - } - else - ViewMode = mode; - } - } - - public function get PaperVisible():Boolean { - return _paperContainer.visible; - } - - public function set PaperVisible(b:Boolean):void { - _paperContainer.visible = b; - } - - public function get SwfFile():String { - return _swfFile; - } - - public function getSwfFilePerPage(swfFile:String, page:int):String { - var fileName:String = swfFile; - var map:String = (fileName.substr(fileName.indexOf("[*,"), fileName.indexOf("]") - fileName.indexOf("[*,") + 1)); - var padding:int = parseInt(map.substr(map.indexOf(",") + 1, map.indexOf("]") - 2)); - fileName = TextMapUtil.StringReplaceAll(fileName, map, padString(page.toString(), padding, "0")); - - return encodeURI(fileName); - } - - public function loadFromBytes(bytes:ByteArray):void { - clearPlugins(); - deleteDisplayContainer(); - deletePageList(); - deleteLoaderPtr(); - deleteLoaderList(); - deleteFLoader(); - deleteSelectionMarker(); - TextMapUtil.totalFragments = ""; - deleteLibMC(); - - _swfFileChanged = true; - _frameLoadCount = 0; - - ViewMode = Viewer.InitViewMode; - - try { - new flash.net.LocalConnection().connect('devaldiGCdummy'); - new flash.net.LocalConnection().connect('devaldiGCdummy'); - } catch (e:*) { - } - - try { - flash.system.System.gc(); - } catch (e:*) { - } - - if (_docLoader != null && !_docLoader.hasEventListener(SwfLoadedEvent.SWFLOADED)) { - _docLoader.addEventListener("onDocumentLoadedError", onDocumentLoadedErrorHandler, false, 0, true); - _docLoader.addEventListener(SwfLoadedEvent.SWFLOADED, swfComplete, false, 0, true); - } - - if (_docLoader != null) { - _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); - _docLoader.stream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress, false, 0, true); - } - - _docLoader.loadFromBytes(bytes); - - _paperContainer.verticalScrollPosition = 0; - createDisplayContainer(); - - // Changing the SWF file causes the component to invalidate. - invalidateProperties(); - invalidateSize(); - invalidateDisplayList(); - } - - public function set SwfFile(s:String):void { - var pagesSplit:Boolean = false; - s = unescape(s); - - if (s.length != 0) { - - if (s.indexOf("{") >= 0 && s.indexOf("}") > 0) { - numPages = parseInt(s.substr(s.lastIndexOf(",") + 1, s.indexOf("}") - s.lastIndexOf(",") - 1)); - s = TextMapUtil.StringReplaceAll(s, "{", ""); - s = TextMapUtil.StringReplaceAll(s, "," + numPages.toString() + "}", ""); - pagesSplit = true; - } - - clearPlugins(); - deleteDisplayContainer(); - deletePageList(); - deleteLoaderPtr(); - deleteLoaderList(); - deleteFLoader(); - deleteSelectionMarker(); - TextMapUtil.totalFragments = ""; - - if (s != _swfFile) - deleteLibMC(); - - _swfFileChanged = true; - _frameLoadCount = 0; - - if (!pagesSplit) - _swfFile = encodeURI(s); - else - _swfFile = s; - - ViewMode = Viewer.InitViewMode; - - try { - new flash.net.LocalConnection().connect('devaldiGCdummy'); - new flash.net.LocalConnection().connect('devaldiGCdummy'); - } catch (e:*) { - } - - try { - flash.system.System.gc(); - } catch (e:*) { - } - - if (_docLoader != null && !_docLoader.hasEventListener(SwfLoadedEvent.SWFLOADED)) { - _docLoader.IsSplit = pagesSplit; - _docLoader.addEventListener("onDocumentLoadedError", onDocumentLoadedErrorHandler, false, 0, true); - _docLoader.addEventListener(SwfLoadedEvent.SWFLOADED, swfComplete, false, 0, true); - } - - if (_docLoader != null) { - _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); - _docLoader.stream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress, false, 0, true); - } - - _paperContainer.verticalScrollPosition = 0; - createDisplayContainer(); - - // Changing the SWF file causes the component to invalidate. - invalidateProperties(); - invalidateSize(); - invalidateDisplayList(); - - var _request:URLRequest; - - if (_swfFile.length > 0 && pagesSplit) { - _loadTimer = new Timer(100); - _loadTimer.addEventListener("timer", loadtimer); - _request = new URLRequest(getSwfFilePerPage(_swfFile, 1)); - } - else if (_swfFile.length > 0 && !pagesSplit) { - _request = new URLRequest(_swfFile); - } - - Security.loadEncryptedFile(_request, _secretKey, function(e:Event):void { - _docLoader.loadFromBytes(_secretKey ? e.target.decryptedData : e.target.data); - }, onLoadProgress); - } - } - - [Bindable] - public function get Scale():String { - return _scale.toString(); - } - - public function get CurrentlySelectedText():String { - return _currentlySelectedText; - } - - public function Zoom(factor:Number):void { - if (factor < _minZoomSize || factor > _maxZoomSize || factor == _scale) - return; - - if ((!UsingExtViewMode && _viewMode != ViewModeEnum.PORTRAIT) || (UsingExtViewMode && !CurrExtViewMode.doZoom)) { - return; - } - - var _target:DisplayObject; - _paperContainer.CenteringEnabled = (_paperContainer.width > 0); - - _tweencount = _displayContainer.numChildren; - - for (var i:int = 0; i < _displayContainer.numChildren; i++) { - _target = _displayContainer.getChildAt(i); - _target.filters = null; - Tweener.addTween(_target, {scaleX: factor, scaleY: factor, time: _zoomtime, transition: _zoomtransition, onComplete: tweenComplete}); - } - - FitMode = FitModeEnum.FITNONE; - _scale = factor; - - dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); - } - - // rotate not finished. - public function rotate():void { - var counter:int = 0; - //Tweener.addTween(_displayContainer.getChildAt(currPage-1), {x:_displayContainer.getChildAt(currPage-1).parent.width/2+_displayContainer.getChildAt(currPage-1).height/2, y:((_displayContainer.getChildAt(currPage-1).height/2)-_displayContainer.getChildAt(currPage-1).width/2),rotation:90, time: 0.3, transition: 'easenone', onComplete: tweenComplete}); - } - - public function getFitWidthFactor():Number { - _libMC.gotoAndStop(1); - return (_paperContainer.width / _libMC.width) - 0.032; //- 0.03; - } - - public function getFitHeightFactor():Number { - _libMC.gotoAndStop(1); - return (_paperContainer.height / _libMC.height); - } - - public function fitWidth():Boolean { - if (_displayContainer.numChildren == 0) { - return false; - } - - var _target:DisplayObject; - _paperContainer.CenteringEnabled = (_paperContainer.width > 0); - var factor:Number = getFitWidthFactor(); - _scale = factor; - _tweencount = _displayContainer.numChildren; - - for (var i:int = 0; i < _displayContainer.numChildren; i++) { - _target = _displayContainer.getChildAt(i); - _target.filters = null; - Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); - } - - FitMode = FitModeEnum.FITWIDTH; - dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); - - _paperContainer.horizontalScrollPosition = _paperContainer.maxHorizontalScrollPosition / 2; - _paperContainer.validateDisplayList(); - - return factor > 0; - } - - public function fitHeight():Boolean { - if (_displayContainer.numChildren == 0) { - return false; - } - - var _target:DisplayObject; - _paperContainer.CenteringEnabled = (_paperContainer.height > 0); - var factor:Number = getFitHeightFactor(); - _scale = factor; - _tweencount = _displayContainer.numChildren; - - for (var i:int = 0; i < _displayContainer.numChildren; i++) { - _target = _displayContainer.getChildAt(i); - _target.filters = null; - Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); - } - - FitMode = FitModeEnum.FITHEIGHT; - dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED, _scale)); - - return factor > 0; - } - - private function tweenComplete():void { - _tweencount--; - - if (_tweencount == 0) { - - if (_loadTimer != null) - _loadTimer.start(); - - repositionPapers(); - } - - if (_tweencount < numPagesLoaded - 2 || _tweencount == 0) { - PaperVisible = true; - } - } - - private function reScaleComplete():void { - _tweencount--; - - if (_tweencount == 0) { - if (_displayContainer.numChildren > 0) { - _paperContainer.verticalScrollPosition = 0; - - if (_loadTimer != null) - _loadTimer.start(); - - repositionPapers(); - } - - if (_tweencount < numPagesLoaded - 2 || _tweencount == 0) { - PaperVisible = true; - } - } - } - - public function set Scale(s:String):void { - var diff:Number = _scale - new Number(s); - _scale = new Number(s); - } - - override protected function createChildren():void { - // Call the createChildren() method of the superclass. - super.createChildren(); - this.styleName = "viewerBackground"; - - // Bind events - //_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete); - addEventListener(Event.RESIZE, sizeChanged, false, 0, true); - systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler, false, 0, true); - - // Create a visible container for the swf - _swfContainer = new Canvas(); - _swfContainer.visible = false; - this.addChild(_swfContainer); - - // Create a timer to use for repainting - _repaintTimer = new Timer(5, 0); - _repaintTimer.addEventListener("timer", repaintHandler); - - createDisplayContainer(); - } - - private function onframeenter(event:Event):void { - if (!_dupImageClicked) { - return; - } - - if (_docLoader != null && _docLoader.IsSplit) - return; - - if (event.target.content != null) { - if (event.target.parent is DupImage && - event.target.content.currentFrame != (event.target.parent as DupImage).dupIndex - && _dupImageClicked) { - var np:int = event.target.content.currentFrame; - event.target.content.gotoAndStop((event.target.parent as DupImage).dupIndex); - gotoPage(np); - } - } - } - - private function updComplete(event:Event):void { - if (_scrollToPage > 0) { - _paperContainer.verticalScrollPosition = _pageList[_scrollToPage - 1].y; - //_paperContainer.horizontalScrollPosition = 0; - _scrollToPage = 0; - } - - repaint(); - //repositionPapers(); - } - - private function repaintHandler(e:Event):void { - if (_loadTimer != null) { - _loadTimer.reset(); - _loadTimer.start(); - } - - repositionPapers(); - _repaintTimer.stop(); - _repaintTimer.delay = 5; - } - - private function loadtimer(e:Event):void { - if (_loadTimer != null) - _loadTimer.stop(); - - repositionPapers(); - } - - private function bytesLoaded(event:Event):void { - event.target.loader.loaded = true; - - var bFound:Boolean = false; - - // Split up approach - if (_docLoader != null && _docLoader.IsSplit) { - event.target.loader.loading = false; - - if (event.target.loader.content != null && event.target.loader.content is MovieClip) { - event.target.loader.content.stop(); - } - - for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { - if (_docLoader.LoaderList[i].loading) { - bFound = true; - break; - } - } - - _frameLoadCount = numPages; - _bbusyloading = false; - _displayContainer.visible = true; - - if (!bFound) { - dispatchEvent(new PageLoadedEvent(PageLoadedEvent.PAGE_LOADED, event.target.loader.pageStartIndex)); - - if (_fitPageOnLoad && ((_paperContainer.height / _libMC.height) > 0)) { - FitMode = FitModeEnum.FITHEIGHT; - _fitPageOnLoad = false; - _scrollToPage = 1; - _pscale = _scale; - } - if (_fitWidthOnLoad && ((_paperContainer.width / _libMC.width) > 0)) { - FitMode = FitModeEnum.FITWIDTH; - _fitWidthOnLoad = false; - _scrollToPage = 1; - _pscale = _scale; - } - } - - repaint(); - } else { // normal file approach - if (event.target.loader.content != null) { - event.target.loader.content.stop(); - } - - if (!ProgressiveLoading || (ProgressiveLoading && _libMC.framesLoaded == _libMC.totalFrames)) { - for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { - if (!_docLoader.LoaderList[i].loaded && !(_docLoader.LoaderList[i].parent is DupImage)) { - _docLoader.LoaderList[i].unloadAndStop(true); - _docLoader.LoaderList[i].loadBytes(_inputBytes, StreamUtil.getExecutionContext()); - bFound = true; - break; - } - } - } - - if (!bFound) { - _bbusyloading = false; - if (_fitPageOnLoad) { - FitMode = FitModeEnum.FITHEIGHT; - _fitPageOnLoad = false; - _scrollToPage = 1; - _pscale = _scale; - } - if (_fitWidthOnLoad) { - FitMode = FitModeEnum.FITWIDTH; - _fitWidthOnLoad = false; - _scrollToPage = 1; - _pscale = _scale; - } - _displayContainer.visible = true; - - if (_libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded) { - dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED, numPages)); - _frameLoadCount = _libMC.framesLoaded; - } - } - } - } - - public function repositionPapers():void { - if (_docLoader == null) { - return; - } - - if (_docLoader.LoaderList == null || numPagesLoaded == 0) { - return; - } - - { - var loaderidx:int = 0; - var bFoundFirst:Boolean = false; - var _thumb:Bitmap; - var _thumbData:BitmapData; - var uloaderidx:int = 0; - var p:int = -1; - var pl:int = 0; - - for (var i:int = 0; i < _pageList.length; i++) { - if (ViewMode == ViewModeEnum.TILE) { - if (!bFoundFirst && ((i) * (_pageList[i].height + 6)) >= _paperContainer.verticalScrollPosition) { - bFoundFirst = true; - p = i + 1; - } - } - else if (ViewMode == ViewModeEnum.PORTRAIT) { - if (!bFoundFirst) { - var perH:int = 0; - if (_pageList.length > 1) { - var nowpH:Number = 0; - var nowP:Number = 0; - - while (_paperContainer.verticalScrollPosition + 1 > nowpH && nowP - 1 < _pageList.length) { - nowP++; - - if (nowP < _pageList.length) - nowpH += _pageList[nowP].y - _pageList[nowP - 1].y; - else if (nowP >= _pageList.length) - nowpH += _pageList[_pageList.length - 1].y - _pageList[_pageList.length - 2].y; - } - - if (0 < nowP < 0.5) - p = 1; - else if (nowP >= (_pageList.length - 0.5)) - p = _pageList.length; - else { - p = Math.round(nowP); - if (_pageList.length > p - 1 && _paperContainer.verticalScrollPosition < _pageList[p - 1].y && p != _pageList.length) { - p -= 1; - } - } - bFoundFirst = true; - } - else { - bFoundFirst = true; - p = 1; - } - } - } - - if (p > numPages) - return; - - if (UsingExtViewMode) { - if (currPage != CurrExtViewMode.currentPage) - dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED, CurrExtViewMode.currentPage)); - - p = CurrExtViewMode.currentPage; - currPage = p; - } - - if (p > 0 && p != _currPage) { - currPage = p; - dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED, p)); - } - - if (_libMC != null && checkIsVisible(i)) { - if (_pageList[i].numChildren < 4) { - if (ViewMode == ViewModeEnum.PORTRAIT) { - - if (_docLoader.IsSplit) - uloaderidx = finduloaderIdx(_pageList[i].dupIndex); - - if (!_docLoader.IsSplit || uloaderidx == -1) - uloaderidx = (i == _pageList.length - 1 && loaderidx + 3 < _docLoader.LoaderList.length) ? loaderidx + 3 : (loaderidx < _docLoader.LoaderList.length) ? loaderidx : 0; - - if (!_docLoader.IsSplit) { - if (!_bbusyloading && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0) { - if (numPagesLoaded >= _pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content == null || (_docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].content.framesLoaded < _pageList[i].dupIndex)) { - _bbusyloading = true; - _docLoader.LoaderList[uloaderidx].unloadAndStop(true); - _docLoader.LoaderList[uloaderidx].loadBytes(_inputBytes, StreamUtil.getExecutionContext()); - flash.utils.setTimeout(repositionPapers, 200); - } - } - - if ((i < 2 || _pageList[i].numChildren == 0 || _pageList[i].loadedIndex != _pageList[i].dupIndex || (_pageList[i] != null && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].content.currentFrame != _pageList[i].dupIndex)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null) { - if (numPagesLoaded >= _pageList[i].dupIndex) { - _docLoader.LoaderList[uloaderidx].content.gotoAndStop(_pageList[i].dupIndex); - _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); - _pageList[i].loadedIndex = _pageList[i].dupIndex; - /* - if(_libMC.width*_scale>0&&_libMC.height*_scale>0){ - _libMC.gotoAndStop(_pageList[i].dupIndex); - _thumbData = new BitmapData(_libMC.width*_scale, _libMC.height*_scale, false, 0xFFFFFF); - _thumb = new Bitmap(_thumbData); - _pageList[i].source = _thumb; - _thumbData.draw(_libMC,new Matrix(_scale, 0, 0, _scale),null,null,null,true); - } */ - } - } - } - - if (_docLoader.IsSplit) { - if (!_bbusyloading && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0) { - if (_docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].pageStartIndex != _pageList[i].dupIndex && !_loadTimer.running && !_docLoader.LoaderList[uloaderidx].loading) { - dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING, _pageList[i].dupIndex)); - _pageList[i].resetPage(_libMC.width, _libMC.height, _scale, true); - _docLoader.LoaderList[uloaderidx].unloadAndStop(true); - _docLoader.LoaderList[uloaderidx].loaded = false; - _docLoader.LoaderList[uloaderidx].loading = true; - - Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _pageList[i].dupIndex)), _secretKey, function(e:Event):void { - - try { - _docLoader.LoaderList[uloaderidx].loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); - } catch(err:IOErrorEvent) { - } - - }, onLoadProgress); - - - _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; - repaint(); - - } - } - - if ((_pageList[i].numChildren == 0 || (_pageList[i] != null && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].loaded && _docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex) { - if (numPagesLoaded >= _pageList[i].dupIndex || true) { - if (_docLoader.LoaderList[uloaderidx].parent != null) - _docLoader.LoaderList[uloaderidx].parent.removeChild(_docLoader.LoaderList[uloaderidx]); - - _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); - _pageList[i].loadedIndex = _pageList[i].dupIndex; - - if ((_performSearchOnPageLoad && _pendingSearchPage == _pageList[i].dupIndex) || (SearchMatchAll && prevSearchText.length > 0)) { - _performSearchOnPageLoad = false; - searchTextByService(prevSearchText) - } - } - } - } - - } else if (ViewMode == ViewModeEnum.TILE && _pageList[i].source == null && (numPagesLoaded >= _pageList[i].dupIndex || _docLoader.IsSplit)) { - if (!_docLoader.IsSplit) { - _libMC.gotoAndStop(_pageList[i].dupIndex); - _thumbData = new BitmapData(_libMC.width * _scale, _libMC.height * _scale, false, 0xFFFFFF); - _thumb = new Bitmap(_thumbData); - _pageList[i].source = _thumb; - _thumbData.draw(_libMC.getDocument(), new Matrix(_scale, 0, 0, _scale), null, null, null, true); - } else { - - if (!_bbusyloading && !_loadTimer.running && _docLoader.LoaderList != null && _docLoader.LoaderList.length > 0 && !_docLoader.LoaderList[uloaderidx].loading) { - dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING, _pageList[i].dupIndex)); - _docLoader.LoaderList[uloaderidx].loaded = false; - _docLoader.LoaderList[uloaderidx].loading = true; - _pageList[i].resetPage(_libMC.width, _libMC.height, _scale, true); - - Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _pageList[i].dupIndex)), _secretKey, function(e:Event):void { - try { - _docLoader.LoaderList[uloaderidx].loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); - } catch(err:IOErrorEvent) { - } - }, onLoadProgress); - - _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; - repaint(); - - } - - if (_docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex && _pageList[i].loadedIndex != _pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx].content != null) { - _thumbData = new BitmapData(_docLoader.LoaderList[uloaderidx].width * _scale, _docLoader.LoaderList[uloaderidx].height * _scale, false, 0xFFFFFF); - _thumb = new Bitmap(_thumbData); - _pageList[i].source = _thumb; - _pageList[i].loadedIndex = _pageList[i].dupIndex; - _thumbData.draw(_docLoader.LoaderList[uloaderidx], new Matrix(_scale, 0, 0, _scale), null, null, null, true); - } - } - - if (_pluginList != null) { - for (pl = 0; pl < _pluginList.length; pl++) { - _pluginList[pl].drawSelf(i, _thumbData, _scale); - } - } - } - } - - if (UsingExtViewMode) { - CurrExtViewMode.renderPage(i); - CurrExtViewMode.renderSelection(i, _selectionMarker); - } - - if ((_viewMode == ViewModeEnum.PORTRAIT) && _selectionMarker != null) { - if (i + 1 == searchPageIndex && _selectionMarker.parent != _pageList[i]) { - _pageList[i].addChildAt(_selectionMarker, _pageList[i].numChildren); - } else if (i + 1 == searchPageIndex && _selectionMarker.parent == _pageList[i]) { - _pageList[i].setChildIndex(_selectionMarker, _pageList[i].numChildren - 1); - } - } - - if (_viewMode != ViewModeEnum.TILE) { - if (_pluginList != null) { - for (pl = 0; pl < _pluginList.length; pl++) { - _pluginList[pl].drawSelf(i, _pageList[i], _scale); - } - } - } - - if (_viewMode != ViewModeEnum.TILE && !UsingExtViewMode && _markList[i] != null) { - if (_markList[i].parent != _pageList[i]) { - _pageList[i].addChildAt(_markList[i], _pageList[i].numChildren); - } else { - _pageList[i].setChildIndex(_markList[i], _pageList[i].numChildren - 1); - } - } - - if (UsingExtViewMode && _markList[i] != null) { - CurrExtViewMode.renderMark(_markList[i], i); - } - - loaderidx++; - } else { - if (_pageList[i].numChildren > 0 || _pageList[i].source != null) { - _pageList[i].source = null; - - if (_tweencount == 0) - _pageList[i].resetPage(_libMC.width, _libMC.height, _scale); - else - _pageList[i].removeAllChildren(); - - _pageList[i].loadedIndex = -1; - } - } - } - } - } - - private function padString(_str:String, _n:Number, _pStr:String):String { - var _rtn:String = _str; - if ((_pStr == null) || (_pStr.length < 1)) { - _pStr = " "; - } - - if (_str.length < _n) { - var _s:String = ""; - for (var i:Number = 0; i < (_n - _str.length); i++) { - _s += _pStr; - } - _rtn = _s + _str; - } - - return _rtn; - } - - private function finduloaderIdx(idx:int):int { - for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { - if (_docLoader.LoaderList[i].pageStartIndex == idx) - return i; - } - for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { - if (!checkIsVisible(_docLoader.LoaderList[i].pageStartIndex)) - return i; - } - return -1; - } - - public function repaint():void { - _repaintTimer.reset(); - _repaintTimer.start(); - } - - private function checkIsVisible(pageIndex:int):Boolean { - try { - if (ViewMode == ViewModeEnum.TILE) { - return _pageList[pageIndex].parent.y + _pageList[pageIndex].height >= _paperContainer.verticalScrollPosition && - (_pageList[pageIndex].parent.y - _pageList[pageIndex].height) < (_paperContainer.verticalScrollPosition + _paperContainer.height); - } - else if (!UsingExtViewMode) { - if (_paperContainer.height <= 0) - return false; - - return (_pageList[pageIndex].y + (_pageList[pageIndex].getScaledHeight() + 6)) >= _paperContainer.verticalScrollPosition && - (_pageList[pageIndex].y - (_pageList[pageIndex].getScaledHeight() + 6)) < (_paperContainer.verticalScrollPosition + _paperContainer.height); - } - - if (UsingExtViewMode) - return CurrExtViewMode.checkIsVisible(pageIndex); - - } catch(e:Error) { - return false; - } - return false; - } - - public function createDisplayContainer():void { - - -// if (_skinImgDo != null && _skinImgDo.parent == this) { -// removeChild(_skinImgDo); -// _skinImgDo.removeEventListener(MouseEvent.MOUSE_OVER, skinMouseOver); -// _skinImgDo.removeEventListener(MouseEvent.MOUSE_OUT, skinMouseOut); -// _skinImgDo.removeEventListener(MouseEvent.MOUSE_DOWN, skinMouseDown); -// } - -// _skinImgDo = new Image(); -// _skinImgDo.source = _skinImg; -// _skinImgDo.x = this.width - _skinImg.width - 27; -// _skinImgDo.y = this.height - _skinImg.height - 10; -// _skinImgDo.addEventListener(MouseEvent.MOUSE_OVER, skinMouseOver, false, 0, true); -// _skinImgDo.addEventListener(MouseEvent.MOUSE_OUT, skinMouseOut, false, 0, true); -// _skinImgDo.addEventListener(MouseEvent.MOUSE_DOWN, skinMouseDown, false, 0, true); -// _skinImgDo.buttonMode = true; -// addChild(_skinImgDo); - - // Add the swf to the invisible container. - _swfContainer.removeAllChildren(); - var uic:UIComponent = new UIComponent(); - _swfContainer.addChild(uic); - - if (_docLoader != null && _docLoader.DocumentContainer != null) - uic.addChild(_docLoader.DocumentContainer); - - if (_paperContainer != null && _paperContainer.parent == this) { - removeChild(_paperContainer); - _paperContainer.removeEventListener(FlexEvent.UPDATE_COMPLETE, updComplete); - - _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); - } - - _paperContainer = new ZoomCanvas(); - _paperContainer.percentHeight = 100; - _paperContainer.percentWidth = 100; - _paperContainer.addEventListener(FlexEvent.UPDATE_COMPLETE, updComplete, false, 0, true); - _paperContainer.x = (ViewMode == ViewModeEnum.PORTRAIT || ViewMode == ViewModeEnum.TILE) ? 2.5 : 0; - _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler, false, 0, true); - _paperContainer.setStyle("horizontalGap", 1); - _paperContainer.setStyle("verticalGap", 0); - - //addChildAt(_paperContainer, getChildIndex(_skinImgDo) - 1); - addChild(_paperContainer); - try { - new flash.net.LocalConnection().connect('devaldiGCdummy'); - new flash.net.LocalConnection().connect('devaldiGCdummy'); - } catch (e:*) { - } - - try { - flash.system.System.gc(); - } catch (e:*) { - } - - if (_paperContainer.numChildren > 0) { - _paperContainer.removeAllChildren(); - } - - deleteDisplayContainer(); - - if (_viewMode == ViewModeEnum.TILE) { - _displayContainer = new FlowBox(); - _displayContainer.setStyle("horizontalAlign", "left"); - _paperContainer.horizontalScrollPolicy = "off"; - _scale = 0.243; - _paperContainer.addChild(_displayContainer); - _paperContainer.childrenDoDrag = true; - _initialized = true; - } - else if (UsingExtViewMode) { - _initialized = CurrExtViewMode.initComponent(this); - } - else { - _displayContainer = new FlowVBox(); - _displayContainer.setStyle("horizontalAlign", "center"); - _paperContainer.addChild(_displayContainer); - _paperContainer.childrenDoDrag = true; - _initialized = true; - } - - _displayContainer.verticalScrollPolicy = "off"; - _displayContainer.horizontalScrollPolicy = "off"; - _displayContainer.setStyle("verticalAlign", "center"); - _displayContainer.percentHeight = 100; - _displayContainer.percentWidth = (ViewMode == ViewModeEnum.PORTRAIT) ? 96 : 100; - _displayContainer.useHandCursor = true; - _displayContainer.addEventListener(MouseEvent.ROLL_OVER, displayContainerrolloverHandler, false, 0, true); - _displayContainer.addEventListener(MouseEvent.ROLL_OUT, displayContainerrolloutHandler, false, 0, true); - _displayContainer.addEventListener(MouseEvent.MOUSE_DOWN, displayContainerMouseDownHandler, false, 0, true); - _displayContainer.addEventListener(MouseEvent.MOUSE_UP, displayContainerMouseUpHandler, false, 0, true); - _displayContainer.addEventListener(MouseEvent.DOUBLE_CLICK, displayContainerDoubleClickHandler, false, 0, true); - //_displayContainer.mouseChildren = false; - _displayContainer.doubleClickEnabled = true; - } - - private function displayContainerrolloverHandler(event:MouseEvent):void { - - if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { - if (TextSelectEnabled && CursorsEnabled) { - _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); - } else if (CursorsEnabled) { - resetCursor(); - } - } - } - - private function displayContainerMouseUpHandler(event:MouseEvent):void { - if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { - - if (CursorsEnabled) - CursorManager.removeCursor(_grabbingCursorID); - - if (TextSelectEnabled && CursorsEnabled) { - _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); - } else if (CursorsEnabled && !(event.target is IFlexPaperPluginControl) || (event.target.parent != null && event.target.parent.parent != null && event.target.parent.parent is IFlexPaperPluginControl)) { - resetCursor(); - } - } - } - - private function displayContainerDoubleClickHandler(event:MouseEvent):void { - if (TextSelectEnabled) { - return; - } - if (ViewMode == ViewModeEnum.PORTRAIT) - FitMode = (FitMode == FitModeEnum.FITWIDTH) ? FitModeEnum.FITHEIGHT : FitModeEnum.FITWIDTH; - - if (UsingExtViewMode) - CurrExtViewMode.handleDoubleClick(event); - } - - private function displayContainerMouseDownHandler(event:MouseEvent):void { - if (_viewMode == ViewModeEnum.PORTRAIT || (UsingExtViewMode && CurrExtViewMode.supportsTextSelect)) { - - if (CursorsEnabled) - CursorManager.removeCursor(_grabCursorID); - - if (TextSelectEnabled && CursorsEnabled) { - _grabbingCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); - } else if (CursorsEnabled) { - _grabbingCursorID = CursorManager.setCursor(MenuIcons.GRABBING); - } - } - - if (UsingExtViewMode) - CurrExtViewMode.handleMouseDown(event); - } - - private function displayContainerrolloutHandler(event:Event):void { - if (CursorsEnabled) - CursorManager.removeAllCursors(); - } - - private function wheelHandler(evt:MouseEvent):void { - _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); - - var t:Timer = new Timer(1, 1); - t.addEventListener("timer", addMouseScrollListener, false, 0, true); - t.start(); - - _paperContainer.dispatchEvent(evt.clone()); - } - - private function addMouseScrollListener(e:Event):void { - _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler, false, 0, true); - } - - private function keyboardHandler(event:KeyboardEvent):void { - if (event.keyCode == Keyboard.DOWN) { - _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 10; - } - if (event.keyCode == Keyboard.UP) { - _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 10; - } - if (event.keyCode == Keyboard.PAGE_DOWN) { - _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 300; - } - if (event.keyCode == Keyboard.PAGE_UP) { - _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 300; - } - if (event.keyCode == Keyboard.HOME) { - _paperContainer.verticalScrollPosition = 0; - } - if (event.keyCode == Keyboard.END) { - _paperContainer.verticalScrollPosition = _paperContainer.maxVerticalScrollPosition; - } - } - - private function sizeChanged(evt:Event):void { -// _skinImgDo.source = _skinImg; -// _skinImgDo.x = this.width - _skinImg.width - 27; -// _skinImgDo.y = this.height - _skinImg.height - 10; - } - - private function skinMouseOver(evt:MouseEvent):void { -// _skinImgDo.addChild(_skinImgc); - } - - private function skinMouseOut(evt:MouseEvent):void { -// if (_skinImgc.parent == _skinImgDo) { -// _skinImgDo.removeChild(_skinImgc); -// } - } - - private function skinMouseDown(evt:MouseEvent):void { - //dispatchEvent(new Event("onLogoClicked")); - } - - override protected function commitProperties():void { - super.commitProperties(); - - if (_swfFileChanged && _swfFile != null && _swfFile.length > 0) { // handler for when the Swf file has changed. - - dispatchEvent(new Event("onDocumentLoading")); - - _swfFileChanged = false; - } - } - - private function resizeMc(mc:MovieClip, maxW:Number, maxH:Number = 0, constrainProportions:Boolean = true):void { - maxH = maxH == 0 ? maxW : maxH; - mc.width = maxW; - mc.height = maxH; - if (constrainProportions) { - mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; - } - } - - private function onLoadProgress(event:ProgressEvent):void { - var e:ProgressEvent = new ProgressEvent("onLoadingProgress") - e.bytesTotal = event.bytesTotal; - e.bytesLoaded = event.bytesLoaded; - dispatchEvent(e); - } - - private function onDocumentLoadedErrorHandler(event:Event):void { - dispatchEvent(event); - } - - - private function swfComplete(event:SwfLoadedEvent):void { - if (!ProgressiveLoading) { - - try { - if (event.swfObject.content != null && (event.swfObject.content is MovieClip || event.swfObject.content is Bitmap)) { - _libMC = new SwfDocument(event.swfObject.content as DisplayObject); - } - DupImage.paperSource = _libMC.getDocument(); - } catch(e:Error) { - - if (!_docLoader.Resigned) { - _docLoader.signFileHeader(_docLoader.InputBytes); - return; - } - } - - if (!_secretKey && (_libMC == null || (event.swfObject != null && event.swfObject.content != null && event.swfObject.content is AVM1Movie)) && !_docLoader.Resigned) { - - _docLoader.signFileHeader(_docLoader.InputBytes); - - return; - } - - _inputBytes = _docLoader.InputBytes; - - if (_libMC.height > 0 && _docLoader.LoaderList == null) { - createLoaderList(); - } - - if (!_docLoader.IsSplit) - numPages = _libMC.totalFrames; - - _swfLoaded = true - _libMC.getDocument().cacheAsBitmap = true; - _libMC.getDocument().opaqueBackground = 0xFFFFFF; - reCreateAllPages(); - - _bbusyloading = false; - repositionPapers(); - //dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED,numPages)); - } else { - if (event.swfObject.content != null) { - var mobj:Object = event.swfObject.content; - var firstLoad:Boolean = false; - - if (mobj is AVM1Movie || _loaderptr != null) { - _inputBytes = _docLoader.InputBytes; - - if (_loaderptr == null) { - _docLoader.postProcessBytes(_inputBytes); - _loaderptr = new Loader(); - _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete, false, 0, true); - } - - _docLoader.signFileHeader(_inputBytes, _loaderptr); - _loaderptr.unloadAndStop(true); - _loaderptr.loadBytes(_inputBytes, StreamUtil.getExecutionContext()); - } - - if (mobj is MovieClip) { - _libMC = new SwfDocument(mobj as MovieClip); - _libMC.getDocument().cacheAsBitmap = true; - _libMC.getDocument().opaqueBackground = 0xFFFFFF; - - if (_libMC.height > 0 && _docLoader.LoaderList == null) { - createLoaderList(); - } - DupImage.paperSource = _libMC.getDocument(); - - if (!_docLoader.IsSplit) - numPages = _libMC.totalFrames; - - firstLoad = _pageList == null || (_pageList.length == 0 && numPages > 0); - - if (_loaderptr == null) { - _inputBytes = _docLoader.InputBytes; - } else { - _inputBytes = _loaderptr.contentLoaderInfo.bytes; - } - - if (_libMC.framesLoaded > 0) - addInLoadedPages(); - - flash.utils.setTimeout(function():void { - try { - var bDocLoaded:Boolean = (_libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded); - - if (_libMC.framesLoaded > _frameLoadCount) { - repositionPapers(); - if (_docLoader.LoaderList.length > 0 && _viewMode == ViewModeEnum.PORTRAIT) { - _bbusyloading = true; - _docLoader.LoaderList[_docLoader.LoaderList.length - 1].unloadAndStop(true); - _docLoader.LoaderList[_docLoader.LoaderList.length - 1].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); - } - _frameLoadCount = _libMC.framesLoaded; - } - - if (bDocLoaded) - dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED, numPages)); - } catch (e:*) { - } - }, 500); - - - _bbusyloading = false; - _swfLoaded = true - } - } - } - } - - private function deleteDisplayContainer():void { - if (_displayContainer != null) { - _displayContainer.removeAllChildren(); - _displayContainer.removeEventListener(MouseEvent.ROLL_OVER, displayContainerrolloverHandler); - _displayContainer.removeEventListener(MouseEvent.ROLL_OUT, displayContainerrolloutHandler); - _displayContainer.removeEventListener(MouseEvent.MOUSE_DOWN, displayContainerMouseDownHandler); - _displayContainer.removeEventListener(MouseEvent.MOUSE_UP, displayContainerMouseUpHandler); - _displayContainer.removeEventListener(MouseEvent.DOUBLE_CLICK, displayContainerDoubleClickHandler); - } - } - - private function deleteLoaderList():void { - if (_docLoader == null) { - return; - } - if (_docLoader.LoaderList != null) { - for (var i:int = 0; i < _docLoader.LoaderList.length; i++) { - if (_docLoader.LoaderList[i].parent != null) { - _docLoader.LoaderList[i].parent.removeChild(_docLoader.LoaderList[i]); - } - - if (_docLoader.LoaderList[i].contentLoaderInfo != null) { - _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(Event.COMPLETE, bytesLoaded); - _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, docLoaderIOErrorListener); - } - - _docLoader.LoaderList[i].removeEventListener(Event.ENTER_FRAME, onframeenter); - _docLoader.LoaderList[i].unloadAndStop(true); - - delete(_docLoader.LoaderList[i]); - _docLoader.LoaderList[i] = null; - } - } - - _docLoader.LoaderList = null; - } - - public function deleteSelectionMarker():void { - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - - _selectionMarker = null; - } - } - - private function deleteLibMC():void { - if (_libMC != null) { - if (_libMC.parent != null && _libMC.parent is Loader) { - (_libMC.parent as Loader).unloadAndStop(true); - } - - _libMC = null; - } - } - - private function deleteLoaderPtr():void { - if (_loaderptr != null) { - if (_loaderptr.parent != null) { - _loaderptr.removeChild(_loaderptr); - } - - if (_loaderptr.contentLoaderInfo != null) { - _loaderptr.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); - } - - _loaderptr.unloadAndStop(true); - _loaderptr = null; - } - } - - private function clearPlugins():void { - if (_pluginList == null) { - return; - } - - for (var pl:int = 0; pl < _pluginList.length; pl++) { - _pluginList[pl].clear(); - } - } - - private function deletePageList():void { - if (_pageList != null) { - for (var pl:int = 0; pl < _pageList.length; pl++) { - - _pageList[pl].removeEventListener(MouseEvent.MOUSE_OVER, dupImageMoverHandler); - _pageList[pl].removeEventListener(MouseEvent.MOUSE_OUT, dupImageMoutHandler); - _pageList[pl].removeEventListener(MouseEvent.CLICK, dupImageClickHandler); - _pageList[pl].removeEventListener(MouseEvent.MOUSE_DOWN, textSelectorMouseDownHandler); - - if (_pageList[pl].parent != null) { - _pageList[pl].removeAllChildren(); - _pageList[pl].source = null; - _pageList[pl].parent.removeChild(_pageList[pl]); - } - - delete(_pageList[pl]); - _pageList[pl] = null; - } - } - - DupImage.paperSource = null; - - _pageList = null; - } - - private function deleteFLoader():void { - if (_docLoader != null) { - _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); - _docLoader.resetURLStream(); - } - - /*if(_loader!=null){ - _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); - _loader.unloadAndStop(true); - _loader = null; - }*/ - - //_docLoader = null; - - /*_loader = new Loader(); - if(!_loader.contentLoaderInfo.hasEventListener(Event.COMPLETE)) - _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete,false,0,true);*/ - } - - public function addInLoadedPages(recreate:Boolean = false):void { - if (recreate) { - _displayContainer.removeAllChildren(); - deletePageList(); - } - - if (_pageList == null || (_pageList != null && _pageList.length != numPages)) { - _pageList = new Array(numPages); - if (_markList == null) { - _markList = new Array(numPages); - } - - _displayContainer.visible = false; - _libMC.stop(); - - var w:Number = 0; - var h:Number = 0; - _libMC.gotoAndStop(1); - w = _libMC.width; - h = _libMC.height; - - for (var i:int = 0; i < numPages; i++) { - _libMC.gotoAndStop(i + 1); - createPaper(i + 1, (_libMC.width > 0) ? _libMC.width : w, (_libMC.height > 0) ? _libMC.height : h); - } - - addPages(); - - if (_pluginList != null) { - for (var p:int = 0; p < _pluginList.length; p++) { - _pluginList[p].init(); - } - } - - //if(_fitWidthOnLoad){_scale = getFitWidthFactor();} - //if(_fitPageOnLoad){_scale = getFitHeightFactor();} - } - - flash.utils.setTimeout(repositionPapers, 500); - } - - public function reCreateAllPages():void { - if (!_swfLoaded) { - return; - } - - _displayContainer.visible = false; - _displayContainer.removeAllChildren(); - - deletePageList(); - _pageList = new Array(numPages); - if (_markList == null) { - _markList = new Array(numPages); - } - - if (_pluginList != null) { - for (var p:int = 0; p < _pluginList.length; p++) { - _pluginList[p].init(); - } - } - - _libMC.stop(); - - var w:Number = 0; - var h:Number = 0; - _libMC.gotoAndStop(1); - w = _libMC.width; - h = _libMC.height; - - for (var i:int = 0; i < numPages; i++) { - _libMC.gotoAndStop(i + 1); - createPaper(i + 1, (_libMC.width > 0) ? _libMC.width : w, (_libMC.height > 0) ? _libMC.height : h); - } - - addPages(); - - // kick off the first page to load - if (!_docLoader.IsSplit) { - if (_docLoader.LoaderList.length > 0) { - _bbusyloading = true; - _docLoader.LoaderList[0].unloadAndStop(true); - _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); - } - } else { - if (_docLoader.LoaderList.length > 0 && (_viewMode == ViewModeEnum.PORTRAIT) && _libMC.loaderInfo != null && _libMC.loaderInfo.bytes != null) { - _bbusyloading = true; - _docLoader.LoaderList[0].pageStartIndex = 1; - _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes, StreamUtil.getExecutionContext()); - } - } - - if (_docLoader.LoaderList.length > 0 && UsingExtViewMode) { - CurrExtViewMode.initOnLoading(); - } - } - - private function createLoaderList():void { - _docLoader.LoaderList = new Array(Math.round(getCalculatedHeight(_paperContainer) / (_libMC.height * _minZoomSize)) + (_docLoader.IsSplit) ? 5 : 1); - - if (UsingExtViewMode && CurrExtViewMode.loaderListLength > _docLoader.LoaderList.length) - _docLoader.LoaderList = new Array(CurrExtViewMode.loaderListLength); - - { - for (var li:int = 0; li < _docLoader.LoaderList.length; li++) { - _docLoader.LoaderList[li] = new DupLoader(); - _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(Event.COMPLETE, bytesLoaded, false, 0, true); - _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, docLoaderIOErrorListener); - _docLoader.LoaderList[li].addEventListener(Event.ENTER_FRAME, onframeenter, false, 0, true); - } - } - } - - private function docLoaderIOErrorListener(e:IOErrorEvent):void { - if (_docLoader != null && _docLoader.IsSplit) { - dispatchEvent(new ErrorLoadingPageEvent(ErrorLoadingPageEvent.ERROR_LOADING_PAGE, e.target.pageStartIndex)); - } - } - - private function getCalculatedHeight(obj:DisplayObject):Number { - var pHeight:Number = 0; - var oPercHeight:Number = 0; - - pHeight = obj.height; - if (pHeight > 0) { - return pHeight; - } - if ((obj as Container).percentHeight > 0) { - oPercHeight = (obj as Container).percentHeight; - } - - while (obj.parent != null) { - if (obj.parent.height > 0) { - pHeight = obj.parent.height * (oPercHeight / 100); - break; - } - obj = obj.parent; - } - - return pHeight; - } - - public var snap:TextSnapshot; - private var searchIndex:int = -1; - private var searchPageIndex:int = -1; - private var _selectionMarker:ShapeMarker; - private var prevSearchText:String = ""; - private var prevYsave:Number = -1; - private var _markList:Array; - private var prevSearchIndexList:Array; - - public function get SearchPageIndex():int { - return searchPageIndex; - } - - public function set SearchPageIndex(s:int):void { - searchPageIndex = s; - } - - private var _searchExtracts:Array; - - public function searchTextByService(text:String):void { - if (prevSearchText != text) { - _searchExtracts = new Array(numPages); - searchPageIndex = -1; - prevSearchText = text; - searchIndex = -1; - prevSearchIndexList = new Array(); - } - - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - } - - if (searchPageIndex == -1) { - searchPageIndex = currPage; - } - - if (_searchExtracts[searchPageIndex - 1] == null && searchPageIndex != currPage) { - var serve:HTTPService = new HTTPService(); - var url = SearchServiceUrl; - url = TextMapUtil.StringReplaceAll(url, "[page]", searchPageIndex.toString()) - url = TextMapUtil.StringReplaceAll(url, "[searchterm]", text) - url = encodeURI(url); - - serve.method = "GET"; - serve.url = url; - serve.resultFormat = "text"; - serve.addEventListener("result", searchByServiceResult); - serve.addEventListener(FaultEvent.FAULT, searchByServiceFault); - serve.send(); - } else { // perform actual search - if ((_searchExtracts[searchPageIndex - 1] != null && _searchExtracts[searchPageIndex - 1].length > 0 && Number(_searchExtracts[searchPageIndex - 1]) >= 0) || searchPageIndex == currPage) { - if (searchPageIndex != currPage) { - _performSearchOnPageLoad = true; - _pendingSearchPage = searchPageIndex; - gotoPage(searchPageIndex); - } - else { - snap = _pageList[searchPageIndex - 1].textSnapshot; - searchIndex = snap.findText((searchIndex == -1 ? 0 : searchIndex), adjustSearchTerm(text), false); - var tri:Array; - - if (searchIndex > 0) { // found a new match - _selectionMarker = new ShapeMarker(); - _selectionMarker.graphics.beginFill(0x0095f7, 0.3); - - tri = snap.getTextRunInfo(searchIndex, searchIndex + text.length - 1); - if (tri.length > 0) { - prevYsave = tri[0].matrix_ty; - drawCurrentSelection(0x0095f7, _selectionMarker, tri); - } - - if (prevYsave > 0) { - _selectionMarker.graphics.endFill(); - _adjGotoPage = (ViewMode == ViewModeEnum.PORTRAIT) ? (prevYsave) * _scale - 50 : 0; - gotoPage(searchPageIndex); - } - - searchIndex = searchIndex + text.length; - } else { - if (searchPageIndex + 1 <= numPages) { - searchPageIndex++; - searchIndex = -1; - - searchTextByService(prevSearchText); - } else { - dispatchEvent(new Event("onNoMoreSearchResults")); - searchPageIndex = 1; - } - } - } - } else { - if (searchPageIndex + 1 <= numPages) { - searchPageIndex++; - searchIndex = -1; - - searchTextByService(prevSearchText); - } else { - dispatchEvent(new Event("onNoMoreSearchResults")); - searchPageIndex = 1; - } - } - } - } - - private function searchByServiceResult(evt:ResultEvent):void { - var textExtract:String = evt.result.toString(); - _searchExtracts[searchPageIndex - 1] = textExtract; - - searchTextByService(prevSearchText); - } - - private function searchByServiceFault(evt:FaultEvent):void { - dispatchEvent(new Event("onNoMoreSearchResults")); - } - - public function searchText(text:String, clearmarklist:Boolean = true):void { - if (text == null) { - return; - } - - if (text.length == 0) { - return; - } - text = text.toLowerCase(); - - if (_docLoader.IsSplit && SearchServiceUrl != null && SearchServiceUrl.length > 0) - return searchTextByService(text); - - var tri:Array; - - if (prevSearchText != text) { - searchIndex = -1; - prevSearchIndexList = new Array(); - prevSearchText = text; - - if (SearchMatchAll) { - var spi:int = 1; - var si:int = -1; - - if (clearmarklist) { - if (_markList != null) { - for (var i:int = 0; i < _markList.length; i++) { - if (_markList[i] != null && _markList[i].parent != null) { - _markList[i].parent.removeChild(_markList[i]); - } - } - } - - _markList = new Array(numPages); - } - - if (text.indexOf("|") > 0) { - var phrases:Array = text.split("|"); - for (var sf:int = 0; sf < phrases.length; sf++) { - searchText(phrases[sf], false); - } - - return; - } - - while ((spi - 1) < _libMC.framesLoaded) { - _libMC.gotoAndStop(spi); - snap = _libMC.textSnapshot; - si = snap.findText((si == -1 ? 0 : si), adjustSearchTerm(text), false); - //si = snap.getText(0,snap.charCount).toLowerCase().indexOf(text,(si==-1?0:si)); - //si = searchString(snap.getText(0,snap.charCount),text,si); - - if (si > 0) { - var sm:ShapeMarker = new ShapeMarker(); - sm.PageIndex = spi; - - tri = snap.getTextRunInfo(si, si + text.length - 1); - drawCurrentSelection(0x0095f7, sm, tri, false, 0.25); - - - if (_markList[spi - 1] == null) { - _markList[spi - 1] = new UIComponent(); - } - - _markList[spi - 1].addChild(sm); - - } - - if (si == -1) - spi++; - else - si++; - } - } - } - - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - } - - // start searching from the current page - if (searchPageIndex == -1) { - searchPageIndex = currPage; - } else { - var sio:Object = new Object(); - sio.searchIndex = searchIndex; - sio.searchPageIndex = searchPageIndex; - - prevSearchIndexList.push(sio); - searchIndex = searchIndex + text.length; - } - - _libMC.gotoAndStop(searchPageIndex); - - while ((searchPageIndex - 1) < numPagesLoaded) { - snap = _libMC.textSnapshot; - searchIndex = snap.findText((searchIndex == -1 ? 0 : searchIndex), adjustSearchTerm(text), false); - //searchIndex = TextMapUtil.checkUnicodeIntegrity(snap.getText(0,snap.charCount),text,_libMC).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); - //searchIndex = snap.getText(0,snap.charCount).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); - //searchIndex = searchString(snap.getText(0,snap.charCount),text,searchIndex); - - if (searchIndex > 0) { // found a new match - _selectionMarker = new ShapeMarker(); - _selectionMarker.graphics.beginFill(0x0095f7, 0.3); - - tri = snap.getTextRunInfo(searchIndex, searchIndex + text.length - 1); - if (tri.length > 0) { - prevYsave = tri[0].matrix_ty; - drawCurrentSelection(0x0095f7, _selectionMarker, tri); - } - - if (prevYsave > 0) { - _selectionMarker.graphics.endFill(); - _adjGotoPage = (ViewMode == ViewModeEnum.PORTRAIT) ? (prevYsave) * _scale - 50 : 0; - gotoPage(searchPageIndex); - break; - } - - } - - searchPageIndex++; - searchIndex = -1; - _libMC.gotoAndStop(searchPageIndex); - } - - if (searchIndex == -1) { // searched the end of the doc. - dispatchEvent(new Event("onNoMoreSearchResults")); - searchPageIndex = 1; - } - } - - public function nextSearchMatch(s:String):void { - if (s != prevSearchText) { - searchText(s); - } else { - searchIndex = searchIndex + prevSearchText.length; - searchText(prevSearchText); - } - } - - public function prevSearchMatch():void { - if (prevSearchText != null && prevSearchText.length > 0) { - prevSearchIndexList.pop(); - - var sio:Object = prevSearchIndexList.pop(); - if (sio != null) { - searchIndex = sio.searchIndex - 1; - searchPageIndex = sio.searchPageIndex; - searchText(prevSearchText); - } else { - searchIndex = 0; - searchPageIndex = 1; - searchText(prevSearchText); - } - } - } - - private function adjustSearchTerm(searchtxt:String):String { - if (ResourceManager.getInstance().localeChain[0] == 'he_IL') { - searchtxt = reverseString(searchtxt); - } - - return searchtxt; - } - - private function reverseString(string:String):String { - var reversed:String = new String(); - for (var i:int = string.length - 1; i >= 0; i--) - reversed += string.charAt(i); - return reversed; - } - - public function highlight(url:String):void { - var serve:HTTPService = new HTTPService(); - serve.method = "GET"; - serve.url = url; - serve.resultFormat = "e4x" - serve.addEventListener("result", highlightResult); - serve.send(); - } - - private function highlightResult(evt:ResultEvent):void { - try { - - for (var i:int = 0; i < _markList.length; i++) { - if (_markList[i] != null && _markList[i].parent != null) { - _markList[i].parent.removeChild(_markList[i]); - } - } - - _markList = new Array(numPages); - - var highlightXML:XML = new XML(evt.result); - var pg:Number = 0; - var pos:Number = -1; - var len:Number = -1; - var tri:Array; - var color:uint = 0x0095f7; - var text:String; - color = uint("0x" + String(highlightXML.Body.@color).substring(1, String(highlightXML.Body.@color).length)); - - for each (var item:XML in highlightXML.Body.Highlight.loc) { - pg = Number(item.@pg); - pos = Number(item.@pos); - len = Number(item.@len); - - _libMC.gotoAndStop(pg + 1); - snap = _libMC.textSnapshot; - - var sm:ShapeMarker = new ShapeMarker(); - sm.PageIndex = pg + 1; - - text = snap.getText(0, pos, false); - - for (var ci:int = 0; ci < text.length; ci++) { - if (text.charCodeAt(ci) > 10000) { - pos = pos - 1; - } - } - - tri = snap.getTextRunInfo(pos, pos + len); - - drawCurrentSelection(color, sm, tri, false, 0.25); - - if (_markList[pg] == null) { - _markList[pg] = new UIComponent(); - } - - _markList[pg].addChild(sm); - } - - repositionPapers(); - - } catch (e:*) { - } - } - - private function createPaper(index:int, w:Number, h:Number):void { - var di:DupImage = new DupImage(); - di.scaleX = di.scaleY = _scale; - di.dupIndex = index; - di.width = w; - di.height = h; - di.init(); - di.NeedsFitting = DocLoader.IsSplit; - di.RoleModelHeight = _libMC.height; - di.RoleModelWidth = _libMC.width; - //di.mouseChildren = false; - di.addEventListener(MouseEvent.MOUSE_OVER, dupImageMoverHandler, false, 0, true); - di.addEventListener(MouseEvent.MOUSE_OUT, dupImageMoutHandler, false, 0, true); - di.addEventListener(MouseEvent.CLICK, dupImageClickHandler, false, 0, true); - di.addEventListener(MouseEvent.MOUSE_DOWN, textSelectorMouseDownHandler, false, 0, true); - - if (_pluginList != null) - for (var pl:int = 0; pl < _pluginList.length; pl++) - _pluginList[pl].bindPaperEventHandler(di); - - _pageList[index - 1] = di; - _pageList[index - 1].resetPage(w, h, _scale); - } - - private function textSelectorMouseDownHandler(event:MouseEvent):void { - if (!TextSelectEnabled) { - return; - } - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - _selectionMarker = null; - } - - try { - if (!(event.target.content is MovieClip)) { - if (!(event.target is MovieClip)) { - return; - } else { - _selectionMc = (event.target as MovieClip); - } - } else { - _selectionMc = (event.target.content as MovieClip); - } - } catch (e:*) { - return; - } - - _currentlySelectedText = ""; - _firstHitIndex = -1; - _lastHitIndex = -1; - _currentSelectionPage = -1; - snap = _selectionMc.textSnapshot; - - systemManager.addEventListener( - MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true, 0, true); - - systemManager.addEventListener( - MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true, 0, true); - - systemManager.stage.removeEventListener( - Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); - } - - private var _firstHitIndex:int = -1; - private var _lastHitIndex:int = -1; - private var _currentlySelectedText:String = ""; - private var _tri:Array; - private var _currentSelectionPage:int = -1; - private var _selectionMc:MovieClip - private var _selecting:Boolean = false; - public static var DefaultMarkerColor:uint = 0xb5deff; - private var _markerColor:uint = 0xb5deff; - public static var DefaultSelectionColor:uint = 0x0095f7; - private var _selectionColor:uint = 0x0095f7; - - public function get MarkerColor():uint { - return _markerColor; - } - - public function set MarkerColor(c:uint):void { - _markerColor = c; - } - - public function get SelectionColor():uint { - return _selectionColor; - } - - public function set SelectionColor(c:uint):void { - _selectionColor = c; - } - - public function get CurrentSelectionPage():int { - return _currentSelectionPage; - } - - public function get FirstHitIndex():int { - return _firstHitIndex; - } - - public function get LastHitIndex():int { - return _lastHitIndex; - } - - public function get TextRunInfo():Array { - return _tri; - } - - public function set TextRunInfo(a:Array):void { - _tri = a; - } - - private function textSelectorMoveHandler(event:MouseEvent):void { - event.stopImmediatePropagation(); - - var hitIndex:int = snap.hitTestTextNearPos(event.target.parent.mouseX, event.target.parent.mouseY, 10) + ((_firstHitIndex == -1) ? 0 : 1); - - if (hitIndex == _lastHitIndex || hitIndex < 0) { - return; - } - if (!(event.target is DupLoader)) { - return; - } - - if (_firstHitIndex == -1) { - _firstHitIndex = hitIndex; - } - - if (_docLoader.IsSplit) - _currentSelectionPage = (_selectionMc.parent as DupLoader).pageStartIndex; - else - _currentSelectionPage = _selectionMc.currentFrame; - - snap.setSelectColor(_markerColor); - snap.setSelected(0, snap.charCount, false); - - if (_firstHitIndex <= hitIndex) { - snap.setSelected(_firstHitIndex, hitIndex, true); - } else { - snap.setSelected(hitIndex, _firstHitIndex, true); - } - - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - } - - if (_docLoader.IsSplit) - searchPageIndex = (_selectionMc.parent as DupLoader).pageStartIndex; - else - searchPageIndex = _selectionMc.currentFrame; - - _lastHitIndex = hitIndex; - } - - public function drawCurrentSelection(color:uint, shape:Sprite, tri:Array, strikeout:Boolean = false, alpha:Number = 0.3):void { - var ly:Number = -1; - var li:int; - var lx:int; - var miny:int = -1; - var minx:int = -1; - var maxy:int = -1; - var maxx:int = -1; - snap.setSelected(1, snap.charCount, false); - - shape.graphics.beginFill(color, (strikeout) ? 0.5 : alpha); - var rect_commands:Vector.; - rect_commands = new Vector.((tri.length) * 5, true); - - var rect_coords:Vector.; - rect_coords = new Vector.((tri.length) * 10, true); - - for (var i:int = 0; i < tri.length - 1; i++) { - if (miny == -1 || miny > tri[i].corner1y) { - miny = tri[i].corner1y; - } - if (minx == -1 || minx > tri[li].corner3x) { - minx = tri[li].corner3x; - } - if (maxy == -1 || maxy < tri[i].corner3y) { - maxy = tri[i].corner3y; - } - if (maxx == -1 || maxx < tri[i].corner1x) { - maxx = tri[i].corner1x; - } - - if (ly == -1) { - ly = tri[i].corner1y; - li = 0; - } - - rect_commands[i * 5] = 1; - rect_commands[i * 5 + 1] = 2; - rect_commands[i * 5 + 2] = 2; - rect_commands[i * 5 + 3] = 2; - rect_commands[i * 5 + 4] = 2; - - rect_coords[i * 10] = tri[li].corner3x; - rect_coords[i * 10 + 1] = tri[i].corner1y + (strikeout ? (tri[i].corner3y - tri[i].corner1y) / 3 : 0); - - rect_coords[i * 10 + 5] = rect_coords[i * 10 + 1] + (tri[i].corner3y - tri[i].corner1y) / ((strikeout) ? 5 : 1); //h - - if (i != tri.length - 2 && tri[i].corner1x > tri[li].corner3x) - rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[i].corner1x - tri[li].corner3x; - else if (i == tri.length - 2 && tri[i + 1].corner1x > tri[li].corner3x) - rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[i + 1].corner1x - tri[li].corner3x; - else if (i == tri.length - 2 && tri[i + 1].corner1x < tri[li].corner3x) { - rect_coords[i * 10 + 2] = rect_coords[i * 10] + tri[li].corner1x - tri[li].corner3x; - rect_coords[i * 10] = tri[li].corner3x; - - /* add an extra struct for the last char*/ - rect_commands[(i + 1) * 5] = 1; - rect_commands[(i + 1) * 5 + 1] = 2; - rect_commands[(i + 1) * 5 + 2] = 2; - rect_commands[(i + 1) * 5 + 3] = 2; - rect_commands[(i + 1) * 5 + 4] = 2; - - rect_coords[(i + 1) * 10] = tri[(i + 1)].corner3x; - rect_coords[(i + 1) * 10 + 1] = tri[(i + 1)].corner1y; - rect_coords[(i + 1) * 10 + 2] = rect_coords[(i + 1) * 10] + tri[i + 1].corner1x - tri[i + 1].corner3x; - rect_coords[(i + 1) * 10 + 3] = rect_coords[(i + 1) * 10 + 1]; - rect_coords[(i + 1) * 10 + 4] = rect_coords[(i + 1) * 10 + 2]; - rect_coords[(i + 1) * 10 + 5] = rect_coords[(i + 1) * 10 + 1] + tri[i + 1].corner3y - tri[i + 1].corner1y; - rect_coords[(i + 1) * 10 + 6] = rect_coords[(i + 1) * 10]; - rect_coords[(i + 1) * 10 + 7] = rect_coords[(i + 1) * 10 + 5]; - rect_coords[(i + 1) * 10 + 8] = rect_coords[(i + 1) * 10]; - rect_coords[(i + 1) * 10 + 9] = rect_coords[(i + 1) * 10 + 1]; - } - - rect_coords[i * 10 + 3] = rect_coords[i * 10 + 1]; - rect_coords[i * 10 + 4] = rect_coords[i * 10 + 2]; - rect_coords[i * 10 + 6] = rect_coords[i * 10]; - rect_coords[i * 10 + 7] = rect_coords[i * 10 + 5]; - rect_coords[i * 10 + 8] = rect_coords[i * 10]; - rect_coords[i * 10 + 9] = rect_coords[i * 10 + 1]; - - ly = tri[i + 1].corner1y; - lx = tri[i + 1].corner3x; - li = i + 1; - } - shape.graphics.drawPath(rect_commands, rect_coords, "nonZero"); - shape.graphics.endFill(); - - // draw a transparent box covering the whole area to increase hitTest accuracy on mousedown - shape.graphics.beginFill(0xffffff, 0); - shape.graphics.drawRect(minx, miny, maxx - minx, maxy - miny); - shape.graphics.endFill(); - } - - private function textSelectorMouseUpHandler(event:MouseEvent):void { - stopSelecting(); - } - - private function textSelectorMouseLeaveHandler(event:MouseEvent):void { - stopSelecting(); - } - - private function stopSelecting():void { - systemManager.removeEventListener( - MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true); - - systemManager.removeEventListener( - MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true); - - systemManager.stage.removeEventListener( - Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); - - var rev:int; - if (_firstHitIndex > _lastHitIndex) { - rev = _firstHitIndex; - _firstHitIndex = _lastHitIndex; - _lastHitIndex = rev; - } - - //var totaltext:String = snap.getText(0,snap.charCount,false); - - if (_firstHitIndex >= 0 && _lastHitIndex > 0) - _currentlySelectedText = snap.getText(_firstHitIndex, _lastHitIndex - 1, false); - else - _currentlySelectedText = ""; - - - if (_currentlySelectedText.length == 0 && _firstHitIndex >= 0 && _lastHitIndex > 0) { - _currentlySelectedText = snap.getText(_firstHitIndex, _lastHitIndex - 1, true); - } - - _currentlySelectedText = TextMapUtil.checkUnicodeIntegrity(_currentlySelectedText, null, _libMC); - - /* trace(_currentlySelectedText.charCodeAt(0)+"|"); - trace(_currentlySelectedText.charCodeAt(1)+"|"); - trace(_currentlySelectedText.charCodeAt(2)+"|"); - trace(_currentlySelectedText.charCodeAt(3)+"|"); - */ - - - _tri = snap.getTextRunInfo(_firstHitIndex, _lastHitIndex - 1); - - if (_currentSelectionPage > 0) { - if (_selectionMarker != null && _selectionMarker.parent != null) { - _selectionMarker.parent.removeChild(_selectionMarker); - } - - _selectionMarker = new ShapeMarker(); - _selectionMarker.PageIndex = _currentSelectionPage; - drawCurrentSelection(_selectionColor, _selectionMarker, _tri); - snap.setSelected(_firstHitIndex, _lastHitIndex, false); - _pageList[_currentSelectionPage - 1].addChildAt(_selectionMarker, _pageList[_selectionMc.currentFrame - 1].numChildren); - } - - dispatchEvent(new SelectionCreatedEvent(SelectionCreatedEvent.SELECTION_CREATED, _currentlySelectedText)); - - _selectionMc = null; - } - - private function dupImageClickHandler(event:MouseEvent):void { - stage.stageFocusRect = false; - stage.focus = event.target as InteractiveObject; - - if ((_viewMode == ViewModeEnum.TILE) && event.target != null && event.target is DupImage) { - ViewMode = 'Portrait'; - _scrollToPage = (event.target as DupImage).dupIndex; - } else { - _dupImageClicked = true; - var t:Timer = new Timer(100, 1); - t.addEventListener("timer", resetClickHandler, false, 0, true); - t.start(); - - if (event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("http") >= 0) { - dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, - (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("http")))); - } else if (event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("url:") >= 0) { - dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, - (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("url:")))); - } - - } - } - - private function resetClickHandler(e:Event):void { - _dupImageClicked = false; - } - - private function dupImageMoverHandler(event:MouseEvent):void { - - if (_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage) { - addGlowFilter(event.target as DupImage); - } else { - if (event.target is flash.display.SimpleButton || event.target is mx.core.SpriteAsset || (event.target is IFlexPaperPluginControl) || (event.target.parent != null && event.target.parent.parent != null && event.target.parent.parent is IFlexPaperPluginControl)) { - CursorManager.removeAllCursors(); - } else { - if (TextSelectEnabled && CursorsEnabled) { - _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); - } else if (CursorsEnabled) { - resetCursor(); - } - } - } - } - - public function resetCursor():void { - if (CursorsEnabled) - _grabCursorID = CursorManager.setCursor(MenuIcons.GRAB); - } - - private function dupImageMoutHandler(event:MouseEvent):void { - if (_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage) { - (event.target as DupImage).filters = null; - (event.target as DupImage).addDropShadow(); - } - } - - private function addPages():void { - for (var pi:int = 0; pi < _pageList.length; pi++) { - if (!UsingExtViewMode) - _displayContainer.addChild(_pageList[pi]); - else - CurrExtViewMode.addChild(pi, _pageList[pi]); - } - } - - private var _splitpj:PrintJob; - private var _splitpjoptions:PrintJobOptions = new PrintJobOptions(); - private var _splitpjloading:Boolean = false; - private var _splitpjprinted:int = 0; - private var _splitpageNumList:Array; - - private function printSplitPaper(start:Boolean = false, range:String = ""):void { - if (start) { - _splitpj = new PrintJob(); - _loaderptr = new Loader(); - _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, printSplitPaperLoaded, false, 0, true); - - if (range.length > 0) { - if (range == "Current") { - _splitpageNumList = new Array(); - _splitpageNumList[currPage] = true; - } - else { - _splitpageNumList = range.split(","); - for (var i:int = 0; i < _splitpageNumList.length; i++) { - if (_splitpageNumList[i].toString().indexOf("-") > -1) { - var rs:int = Number(_splitpageNumList[i].toString().substr(0, _splitpageNumList[i].toString().indexOf("-"))); - var re:int = Number(_splitpageNumList[i].toString().substr(_splitpageNumList[i].toString().indexOf("-") + 1)); - for (var irs:int = rs; irs < re + 1; irs++) { - _splitpageNumList[irs] = true; - } - } else { - _splitpageNumList[int(Number(_splitpageNumList[i].toString()))] = true; - } - } - } - } - - _splitpj.start(); - } - - while (_splitpjprinted < numPages) { - if (!_splitpjloading) { - if (_splitpageNumList == null || (_splitpageNumList != null && _splitpageNumList[_splitpjprinted + 1] != null)) { - _splitpjloading = true; - Security.loadEncryptedFile(new URLRequest(getSwfFilePerPage(_swfFile, _splitpjprinted + 1)), _secretKey, function(e:Event):void { - _loaderptr.loadBytes(_secretKey ? e.target.decryptedData : e.target.data, StreamUtil.getExecutionContext()); - }, function(e:ProgressEvent):void { - }); - return; - } else - _splitpjprinted++; - } - else { - setTimeout(printSplitPaper, 200); - return; - } - } - - _splitpj.send(); - } - - private function printSplitPaperLoaded(event:Event):void { - var pageToPrint:MovieClip = event.target.content as MovieClip; - - if ((_splitpj.pageHeight / pageToPrint.height) < 1 && (_splitpj.pageHeight / pageToPrint.height) < (_splitpj.pageWidth / pageToPrint.width)) - pageToPrint.scaleX = pageToPrint.scaleY = (_splitpj.pageHeight / pageToPrint.height); - else if ((_splitpj.pageWidth / pageToPrint.width) < 1) - pageToPrint.scaleX = pageToPrint.scaleY = (_splitpj.pageWidth / pageToPrint.width); - - if ((_swfContainer.getChildAt(0) as UIComponent).numChildren > 0) - (_swfContainer.getChildAt(0) as UIComponent).removeChildAt(0); - - (_swfContainer.getChildAt(0) as UIComponent).addChild(pageToPrint); - - _splitpj.addPage(_swfContainer, null, _splitpjoptions); - _splitpjloading = false; - _splitpjprinted++; - printSplitPaper(); - } - - public function printPaper():void { - if (_docLoader.IsSplit) - return printSplitPaper(true); - - if (_libMC.parent is DupImage) { - (_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument()); - } - _libMC.alpha = 1; - - var pj:PrintJob = new PrintJob(); - var pjlist:Array = new Array(); - - if (!(_pluginList != null && _pluginList.length > 0)) { - if (pj.start()) { - _libMC.stop(); - - //if(pj.orientation == "landscape"){ - - //} - - if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) - _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); - else if ((pj.pageWidth / _libMC.width) < 1) - _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); - - var options:PrintJobOptions = new PrintJobOptions(); - //options.printAsBitmap = true; - - var i:int = 0; - _libMC.gotoAndStop(i + 1); - - while (_libMC.totalFrames > _libMC.currentFrame) { - if (_libMC.currentFrame == i + 1) { - pj.addPage(_swfContainer, null, options); - - i++; - } - - _libMC.gotoAndStop(_libMC.currentFrame + 1); - } - - pj.addPage(_swfContainer, null, options); - pj.send(); - } - } - - // printing with plug-ins uses a bitmap approach - if (_pluginList != null && _pluginList.length > 0) { - var di:DupImage; - var i:int = 0; - _libMC.gotoAndStop(i + 1); - - if (pj.start()) { - _libMC.stop(); - - if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) - _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); - else if ((pj.pageWidth / _libMC.width) < 1) - _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); - - var options:PrintJobOptions = new PrintJobOptions(); - - while (_libMC.totalFrames > _libMC.currentFrame) { - if (_libMC.currentFrame == i + 1) { - di = preparePrintBitmap(i); - pjlist[i] = preparePrintBitmap(i); - i++; - } - - _libMC.gotoAndStop(_libMC.currentFrame + 1); - } - - di = preparePrintBitmap(_libMC.totalFrames); - pjlist[_libMC.totalFrames - 1] = preparePrintBitmap(_libMC.totalFrames - 1); - - for (var ipjlist:int = 0; ipjlist < pjlist.length; ipjlist++) { - pj.addPage(pjlist[ipjlist], null, options); - } - - pj.send(); - } - } - - _libMC.scaleX = _libMC.scaleY = 1; - _libMC.alpha = 0; - dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); - } - - private function preparePrintBitmap(pageIndex:int):DupImage { - var di:DupImage = new DupImage(); - di.removeAllChildren(); - - var bmd:BitmapData = new BitmapData(_libMC.width, _libMC.height); - var bm:Bitmap = new Bitmap(bmd); - - bmd = new BitmapData(_libMC.width, _libMC.height); - bm = new Bitmap(bmd); - bmd.draw(_libMC.getDocument(), new Matrix(1, 0, 0, 1), null, null, null, true); - - if (_pluginList != null) { - for (var pl = 0; pl < _pluginList.length; pl++) { - _pluginList[pl].drawSelf(pageIndex, bmd, 1); - } - } - - di.addChild(bm); - - return di; - } - - public function printPaperRange(range:String):void { - if (_docLoader.IsSplit) - return printSplitPaper(true, range); - - if (_libMC.parent is DupImage) { - (_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument()); - } - _libMC.alpha = 1; - - var pageNumList:Array = new Array(); - var pjlist:Array = new Array(); - - if (range == "Current") { - pageNumList[currPage] = true; - } else { - var splitPageNumList:Array = range.split(","); - for (var i:int = 0; i < splitPageNumList.length; i++) { - if (splitPageNumList[i].toString().indexOf("-") > -1) { - var rs:int = Number(splitPageNumList[i].toString().substr(0, splitPageNumList[i].toString().indexOf("-"))); - var re:int = Number(splitPageNumList[i].toString().substr(splitPageNumList[i].toString().indexOf("-") + 1)); - for (var irs:int = rs; irs < re + 1; irs++) { - pageNumList[irs] = true; - } - } else { - pageNumList[int(Number(splitPageNumList[i].toString()))] = true; - } - } - } - - var pj:PrintJob = new PrintJob(); - var options:PrintJobOptions = new PrintJobOptions(); - //options.printAsBitmap = true; - - if (!(_pluginList != null && _pluginList.length > 0)) { - if (pj.start()) { - _libMC.stop(); - - if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) - _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); - else if ((pj.pageWidth / _libMC.width) < 1) - _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); - - var i:int = 0; - _libMC.gotoAndStop(i + 1); - while (_libMC.totalFrames > _libMC.currentFrame) { - if (_libMC.currentFrame == i + 1) { - if (pageNumList[i + 1] != null) { - pj.addPage(_swfContainer, null, options); - } - - i++; - } - - _libMC.gotoAndStop(_libMC.currentFrame + 1); - } - - if (pageNumList[_libMC.totalFrames] != null) { - pj.addPage(_swfContainer, null, options); - } - - pj.send(); - } - } - - // printing with plug-ins uses a bitmap approach - if (_pluginList != null && _pluginList.length > 0) { - var di:DupImage; - var i:int = 0; - if (pj.start()) { - _libMC.stop(); - - if ((pj.pageHeight / _libMC.height) < 1 && (pj.pageHeight / _libMC.height) < (pj.pageWidth / _libMC.width)) - _libMC.scaleX = _libMC.scaleY = (pj.pageHeight / _libMC.height); - else if ((pj.pageWidth / _libMC.width) < 1) - _libMC.scaleX = _libMC.scaleY = (pj.pageWidth / _libMC.width); - - var i:int = 0; - _libMC.gotoAndStop(i + 1); - while (_libMC.totalFrames > _libMC.currentFrame) { - if (_libMC.currentFrame == i + 1) { - if (pageNumList[i + 1] != null) { - di = preparePrintBitmap(i); - pjlist[i] = preparePrintBitmap(i); - } - - i++; - } - - _libMC.gotoAndStop(_libMC.currentFrame + 1); - } - - if (pageNumList[_libMC.totalFrames] != null) { - di = preparePrintBitmap(_libMC.totalFrames); - pjlist[_libMC.totalFrames - 1] = preparePrintBitmap(_libMC.totalFrames - 1); - } - - for (var ipjlist:int = 0; ipjlist < pjlist.length; ipjlist++) { - pj.addPage(pjlist[ipjlist], null, options); - } - - pj.send(); - } - } - - - _libMC.scaleX = _libMC.scaleY = 1; - _libMC.alpha = 0; - - dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); - } - - private function addGlowFilter(img:Image):void { - var filter:flash.filters.GlowFilter = new flash.filters.GlowFilter(0x111111, 1, 5, 5, 2, 1, false, false); - img.filters = [ filter ]; - } - - private function addDropShadow(img:Image):void { - var filter:DropShadowFilter = new DropShadowFilter(); - filter.blurX = 4; - filter.blurY = 4; - filter.quality = 2; - filter.alpha = 0.5; - filter.angle = 45; - filter.color = 0x202020; - filter.distance = 6; - filter.inner = false; - img.filters = [ filter ]; - } - - public function get SecretKey():String { - return _secretKey; - } - - public function set SecretKey(value:String):void { - _secretKey = value; - } -} +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ + +package com.devaldi.controls.flexpaper +{ + import caurina.transitions.Tweener; + + import com.devaldi.controls.FlowBox; + import com.devaldi.controls.FlowVBox; + import com.devaldi.controls.MatrixTransformer; + import com.devaldi.controls.Spinner; + import com.devaldi.controls.ZoomCanvas; + import com.log4ic.resources.MenuIcons; + import com.devaldi.controls.flexpaper.utils.StreamUtil; + import com.devaldi.controls.flexpaper.utils.TextMapUtil; + import com.devaldi.events.CurrentPageChangedEvent; + import com.devaldi.events.CursorModeChangedEvent; + import com.devaldi.events.DocumentLoadedEvent; + import com.devaldi.events.DocumentPrintedEvent; + import com.devaldi.events.ErrorLoadingPageEvent; + import com.devaldi.events.ExternalLinkClickedEvent; + import com.devaldi.events.FitModeChangedEvent; + import com.devaldi.events.PageLoadedEvent; + import com.devaldi.events.PageLoadingEvent; + import com.devaldi.events.ScaleChangedEvent; + import com.devaldi.events.SelectionCreatedEvent; + import com.devaldi.events.SwfLoadedEvent; + import com.devaldi.events.ViewModeChangedEvent; + import com.devaldi.streaming.DupImage; + import com.devaldi.streaming.DupLoader; + import com.devaldi.streaming.IDocumentLoader; + import com.devaldi.streaming.IGenericDocument; + import com.devaldi.streaming.SwfDocument; + + import flash.display.AVM1Movie; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.DisplayObject; + import flash.display.InteractiveObject; + import flash.display.Loader; + import flash.display.MovieClip; + import flash.display.Shape; + import flash.display.SimpleButton; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.events.ProgressEvent; + import flash.external.ExternalInterface; + import flash.filters.DropShadowFilter; + import flash.geom.Matrix; + import flash.geom.Point; + import flash.net.URLRequest; + import flash.printing.PrintJob; + import flash.printing.PrintJobOptions; + import flash.system.ApplicationDomain; + import flash.system.LoaderContext; + import flash.system.System; + import flash.text.TextSnapshot; + import flash.ui.Keyboard; + import flash.utils.ByteArray; + import flash.utils.Timer; + import flash.utils.escapeMultiByte; + import flash.utils.setTimeout; + + import mx.containers.Box; + import mx.containers.Canvas; + import mx.containers.HBox; + import mx.containers.VBox; + import mx.controls.Alert; + import mx.controls.Image; + import mx.core.Container; + import mx.core.SpriteAsset; + import mx.core.UIComponent; + import mx.events.FlexEvent; + import mx.events.IndexChangedEvent; + import mx.managers.CursorManager; + import mx.resources.ResourceManager; + import mx.rpc.events.FaultEvent; + import mx.rpc.events.ResultEvent; + import mx.rpc.http.HTTPService; + import mx.managers.PopUpManager; + + [Event(name="onDocumentLoaded", type="com.devaldi.events.DocumentLoadedEvent")] + [Event(name="onPageLoaded", type="com.devaldi.events.PageLoadedEvent")] + [Event(name="onPageLoading", type="com.devaldi.events.PageLoadingEvent")] + [Event(name="onDocumentLoading", type="flash.events.Event")] + [Event(name="onNoMoreSearchResults", type="flash.events.Event")] + [Event(name="onLoadingProgress", type="flash.events.ProgressEvent")] + [Event(name="onScaleChanged", type="com.devaldi.events.ScaleChangedEvent")] + [Event(name="onExternalLinkClicked", type="com.devaldi.events.ExternalLinkClickedEvent")] + [Event(name="onCurrPageChanged", type="com.devaldi.events.CurrentPageChangedEvent")] + [Event(name="onViewModeChanged", type="com.devaldi.events.ViewModeChangedEvent")] + [Event(name="onFitModeChanged", type="com.devaldi.events.FitModeChangedEvent")] + [Event(name="onCursorModeChanged", type="com.devaldi.events.CursorModeChangedEvent")] + [Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] + [Event(name="onLogoClicked", type="flash.events.Event")] + [Event(name="onSelectionCreated", type="com.devaldi.events.SelectionCreatedEvent")] + [Event(name="onDocumentPrinted", type="com.devaldi.events.DocumentPrintedEvent")] + [Event(name="onErrorLoadingPage", type="com.devaldi.events.ErrorLoadingPageEvent")] + + public class Viewer extends Canvas + { + private var _swfFile:String = ""; + private var _swfFileChanged:Boolean = false; + private var _initialized:Boolean = false; + private var _loaderptr:Loader; + private var _libMC:IGenericDocument; + private var _displayContainer:Container; + private var _paperContainer:ZoomCanvas; + private var _swfContainer:Canvas; + private var _scale:Number = 1; + private var _pscale:Number = 1; + private var _swfLoaded:Boolean = false; + private var _pageList:Array; + private var _viewMode:String = Viewer.InitViewMode; + private var _fitMode:String = FitModeEnum.FITNONE; + public static var InitViewMode:String = ViewModeEnum.PORTRAIT; + private var _scrollToPage:Number = 0; + private var _numPages:Number = 0; + private var _currPage:Number = 0; + private var _tweencount:Number = 0; + private var _bbusyloading:Boolean = true; + private var _zoomtransition:String = "easeOut"; + private var _zoomtime:Number = 0.6; + private var _fitPageOnLoad:Boolean = false; + private var _fitWidthOnLoad:Boolean = false; + private var _dupImageClicked:Boolean = false; + private var _docLoader:IDocumentLoader; + private var _progressiveLoading:Boolean = false; + private var _repaintTimer:Timer; + private var _loadTimer:Timer; + private var _frameLoadCount:int = 0; + private var _adjGotoPage:int = 0; + private var _zoomInterval:Number = 0; + private var _inputBytes:ByteArray; + private var _textSelectEnabled:Boolean = false; + private var _cursorsEnabled:Boolean = true; + private var _grabCursorID:Number = 0; + private var _grabbingCursorID:Number = 0; + private var _pluginList:Array; + public static var ViewModeExtList:Array; + private var _currentExtViewMode:IFlexPaperViewModePlugin; + private var _minZoomSize:Number = 0.3; + private var _maxZoomSize:Number = 5; + private var _searchMatchAll:Boolean = false; + private var _searchServiceUrl:String = ""; + private var _performSearchOnPageLoad:Boolean = false; + private var _pendingSearchPage:int = -1; + private var _skinImg:Bitmap = new MenuIcons.SMALL_TRANSPARENT(); + private var _skinImgc:Bitmap = new MenuIcons.SMALL_TRANSPARENT_COLOR(); + private var _skinImgDo:Image; + + public function Viewer(){ + super(); + } + + public function get BusyLoading():Boolean { + return _bbusyloading; + } + + public function set BusyLoading(b:Boolean):void { + _bbusyloading = b; + } + + public function get libMC():IGenericDocument { + return _libMC; + } + + public function get IsInitialized():Boolean{ + return _initialized; + } + + public function get SwfLoaded():Boolean{ + return _swfLoaded; + } + + public function get DisplayContainer():Container{ + return _displayContainer; + } + + public function set DisplayContainer(c:Container):void{ + _displayContainer = c; + } + + public function get PaperContainer():ZoomCanvas{ + return _paperContainer; + } + + public function get PageList():Array { + return _pageList; + } + + public function get DocLoader():IDocumentLoader{ + return _docLoader; + } + + public function set DocLoader(d:IDocumentLoader):void{ + _docLoader = d; + } + + [Bindable] + public function get ViewMode():String { + return _viewMode; + } + + [Bindable] + public function get FitMode():String { + return _fitMode; + } + + public function set ViewMode(s:String):void { + if(s!=_viewMode){ + for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList){ + if(s == vme.Name){ + _currentExtViewMode = vme; + } + } + + if(s == ViewModeEnum.TILE&&ViewMode==ViewModeEnum.PORTRAIT){_pscale = _scale; _scale = 0.23;_paperContainer.verticalScrollPosition = 0;_fitMode = FitModeEnum.FITNONE;}else{_scale = _pscale;} + _paperContainer.x = (s==ViewModeEnum.PORTRAIT||s==ViewModeEnum.TILE)?2.5:0; + + _viewMode = s; + if(_initialized && _swfLoaded){createDisplayContainer();if(this._progressiveLoading){this.addInLoadedPages(true);}else{reCreateAllPages();}_displayContainer.visible = true;} + FitMode = FitModeEnum.FITNONE; + + if(UsingExtViewMode){ + CurrExtViewMode.setViewMode(s); + _viewMode = s; + } + + dispatchEvent(new ViewModeChangedEvent(ViewModeChangedEvent.VIEWMODE_CHANGED,_viewMode)); + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED,_scale)); + dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED,_fitMode)); + } + } + + public function set FitMode(s:String):void { + if(_viewMode == ViewModeEnum.TILE){_fitMode = FitModeEnum.FITNONE;return} + + if(s!=_fitMode){ + _fitMode = s; + + switch(s){ + case FitModeEnum.FITWIDTH: + fitWidth(); + break; + + case FitModeEnum.FITHEIGHT: + fitHeight(); + break; + } + + dispatchEvent(new FitModeChangedEvent(FitModeChangedEvent.FITMODE_CHANGED,_fitMode)); + } + } + + public function set ProgressiveLoading(b1:Boolean):void { + _progressiveLoading = b1; + } + + [Bindable] + public function get ProgressiveLoading():Boolean { + return _progressiveLoading; + } + + public function set TextSelectEnabled(b1:Boolean):void { + _textSelectEnabled = b1; + + if(_textSelectEnabled && CursorsEnabled) + dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED,"TextSelectorCursor")); + else + dispatchEvent(new CursorModeChangedEvent(CursorModeChangedEvent.CURSORMODE_CHANGED,"ArrowCursor")); + } + + [Bindable] + public function get TextSelectEnabled():Boolean { + return _textSelectEnabled; + } + + [Bindable] + public function get CursorsEnabled():Boolean { + return _cursorsEnabled; + } + + public function set CursorsEnabled(b:Boolean):void { + _cursorsEnabled = b; + } + + public function setPaperFocus():void{ + _paperContainer.setFocus(); + } + + public function get ZoomTransition():String { + return _zoomtransition; + } + + public function set ZoomTransition(s:String):void { + _zoomtransition = s; + } + + public function get ZoomTime():Number { + return _zoomtime; + } + + public function set ZoomTime(n:Number):void { + _zoomtime = n; + } + + public function get MinZoomSize():Number { + return _minZoomSize; + } + + public function set MinZoomSize(n:Number):void { + _minZoomSize = n; + } + + public function get MaxZoomSize():Number { + return _maxZoomSize; + } + + public function set MaxZoomSize(n:Number):void { + _maxZoomSize = n; + } + + public function get PluginList():Array{ + return _pluginList; + } + + public function set PluginList(p:Array):void{ + _pluginList = p; + } + + public function get CurrExtViewMode():IFlexPaperViewModePlugin{ + if(_currentExtViewMode != null && _currentExtViewMode.Name == ViewMode) + return _currentExtViewMode; + else{ + for each (var vme:IFlexPaperViewModePlugin in ViewModeExtList){ + if(ViewMode == vme.Name){ + _currentExtViewMode = vme; + } + } + } + + return _currentExtViewMode; + } + + public function get UsingExtViewMode():Boolean{ + if(ViewMode == ViewModeEnum.PORTRAIT || ViewMode == ViewModeEnum.TILE) + return false; + else + return (CurrExtViewMode!=null && ViewMode == CurrExtViewMode.Name); + } + + public function get ZoomInterval():Number { + return _zoomInterval; + } + + public function set ZoomInterval(n:Number):void { + _zoomInterval = n; + } + + [Bindable] + public function get numPages():Number { + return _numPages; + } + + public function set numPages(n:Number):void { + _numPages = n; + } + + [Bindable] + public function get numPagesLoaded():Number { + return (_libMC!=null)?_libMC.framesLoaded:0; + } + + public function set numPagesLoaded(n:Number):void { + + } + + [Bindable] + public function get currPage():Number { + return _currPage; + } + + public function set currPage(n:Number):void { + _currPage = n; + } + + [Bindable] + public function get SearchMatchAll():Boolean { + if(SearchServiceUrl!=null && SearchServiceUrl.length>0) + return false; + else + return _searchMatchAll; + } + + public function set SearchMatchAll(b1:Boolean):void { + _searchMatchAll = b1; + } + + [Bindable] + public function get SearchServiceUrl():String { + return _searchServiceUrl; + } + + public function set SearchServiceUrl(s1:String):void { + _searchServiceUrl = unescape(s1); + } + + public function get FitWidthOnLoad():Boolean { + return _fitWidthOnLoad; + } + + public function set FitWidthOnLoad(b1:Boolean):void { + _fitWidthOnLoad = b1; + } + + public function get FitPageOnLoad():Boolean { + return _fitPageOnLoad; + } + + public function set FitPageOnLoad(b2:Boolean):void { + _fitPageOnLoad = b2; + } + + public function gotoPage(p:Number, adjGotoPage:int=0):void{ + if(adjGotoPage!=0){_adjGotoPage=adjGotoPage;} + + if(p<1 || p-1 >_pageList.length) + return; + else{ + if(ViewMode == ViewModeEnum.PORTRAIT){ + _paperContainer.verticalScrollPosition = _pageList[p-1].y+3 + _adjGotoPage; + } + + if(UsingExtViewMode) + CurrExtViewMode.gotoPage(p,adjGotoPage); + + // retry if y is not set + if(!UsingExtViewMode && p>1 && _pageList[p-1].y ==0) + { + flash.utils.setTimeout(gotoPage,200,p); + } + else + _adjGotoPage = 0; + + repositionPapers(); + } + } + + public function mvNext():void{ + if(UsingExtViewMode) + CurrExtViewMode.mvNext(); + else + if(currPage1){gotoPage(currPage-1);} + } + } + + public function switchMode(mode:String=null):void{ + if(mode==null){ // no mode passed, just + if(ViewMode == ViewModeEnum.PORTRAIT){ViewMode = ViewModeEnum.TILE;} + else if(ViewMode == ViewModeEnum.TILE){_scale = _pscale; ViewMode = ViewModeEnum.PORTRAIT;} + }else{ + if(ViewMode == mode && ViewMode != ViewModeEnum.PORTRAIT){ + ViewMode = ViewModeEnum.PORTRAIT; + } + else + ViewMode = mode; + } + } + + public function get PaperVisible():Boolean { + return _paperContainer.visible; + } + + public function set PaperVisible(b:Boolean):void { + _paperContainer.visible = b; + } + + public function get SwfFile():String { + return _swfFile; + } + + public function getSwfFilePerPage(swfFile:String, page:int):String{ + var fileName:String = swfFile; + var map:String = (fileName.substr(fileName.indexOf("[*,"),fileName.indexOf("]")-fileName.indexOf("[*,")+1)); + var padding:int = parseInt(map.substr(map.indexOf(",")+1,map.indexOf("]")-2)); + fileName = TextMapUtil.StringReplaceAll(fileName,map,padString(page.toString(),padding,"0")); + + return encodeURI(fileName); + } + + public function set SwfFile(s:String):void { + var pagesSplit:Boolean = false; + s = unescape(s); + + if(s.length!=0){ + + if(s.indexOf("{")>=0 && s.indexOf("}")>0){ + numPages = parseInt(s.substr(s.lastIndexOf(",")+1,s.indexOf("}")-s.lastIndexOf(",")-1)); + s = TextMapUtil.StringReplaceAll(s,"{",""); + s = TextMapUtil.StringReplaceAll(s,","+numPages.toString()+"}",""); + pagesSplit = true; + } + + clearPlugins(); + deleteDisplayContainer(); + deletePageList(); + deleteLoaderPtr(); + deleteLoaderList(); + deleteFLoader(); + deleteSelectionMarker(); + TextMapUtil.totalFragments = ""; + + if(s!=_swfFile) + deleteLibMC(); + + _swfFileChanged = true; + _frameLoadCount = 0; + + if(!pagesSplit) + _swfFile = encodeURI(s); + else + _swfFile = s; + + ViewMode = Viewer.InitViewMode; + + try{ + new flash.net.LocalConnection().connect('devaldiGCdummy'); + new flash.net.LocalConnection().connect('devaldiGCdummy'); + } catch (e:*) {} + + try{flash.system.System.gc();} catch (e:*) {} + + if(_docLoader!=null && !_docLoader.hasEventListener(SwfLoadedEvent.SWFLOADED)){ + _docLoader.PagesSplit = pagesSplit; + _docLoader.addEventListener("onDocumentLoadedError", onDocumentLoadedErrorHandler,false,0,true); + _docLoader.addEventListener(SwfLoadedEvent.SWFLOADED, swfComplete,false,0,true); + } + + if(_docLoader!=null){ + _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); + _docLoader.stream.addEventListener(ProgressEvent.PROGRESS, onLoadProgress,false,0,true); + } + + if(_swfFile.length>0 && pagesSplit){ + _loadTimer = new Timer(100); + _loadTimer.addEventListener("timer",loadtimer); + + _docLoader.load(new URLRequest(getSwfFilePerPage(_swfFile,1)),StreamUtil.getExecutionContext()); //new URLRequest(decodeURI(_swfFile)) + } + else if(_swfFile.length > 0 && !pagesSplit) + _docLoader.load(new URLRequest(_swfFile),StreamUtil.getExecutionContext()); + + _paperContainer.verticalScrollPosition = 0; + createDisplayContainer(); + + // Changing the SWF file causes the component to invalidate. + invalidateProperties(); + invalidateSize(); + invalidateDisplayList(); + } + } + + [Bindable] + public function get Scale():String { + return _scale.toString(); + } + + public function get CurrentlySelectedText():String { + return _currentlySelectedText; + } + + public function Zoom(factor:Number):void{ + if(factor<_minZoomSize || factor>_maxZoomSize || factor == _scale) + return; + + if((!UsingExtViewMode && _viewMode != ViewModeEnum.PORTRAIT) || (UsingExtViewMode && !CurrExtViewMode.doZoom)){return;} + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.width>0); + + _tweencount = _displayContainer.numChildren; + + for(var i:int=0;i<_displayContainer.numChildren;i++){ + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX: factor, scaleY: factor, time: _zoomtime, transition: _zoomtransition, onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITNONE; + _scale = factor; + + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED,_scale)); + } + + // rotate not finished. + public function rotate():void{ + var counter:int=0; + //Tweener.addTween(_displayContainer.getChildAt(currPage-1), {x:_displayContainer.getChildAt(currPage-1).parent.width/2+_displayContainer.getChildAt(currPage-1).height/2, y:((_displayContainer.getChildAt(currPage-1).height/2)-_displayContainer.getChildAt(currPage-1).width/2),rotation:90, time: 0.3, transition: 'easenone', onComplete: tweenComplete}); + } + + public function getFitWidthFactor():Number{ + _libMC.gotoAndStop(1); + return (_paperContainer.width / _libMC.width) - 0.032; //- 0.03; + } + + public function getFitHeightFactor():Number{ + _libMC.gotoAndStop(1); + return (_paperContainer.height / _libMC.height); + } + + public function fitWidth():void{ + if(_displayContainer.numChildren == 0){return;} + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.width>0); + var factor:Number = getFitWidthFactor(); + _scale = factor; + _tweencount = _displayContainer.numChildren; + + for(var i:int=0;i<_displayContainer.numChildren;i++){ + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITWIDTH; + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED,_scale)); + } + + public function fitHeight():void{ + if(_displayContainer.numChildren == 0){return;} + + var _target:DisplayObject; + _paperContainer.CenteringEnabled = (_paperContainer.height>0); + var factor:Number = getFitHeightFactor(); + _scale = factor; + _tweencount = _displayContainer.numChildren; + + for(var i:int=0;i<_displayContainer.numChildren;i++){ + _target = _displayContainer.getChildAt(i); + _target.filters = null; + Tweener.addTween(_target, {scaleX:factor, scaleY:factor,time: 0, transition: 'easenone', onComplete: tweenComplete}); + } + + FitMode = FitModeEnum.FITHEIGHT; + dispatchEvent(new ScaleChangedEvent(ScaleChangedEvent.SCALE_CHANGED,_scale)); + } + + private function tweenComplete():void{ + _tweencount--; + + if(_tweencount==0){ + + if(_loadTimer!=null) + _loadTimer.start(); + + repositionPapers(); + } + + if(_tweencount < numPagesLoaded - 2 || _tweencount == 0){ + PaperVisible = true; + } + } + + private function reScaleComplete():void{ + _tweencount--; + + if(_tweencount==0){ + if(_displayContainer.numChildren>0){ + _paperContainer.verticalScrollPosition = 0; + + if(_loadTimer!=null) + _loadTimer.start(); + + repositionPapers(); + } + + if(_tweencount < numPagesLoaded - 2 || _tweencount == 0){ + PaperVisible = true; + } + } + } + + public function set Scale(s:String):void { + var diff:Number = _scale - new Number(s); + _scale = new Number(s); + } + + override protected function createChildren():void { + // Call the createChildren() method of the superclass. + super.createChildren(); + this.styleName = "viewerBackground"; + + // Bind events + //_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete); + addEventListener(Event.RESIZE, sizeChanged,false,0,true); + systemManager.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler,false,0,true); + + // Create a visible container for the swf + _swfContainer = new Canvas(); + _swfContainer.visible = false; + this.addChild(_swfContainer); + + // Create a timer to use for repainting + _repaintTimer = new Timer(5,0); + _repaintTimer.addEventListener("timer", repaintHandler); + + createDisplayContainer(); + } + + private function onframeenter(event:Event):void{ + if(!_dupImageClicked){return;} + + if(_docLoader!=null && _docLoader.PagesSplit) //todo:links not fixed yet for split up approach + return; + + if(event.target.content != null){ + if (event.target.parent is DupImage && + event.target.content.currentFrame!=(event.target.parent as DupImage).dupIndex + && _dupImageClicked){ + var np:int = event.target.content.currentFrame; + event.target.content.gotoAndStop((event.target.parent as DupImage).dupIndex); + gotoPage(np); + } + } + } + + private function updComplete(event:Event):void { + if(_scrollToPage>0){ + _paperContainer.verticalScrollPosition = _pageList[_scrollToPage-1].y; + _paperContainer.horizontalScrollPosition = 0; + _scrollToPage = 0; + } + + repaint(); + //repositionPapers(); + } + + private function repaintHandler(e:Event):void { + if(_loadTimer!=null){ + _loadTimer.reset(); + _loadTimer.start(); + } + + repositionPapers(); + _repaintTimer.stop(); + _repaintTimer.delay = 5; + } + + private function loadtimer(e:Event):void { + if(_loadTimer!=null) + _loadTimer.stop(); + + repositionPapers(); + } + + private function bytesLoaded(event:Event):void{ + event.target.loader.loaded = true; + + var bFound:Boolean=false; + + // Split up approach + if(_docLoader!=null && _docLoader.PagesSplit){ + event.target.loader.loading = false; + + if(event.target.loader.content!=null && event.target.loader.content is MovieClip){event.target.loader.content.stop();} + + for(var i:int=0;i<_docLoader.LoaderList.length;i++){ + if(_docLoader.LoaderList[i].loading){ + bFound = true; + break; + } + } + + _frameLoadCount = numPages; + _bbusyloading = false; + _displayContainer.visible = true; + repaint(); + + if(!bFound){ + dispatchEvent(new PageLoadedEvent(PageLoadedEvent.PAGE_LOADED,event.target.loader.pageStartIndex)); + + if(_fitPageOnLoad){FitMode = FitModeEnum.FITHEIGHT;_fitPageOnLoad=false;_scrollToPage=1;_pscale=_scale;} + if(_fitWidthOnLoad){FitMode = FitModeEnum.FITWIDTH;_fitWidthOnLoad=false;_scrollToPage=1;_pscale=_scale;} + + } + }else{ // normal file approach + if(event.target.loader.content!=null){event.target.loader.content.stop();} + + if(!ProgressiveLoading || (ProgressiveLoading && _libMC.framesLoaded == _libMC.totalFrames)){ + for(var i:int=0;i<_docLoader.LoaderList.length;i++){ + if(!_docLoader.LoaderList[i].loaded && !(_docLoader.LoaderList[i].parent is DupImage)){ + _docLoader.LoaderList[i].unloadAndStop(true); + _docLoader.LoaderList[i].loadBytes(_inputBytes,StreamUtil.getExecutionContext()); + bFound = true; + break; + } + } + } + + if(!bFound){ + _bbusyloading = false; + if(_fitPageOnLoad){FitMode = FitModeEnum.FITHEIGHT;_fitPageOnLoad=false;_scrollToPage=1;_pscale=_scale;} + if(_fitWidthOnLoad){FitMode = FitModeEnum.FITWIDTH;_fitWidthOnLoad=false;_scrollToPage=1;_pscale=_scale;} + _displayContainer.visible = true; + + if( _libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded){ + dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED,numPages)); + _frameLoadCount = _libMC.framesLoaded; + } + } + } + } + + public function repositionPapers():void{ + if(_docLoader==null){return;} + if(_docLoader!=null&&_docLoader.LoaderList==null||numPagesLoaded==0){return;} + + { + var loaderidx:int=0; + var bFoundFirst:Boolean = false; + var _thumb:Bitmap; + var _thumbData:BitmapData; + var uloaderidx:int=0; + var p:int=-1; + var pl:int=0; + + for(var i:int=0;i<_pageList.length;i++){ + if(ViewMode == ViewModeEnum.TILE){ + if(!bFoundFirst && ((i) * (_pageList[i].height + 6)) >= _paperContainer.verticalScrollPosition){ + bFoundFirst = true; + p = i + 1; + } + } + else if(ViewMode == ViewModeEnum.PORTRAIT){ + if(!bFoundFirst) + { + var perH:int=0; + if(_pageList.length>1) + { + perH=_pageList[1].y-_pageList[0].y; + var nowP:Number=_paperContainer.verticalScrollPosition/(perH); + if(0=(_pageList.length-0.5)&&nowP<=_pageList.length) + p = _pageList.length; + else{ + p = Math.round(nowP)+1; + if(_pageList.length>p-1&&_paperContainer.verticalScrollPosition<_pageList[p-1].y && p!=_pageList.length){ + p-=1; + } + } + bFoundFirst = true; + } + else + { + bFoundFirst = true; + p = 1; + } + } + } + + if(p>numPages) + return; + + if(UsingExtViewMode){ + if(currPage != CurrExtViewMode.currentPage) + dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED,CurrExtViewMode.currentPage)); + + p = CurrExtViewMode.currentPage; + currPage = p; + } + + if(p>0&&p!=_currPage){ + currPage = p; + dispatchEvent(new CurrentPageChangedEvent(CurrentPageChangedEvent.PAGE_CHANGED,p)); + } + + if(_libMC!=null&&checkIsVisible(i)){ + if(_pageList[i].numChildren<4){ + if(ViewMode == ViewModeEnum.PORTRAIT){ + + if(_docLoader.PagesSplit) + uloaderidx = finduloaderIdx(_pageList[i].dupIndex); + + if(!_docLoader.PagesSplit || uloaderidx == -1) + uloaderidx = (i==_pageList.length-1&&loaderidx+3<_docLoader.LoaderList.length)?loaderidx+3:(loaderidx<_docLoader.LoaderList.length)?loaderidx:0; + + if(!_docLoader.PagesSplit){ + if(!_bbusyloading && _docLoader.LoaderList!=null && _docLoader.LoaderList.length>0){ + if(numPagesLoaded>=_pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content==null||(_docLoader.LoaderList[uloaderidx].content!=null&&_docLoader.LoaderList[uloaderidx].content.framesLoaded<_pageList[i].dupIndex)){ + _bbusyloading = true; + _docLoader.LoaderList[uloaderidx].unloadAndStop(true); + _docLoader.LoaderList[uloaderidx].loadBytes(_inputBytes,StreamUtil.getExecutionContext()); + flash.utils.setTimeout(repositionPapers,200); + } + } + + if((i<2||_pageList[i].numChildren==0||(_pageList[i]!=null&&_docLoader.LoaderList[uloaderidx]!=null&&_docLoader.LoaderList[uloaderidx].content!=null&&_docLoader.LoaderList[uloaderidx].content.currentFrame!=_pageList[i].dupIndex)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null){ + if(numPagesLoaded >= _pageList[i].dupIndex){ + _docLoader.LoaderList[uloaderidx].content.gotoAndStop(_pageList[i].dupIndex); + _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); + _pageList[i].loadedIndex = _pageList[i].dupIndex; + /* + if(_libMC.width*_scale>0&&_libMC.height*_scale>0){ + _libMC.gotoAndStop(_pageList[i].dupIndex); + _thumbData = new BitmapData(_libMC.width*_scale, _libMC.height*_scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _thumbData.draw(_libMC,new Matrix(_scale, 0, 0, _scale),null,null,null,true); + } */ + } + } + } + + if(_docLoader.PagesSplit){ + if(!_bbusyloading && _docLoader.LoaderList!=null && _docLoader.LoaderList.length>0){ + if(_docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].pageStartIndex != _pageList[i].dupIndex && !_loadTimer.running && !_docLoader.LoaderList[uloaderidx].loading){ + dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING,_pageList[i].dupIndex)); + try{ + _pageList[i].resetPage(_libMC.width,_libMC.height,_scale,true); + _docLoader.LoaderList[uloaderidx].unloadAndStop(true); + _docLoader.LoaderList[uloaderidx].loaded = false; + _docLoader.LoaderList[uloaderidx].loading = true; + _docLoader.LoaderList[uloaderidx].load(new URLRequest(getSwfFilePerPage(_swfFile,_pageList[i].dupIndex)),StreamUtil.getExecutionContext()); + _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; + }catch(err:IOErrorEvent){} + + repaint(); + + } + } + + if((_pageList[i].numChildren==0||(_pageList[i]!=null&&_docLoader.LoaderList[uloaderidx]!=null&&_docLoader.LoaderList[uloaderidx].content!=null)) && _docLoader.LoaderList[uloaderidx] != null && _docLoader.LoaderList[uloaderidx].content != null && _docLoader.LoaderList[uloaderidx].loaded && _docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex){ + if(numPagesLoaded >= _pageList[i].dupIndex||true){ + if(_docLoader.LoaderList[uloaderidx].parent != null) + _docLoader.LoaderList[uloaderidx].parent.removeChild(_docLoader.LoaderList[uloaderidx]); + + _pageList[i].addChild(_docLoader.LoaderList[uloaderidx]); + _pageList[i].loadedIndex = _pageList[i].dupIndex; + + if(_performSearchOnPageLoad && _pendingSearchPage == _pageList[i].dupIndex){ + _performSearchOnPageLoad = false; + searchTextByService(prevSearchText) + } + } + } + } + + }else if(ViewMode == ViewModeEnum.TILE && _pageList[i].source == null && (numPagesLoaded >= _pageList[i].dupIndex||_docLoader.PagesSplit)){ + if(!_docLoader.PagesSplit){ + _libMC.gotoAndStop(_pageList[i].dupIndex); + _thumbData = new BitmapData(_libMC.width*_scale, _libMC.height*_scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _thumbData.draw(_libMC.getDocument(),new Matrix(_scale, 0, 0, _scale),null,null,null,true); + }else{ + + if(!_bbusyloading && !_loadTimer.running && _docLoader.LoaderList!=null && _docLoader.LoaderList.length>0 && !_docLoader.LoaderList[uloaderidx].loading){ + dispatchEvent(new PageLoadingEvent(PageLoadingEvent.PAGE_LOADING,_pageList[i].dupIndex)); + + try{ + _pageList[i].resetPage(_libMC.width,_libMC.height,_scale,true); + _docLoader.LoaderList[uloaderidx].loaded = false; + _docLoader.LoaderList[uloaderidx].loading = true; + _docLoader.LoaderList[uloaderidx].load(new URLRequest(getSwfFilePerPage(_swfFile,_pageList[i].dupIndex)),StreamUtil.getExecutionContext()); + _docLoader.LoaderList[uloaderidx].pageStartIndex = _pageList[i].dupIndex; + }catch(err:IOErrorEvent){} + + repaint(); + } + + if(_docLoader.LoaderList[uloaderidx].pageStartIndex == _pageList[i].dupIndex && _pageList[i].loadedIndex != _pageList[i].dupIndex && _docLoader.LoaderList[uloaderidx].content!=null){ + _thumbData = new BitmapData(_docLoader.LoaderList[uloaderidx].width*_scale, _docLoader.LoaderList[uloaderidx].height*_scale, false, 0xFFFFFF); + _thumb = new Bitmap(_thumbData); + _pageList[i].source = _thumb; + _pageList[i].loadedIndex = _pageList[i].dupIndex; + _thumbData.draw(_docLoader.LoaderList[uloaderidx],new Matrix(_scale, 0, 0, _scale),null,null,null,true); + } + } + + if(_pluginList!=null){ + for(pl=0;pl<_pluginList.length;pl++){ + _pluginList[pl].drawSelf(i,_thumbData,_scale); + } + } + } + } + + if(UsingExtViewMode){ + CurrExtViewMode.renderPage(i); + CurrExtViewMode.renderSelection(i,_selectionMarker); + } + + if((_viewMode == ViewModeEnum.PORTRAIT) && _selectionMarker != null){ + if(i+1 == searchPageIndex && _selectionMarker.parent != _pageList[i]){ + _pageList[i].addChildAt(_selectionMarker,_pageList[i].numChildren); + }else if(i+1 == searchPageIndex && _selectionMarker.parent == _pageList[i]){ + _pageList[i].setChildIndex(_selectionMarker,_pageList[i].numChildren -1); + } + } + + if(_viewMode != ViewModeEnum.TILE){ + if(_pluginList!=null){ + for(pl=0;pl<_pluginList.length;pl++){ + _pluginList[pl].drawSelf(i,_pageList[i],_scale); + } + } + } + + if(_viewMode != ViewModeEnum.TILE && !UsingExtViewMode && _markList[i] != null){ + if(_markList[i].parent != _pageList[i]){ + _pageList[i].addChildAt(_markList[i],_pageList[i].numChildren); + }else{ + _pageList[i].setChildIndex(_markList[i],_pageList[i].numChildren -1); + } + } + + if(UsingExtViewMode && _markList[i] != null){ + CurrExtViewMode.renderMark(_markList[i],i); + } + + loaderidx++; + }else{ + if(_pageList[i].numChildren>0 || _pageList[i].source != null){ + _pageList[i].source = null; + + if(_tweencount == 0) + _pageList[i].resetPage(_libMC.width,_libMC.height,_scale); + else + _pageList[i].removeAllChildren(); + + _pageList[i].loadedIndex = -1; + } + } + } + } + } + + private function padString(_str:String, _n:Number, _pStr:String):String + { + var _rtn:String = _str; + if ((_pStr == null) || (_pStr.length < 1)) + { + _pStr = " "; + } + + if (_str.length < _n) + { + var _s:String = ""; + for (var i:Number = 0 ; i < (_n - _str.length) ; i++) + { + _s += _pStr; + } + _rtn = _s + _str; + } + + return _rtn; + } + + private function finduloaderIdx(idx:int):int{ + for(var i:int=0;i<_docLoader.LoaderList.length;i++){ + if(_docLoader.LoaderList[i].pageStartIndex == idx) + return i; + } + for(var i:int=0;i<_docLoader.LoaderList.length;i++){ + if(!checkIsVisible(_docLoader.LoaderList[i].pageStartIndex)) + return i; + } + return -1; + } + + public function repaint():void{ + _repaintTimer.reset();_repaintTimer.start(); + } + + private function checkIsVisible(pageIndex:int):Boolean{ + try{ + if(ViewMode == ViewModeEnum.TILE){ + return _pageList[pageIndex].parent.y + _pageList[pageIndex].height >= _paperContainer.verticalScrollPosition && + (_pageList[pageIndex].parent.y - _pageList[pageIndex].height) < (_paperContainer.verticalScrollPosition + _paperContainer.height); + } + else if(!UsingExtViewMode){ + if(_paperContainer.height <= 0) + return false; + + return (_pageList[pageIndex].y + (_pageList[pageIndex].getScaledHeight() + 6)) >= _paperContainer.verticalScrollPosition && + (_pageList[pageIndex].y - (_pageList[pageIndex].getScaledHeight() + 6)) < (_paperContainer.verticalScrollPosition + _paperContainer.height); + } + + if(UsingExtViewMode) + return CurrExtViewMode.checkIsVisible(pageIndex); + + }catch(e:Error){ + return false; + } + return false; + } + + public function createDisplayContainer():void{ + + + if(_skinImgDo != null && _skinImgDo.parent == this){ + removeChild(_skinImgDo); + _skinImgDo.removeEventListener(MouseEvent.MOUSE_OVER,skinMouseOver); + _skinImgDo.removeEventListener(MouseEvent.MOUSE_OUT,skinMouseOut); + _skinImgDo.removeEventListener(MouseEvent.MOUSE_DOWN,skinMouseDown); + } + + _skinImgDo = new Image(); + _skinImgDo.source = _skinImg; + _skinImgDo.x = this.width-_skinImg.width - 27; _skinImgDo.y = this.height-_skinImg.height - 10; + _skinImgDo.addEventListener(MouseEvent.MOUSE_OVER,skinMouseOver,false,0,true); + _skinImgDo.addEventListener(MouseEvent.MOUSE_OUT,skinMouseOut,false,0,true); + _skinImgDo.addEventListener(MouseEvent.MOUSE_DOWN,skinMouseDown,false,0,true); + _skinImgDo.buttonMode = true; + addChild(_skinImgDo); + + // Add the swf to the invisible container. + _swfContainer.removeAllChildren(); + var uic:UIComponent = new UIComponent(); + _swfContainer.addChild(uic); + + if(_docLoader!=null && _docLoader.DocumentContainer != null) + uic.addChild(_docLoader.DocumentContainer); + + if(_paperContainer !=null && _paperContainer.parent == this){ + removeChild(_paperContainer); + _paperContainer.removeEventListener(FlexEvent.UPDATE_COMPLETE,updComplete); + + _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); + } + + _paperContainer = new ZoomCanvas(); + _paperContainer.percentHeight = 100; + _paperContainer.percentWidth = 100; + _paperContainer.addEventListener(FlexEvent.UPDATE_COMPLETE,updComplete,false,0,true); + _paperContainer.x = (ViewMode==ViewModeEnum.PORTRAIT||ViewMode==ViewModeEnum.TILE)?2.5:0; + _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler,false,0,true); + _paperContainer.setStyle("horizontalGap",1); + _paperContainer.setStyle("verticalGap",0); + + addChildAt(_paperContainer,getChildIndex(_skinImgDo)-1); + + try{ + new flash.net.LocalConnection().connect('devaldiGCdummy'); + new flash.net.LocalConnection().connect('devaldiGCdummy'); + } catch (e:*) {} + + try{flash.system.System.gc();} catch (e:*) {} + + if(_paperContainer.numChildren>0){_paperContainer.removeAllChildren();} + + deleteDisplayContainer(); + + if(_viewMode == ViewModeEnum.TILE){ + _displayContainer = new FlowBox(); + _displayContainer.setStyle("horizontalAlign", "left"); + _paperContainer.horizontalScrollPolicy = "off"; + _scale = 0.243; + _paperContainer.addChild(_displayContainer); + _paperContainer.childrenDoDrag = true; + _initialized=true; + } + else if(UsingExtViewMode){ + _initialized = CurrExtViewMode.initComponent(this); + } + else{ + _displayContainer = new FlowVBox(); + _displayContainer.setStyle("horizontalAlign", "center"); + _paperContainer.addChild(_displayContainer); + _paperContainer.childrenDoDrag = true; + _initialized=true; + } + + _displayContainer.verticalScrollPolicy = "off"; + _displayContainer.horizontalScrollPolicy = "off"; + _displayContainer.setStyle("verticalAlign", "center"); + _displayContainer.percentHeight = 100; + _displayContainer.percentWidth = (ViewMode==ViewModeEnum.PORTRAIT)?96:100; + _displayContainer.useHandCursor = true; + _displayContainer.addEventListener(MouseEvent.ROLL_OVER,displayContainerrolloverHandler,false,0,true); + _displayContainer.addEventListener(MouseEvent.ROLL_OUT,displayContainerrolloutHandler,false,0,true); + _displayContainer.addEventListener(MouseEvent.MOUSE_DOWN,displayContainerMouseDownHandler,false,0,true); + _displayContainer.addEventListener(MouseEvent.MOUSE_UP,displayContainerMouseUpHandler,false,0,true); + _displayContainer.addEventListener(MouseEvent.DOUBLE_CLICK,displayContainerDoubleClickHandler,false,0,true); + //_displayContainer.mouseChildren = false; + _displayContainer.doubleClickEnabled = true; + } + + private function displayContainerrolloverHandler(event:MouseEvent):void{ + + if(_viewMode==ViewModeEnum.PORTRAIT||(UsingExtViewMode && CurrExtViewMode.supportsTextSelect)){ + if(TextSelectEnabled && CursorsEnabled){ + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + }else if(CursorsEnabled){ + resetCursor(); + } + } + } + + private function displayContainerMouseUpHandler(event:MouseEvent):void{ + if(_viewMode==ViewModeEnum.PORTRAIT||(UsingExtViewMode && CurrExtViewMode.supportsTextSelect)){ + + if(CursorsEnabled) + CursorManager.removeCursor(_grabbingCursorID); + + if(TextSelectEnabled && CursorsEnabled){ + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + }else if(CursorsEnabled && !(event.target is IFlexPaperPluginControl) || (event.target.parent !=null && event.target.parent.parent !=null && event.target.parent.parent is IFlexPaperPluginControl)){ + resetCursor(); + } + } + } + + private function displayContainerDoubleClickHandler(event:MouseEvent):void{ + if(TextSelectEnabled){return;} + if(ViewMode == ViewModeEnum.PORTRAIT) + FitMode = (FitMode == FitModeEnum.FITWIDTH)?FitModeEnum.FITHEIGHT:FitModeEnum.FITWIDTH; + + if(UsingExtViewMode) + CurrExtViewMode.handleDoubleClick(event); + } + + private function displayContainerMouseDownHandler(event:MouseEvent):void{ + if(_viewMode==ViewModeEnum.PORTRAIT||(UsingExtViewMode && CurrExtViewMode.supportsTextSelect)){ + + if(CursorsEnabled) + CursorManager.removeCursor(_grabCursorID); + + if(TextSelectEnabled && CursorsEnabled){ + _grabbingCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + }else if(CursorsEnabled){ + _grabbingCursorID = CursorManager.setCursor(MenuIcons.GRABBING); + } + } + + if(UsingExtViewMode) + CurrExtViewMode.handleMouseDown(event); + } + + private function displayContainerrolloutHandler(event:Event):void{ + if(CursorsEnabled) + CursorManager.removeAllCursors(); + } + + private function wheelHandler(evt:MouseEvent):void { + _paperContainer.removeEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler); + + var t:Timer = new Timer(1,1); + t.addEventListener("timer", addMouseScrollListener,false,0,true); + t.start(); + + _paperContainer.dispatchEvent(evt.clone()); + } + + private function addMouseScrollListener(e:Event):void { + _paperContainer.addEventListener(MouseEvent.MOUSE_WHEEL, wheelHandler,false,0,true); + } + + private function keyboardHandler(event:KeyboardEvent):void{ + if(event.keyCode == Keyboard.DOWN){ + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 10; + } + if(event.keyCode == Keyboard.UP){ + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 10; + } + if(event.keyCode == Keyboard.PAGE_DOWN){ + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition + 300; + } + if(event.keyCode == Keyboard.PAGE_UP){ + _paperContainer.verticalScrollPosition = _paperContainer.verticalScrollPosition - 300; + } + if(event.keyCode == Keyboard.HOME){ + _paperContainer.verticalScrollPosition = 0; + } + if(event.keyCode == Keyboard.END){ + _paperContainer.verticalScrollPosition = _paperContainer.maxVerticalScrollPosition; + } + } + + private function sizeChanged(evt:Event):void{ + _skinImgDo.source = _skinImg; + _skinImgDo.x = this.width-_skinImg.width - 27; _skinImgDo.y = this.height-_skinImg.height - 10; + } + + private function skinMouseOver(evt:MouseEvent):void{ + _skinImgDo.addChild(_skinImgc); + } + + private function skinMouseOut(evt:MouseEvent):void{ + if(_skinImgc.parent==_skinImgDo){_skinImgDo.removeChild(_skinImgc);} + } + + private function skinMouseDown(evt:MouseEvent):void{ + dispatchEvent(new Event("onLogoClicked")); + } + + override protected function commitProperties():void { + super.commitProperties(); + + if(_swfFileChanged && _swfFile != null && _swfFile.length > 0){ // handler for when the Swf file has changed. + + dispatchEvent(new Event("onDocumentLoading")); + + _swfFileChanged = false; + } + } + + private function resizeMc(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{ + maxH = maxH == 0 ? maxW : maxH; + mc.width = maxW; + mc.height = maxH; + if (constrainProportions) { + mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY; + } + } + + private function onLoadProgress(event:ProgressEvent):void{ + var e:ProgressEvent = new ProgressEvent("onLoadingProgress") + e.bytesTotal = event.bytesTotal; + e.bytesLoaded = event.bytesLoaded; + dispatchEvent(e); + } + + private function onDocumentLoadedErrorHandler(event:Event):void{ + dispatchEvent(event); + } + + private function swfComplete(event:SwfLoadedEvent):void{ + if(!ProgressiveLoading){ + try{ + if(event.swfObject.content != null && (event.swfObject.content is MovieClip || event.swfObject.content is Bitmap)) + _libMC = new SwfDocument(event.swfObject.content as DisplayObject); + DupImage.paperSource = _libMC.getDocument(); + }catch(e:Error){ + if(!_docLoader.Resigned){_docLoader.signFileHeader(_docLoader.InputBytes);return;} + } + + if((_libMC == null || (event.swfObject!=null && event.swfObject.content != null && event.swfObject.content is AVM1Movie)) && !_docLoader.Resigned){_docLoader.signFileHeader(_docLoader.InputBytes);return;} + + _inputBytes = _docLoader.InputBytes; + + if(_libMC.height>0&&_docLoader.LoaderList==null){createLoaderList();} + + if(!_docLoader.PagesSplit) + numPages = _libMC.totalFrames; + + _swfLoaded = true + _libMC.getDocument().cacheAsBitmap = true; + _libMC.getDocument().opaqueBackground = 0xFFFFFF; + reCreateAllPages(); + + _bbusyloading = false; + repositionPapers(); + //dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED,numPages)); + }else{ + if(event.swfObject.content != null){ + var mobj:Object = event.swfObject.content; + var firstLoad:Boolean = false; + + if(mobj is AVM1Movie || _loaderptr != null){ + _inputBytes = _docLoader.InputBytes; + + if(_loaderptr==null){ + _docLoader.postProcessBytes(_inputBytes); + _loaderptr = new Loader(); + _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete,false,0,true); + } + + _docLoader.signFileHeader(_inputBytes,_loaderptr); + _loaderptr.unloadAndStop(true); + _loaderptr.loadBytes(_inputBytes,StreamUtil.getExecutionContext()); + } + + if(mobj is MovieClip){ + _libMC = new SwfDocument(mobj as MovieClip); + _libMC.getDocument().cacheAsBitmap = true; + _libMC.getDocument().opaqueBackground = 0xFFFFFF; + + if(_libMC.height>0&&_docLoader.LoaderList==null){createLoaderList();} + DupImage.paperSource = _libMC.getDocument(); + + if(!_docLoader.PagesSplit) + numPages = _libMC.totalFrames; + + firstLoad = _pageList == null || (_pageList.length == 0 && numPages > 0); + + if(_loaderptr==null){_inputBytes = _docLoader.InputBytes;}else{_inputBytes = _loaderptr.contentLoaderInfo.bytes;} + + if(_libMC.framesLoaded > 0) + addInLoadedPages(); + + flash.utils.setTimeout(function():void{ + try{ + var bDocLoaded:Boolean=(_libMC.framesLoaded == _libMC.totalFrames && _frameLoadCount != _libMC.framesLoaded); + + if(_libMC.framesLoaded>_frameLoadCount){ + repositionPapers(); + if(_docLoader.LoaderList.length>0 && _viewMode == ViewModeEnum.PORTRAIT){_bbusyloading = true; _docLoader.LoaderList[_docLoader.LoaderList.length-1].unloadAndStop(true); _docLoader.LoaderList[_docLoader.LoaderList.length-1].loadBytes(_libMC.loaderInfo.bytes,StreamUtil.getExecutionContext());} + _frameLoadCount = _libMC.framesLoaded; + } + + if(bDocLoaded) + dispatchEvent(new DocumentLoadedEvent(DocumentLoadedEvent.DOCUMENT_LOADED,numPages)); + } catch (e:*) {} + },500); + + + _bbusyloading = false; + _swfLoaded = true + } + } + } + } + + private function deleteDisplayContainer():void{ + if(_displayContainer!=null){ + _displayContainer.removeAllChildren(); + _displayContainer.removeEventListener(MouseEvent.ROLL_OVER,displayContainerrolloverHandler); + _displayContainer.removeEventListener(MouseEvent.ROLL_OUT,displayContainerrolloutHandler); + _displayContainer.removeEventListener(MouseEvent.MOUSE_DOWN,displayContainerMouseDownHandler); + _displayContainer.removeEventListener(MouseEvent.MOUSE_UP,displayContainerMouseUpHandler); + _displayContainer.removeEventListener(MouseEvent.DOUBLE_CLICK,displayContainerDoubleClickHandler); + } + } + + private function deleteLoaderList():void{ + if(_docLoader==null){return;} + if(_docLoader.LoaderList!=null){ + for(var i:int=0;i<_docLoader.LoaderList.length;i++){ + if(_docLoader.LoaderList[i].parent!=null){ + _docLoader.LoaderList[i].parent.removeChild(_docLoader.LoaderList[i]); + } + + if(_docLoader.LoaderList[i].contentLoaderInfo!=null){ + _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(Event.COMPLETE, bytesLoaded); + _docLoader.LoaderList[i].contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,docLoaderIOErrorListener); + } + + _docLoader.LoaderList[i].removeEventListener(Event.ENTER_FRAME,onframeenter); + _docLoader.LoaderList[i].unloadAndStop(true); + + delete(_docLoader.LoaderList[i]); + _docLoader.LoaderList[i]=null; + } + } + + _docLoader.LoaderList = null; + } + + public function deleteSelectionMarker():void{ + if(_selectionMarker!=null&&_selectionMarker.parent!=null){ + _selectionMarker.parent.removeChild(_selectionMarker); + + _selectionMarker = null; + } + } + + private function deleteLibMC():void{ + if(_libMC!=null){ + if(_libMC.parent!=null && _libMC.parent is Loader){ + (_libMC.parent as Loader).unloadAndStop(true); + } + + _libMC = null; + } + } + + private function deleteLoaderPtr():void{ + if(_loaderptr!=null){ + if(_loaderptr.parent!=null){ + _loaderptr.removeChild(_loaderptr); + } + + if(_loaderptr.contentLoaderInfo !=null){ + _loaderptr.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); + } + + _loaderptr.unloadAndStop(true); + _loaderptr = null; + } + } + + private function clearPlugins():void{ + if(_pluginList==null){return;} + + for(var pl:int=0;pl<_pluginList.length;pl++){ + _pluginList[pl].clear(); + } + } + + private function deletePageList():void{ + if(_pageList!=null){ + for(var pl:int=0;pl<_pageList.length;pl++){ + + _pageList[pl].removeEventListener(MouseEvent.MOUSE_OVER,dupImageMoverHandler); + _pageList[pl].removeEventListener(MouseEvent.MOUSE_OUT,dupImageMoutHandler); + _pageList[pl].removeEventListener(MouseEvent.CLICK,dupImageClickHandler); + _pageList[pl].removeEventListener(MouseEvent.MOUSE_DOWN,textSelectorMouseDownHandler); + + if(_pageList[pl].parent!=null){ + _pageList[pl].removeAllChildren(); + _pageList[pl].source = null; + _pageList[pl].parent.removeChild(_pageList[pl]); + } + + delete(_pageList[pl]); + _pageList[pl]=null;} + } + + DupImage.paperSource = null; + + _pageList = null; + } + + private function deleteFLoader():void{ + if(_docLoader!=null){ + _docLoader.stream.removeEventListener(ProgressEvent.PROGRESS, onLoadProgress); + _docLoader.resetURLStream(); + } + + /*if(_loader!=null){ + _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfComplete); + _loader.unloadAndStop(true); + _loader = null; + }*/ + + //_docLoader = null; + + /*_loader = new Loader(); + if(!_loader.contentLoaderInfo.hasEventListener(Event.COMPLETE)) + _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete,false,0,true);*/ + } + + public function addInLoadedPages(recreate:Boolean = false):void{ + if(recreate){ + _displayContainer.removeAllChildren(); deletePageList(); + } + + if(_pageList==null || (_pageList != null && _pageList.length != numPages)){ + _pageList = new Array(numPages); + if(_markList==null){_markList = new Array(numPages);} + + _displayContainer.visible = false; + _libMC.stop(); + + var w:Number=0; var h:Number=0; + _libMC.gotoAndStop(1); + w = _libMC.width; h=_libMC.height; + + for(var i:int=0;i0)?_libMC.width:w,(_libMC.height>0)?_libMC.height:h); + } + + addPages(); + + if(_pluginList!=null){ + for(var p:int=0;p<_pluginList.length;p++){ + _pluginList[p].init(); + } + } + + //if(_fitWidthOnLoad){_scale = getFitWidthFactor();} + //if(_fitPageOnLoad){_scale = getFitHeightFactor();} + } + + flash.utils.setTimeout(repositionPapers,500); + } + + public function reCreateAllPages():void{ + if(!_swfLoaded){return;} + + _displayContainer.visible = false; + _displayContainer.removeAllChildren(); + + deletePageList(); + _pageList = new Array(numPages); + if(_markList==null){_markList = new Array(numPages);} + + if(_pluginList!=null){ + for(var p:int=0;p<_pluginList.length;p++){ + _pluginList[p].init(); + } + } + + _libMC.stop(); + + var w:Number=0; var h:Number=0; + _libMC.gotoAndStop(1); + w = _libMC.width; h=_libMC.height; + + for(var i:int=0;i0)?_libMC.width:w,(_libMC.height>0)?_libMC.height:h); + } + + addPages(); + + // kick off the first page to load + if(!_docLoader.PagesSplit){ + if(_docLoader.LoaderList.length>0){_bbusyloading = true; _docLoader.LoaderList[0].unloadAndStop(true); _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes,StreamUtil.getExecutionContext());} + }else{ + if(_docLoader.LoaderList.length>0 && (_viewMode == ViewModeEnum.PORTRAIT) && _libMC.loaderInfo!=null && _libMC.loaderInfo.bytes != null) + { + _bbusyloading = true; + _docLoader.LoaderList[0].pageStartIndex = 1; + _docLoader.LoaderList[0].loadBytes(_libMC.loaderInfo.bytes,StreamUtil.getExecutionContext()); + } + } + + if(_docLoader.LoaderList.length>0 && UsingExtViewMode){CurrExtViewMode.initOnLoading();} + } + + private function createLoaderList():void + { + _docLoader.LoaderList = new Array(Math.round(getCalculatedHeight(_paperContainer)/(_libMC.height*_minZoomSize))+(_docLoader.PagesSplit)?5:1); + + if(UsingExtViewMode && CurrExtViewMode.loaderListLength > _docLoader.LoaderList.length) + _docLoader.LoaderList = new Array(CurrExtViewMode.loaderListLength); + + { + for(var li:int=0;li<_docLoader.LoaderList.length;li++){ + _docLoader.LoaderList[li] = new DupLoader(); + _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(Event.COMPLETE, bytesLoaded,false,0,true); + _docLoader.LoaderList[li].contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,docLoaderIOErrorListener); + _docLoader.LoaderList[li].addEventListener(Event.ENTER_FRAME,onframeenter,false,0,true); + } + } + } + + private function docLoaderIOErrorListener(e:IOErrorEvent):void{ + if(_docLoader!=null&&_docLoader.PagesSplit){ + dispatchEvent(new ErrorLoadingPageEvent(ErrorLoadingPageEvent.ERROR_LOADING_PAGE,e.target.pageStartIndex)); + } + } + + private function getCalculatedHeight(obj:DisplayObject):Number{ + var pHeight:Number = 0; + var oPercHeight:Number = 0; + + pHeight = obj.height; + if(pHeight>0){return pHeight;} + if((obj as Container).percentHeight>0){oPercHeight=(obj as Container).percentHeight;} + + while(obj.parent != null){ + if(obj.parent.height>0){pHeight = obj.parent.height * (oPercHeight/100);break;} + obj = obj.parent; + } + + return pHeight; + } + + public var snap:TextSnapshot; + private var searchIndex:int = -1; + private var searchPageIndex:int = -1; + private var _selectionMarker:ShapeMarker; + private var prevSearchText:String = ""; + private var prevYsave:Number=-1; + private var _markList:Array; + private var prevSearchIndexList:Array; + + public function get SearchPageIndex():int { + return searchPageIndex; + } + + public function set SearchPageIndex(s:int):void { + searchPageIndex = s; + } + + private var _searchExtracts:Array; + + public function searchTextByService(text:String):void{ + if(prevSearchText != text){ + _searchExtracts = new Array(numPages); + searchPageIndex = -1; + prevSearchText = text; + searchIndex = -1; + prevSearchIndexList = new Array(); + } + + if(_selectionMarker!=null && _selectionMarker.parent != null){_selectionMarker.parent.removeChild(_selectionMarker);} + + if(searchPageIndex == -1){ + searchPageIndex = currPage; + } + + if(_searchExtracts[searchPageIndex-1] == null && searchPageIndex!=currPage){ + var serve:HTTPService = new HTTPService(); + var url = SearchServiceUrl; + url = TextMapUtil.StringReplaceAll(url,"[page]",searchPageIndex.toString()) + url = TextMapUtil.StringReplaceAll(url,"[searchterm]",text) + url = encodeURI(url); + + serve.method = "GET"; + serve.url = url; + serve.resultFormat = "text"; + serve.addEventListener("result",searchByServiceResult); + serve.addEventListener(FaultEvent.FAULT,searchByServiceFault); + serve.send(); + }else{ // perform actual search + if((_searchExtracts[searchPageIndex-1]!=null && _searchExtracts[searchPageIndex-1].length>0 && Number(_searchExtracts[searchPageIndex-1]) >= 0) || searchPageIndex==currPage){ + if(searchPageIndex!=currPage){ + _performSearchOnPageLoad=true; + _pendingSearchPage = searchPageIndex; + gotoPage(searchPageIndex); + } + else{ + snap = _pageList[searchPageIndex-1].textSnapshot; + searchIndex = snap.findText((searchIndex==-1?0:searchIndex),adjustSearchTerm(text),false); + var tri:Array; + + if(searchIndex > 0){ // found a new match + _selectionMarker = new ShapeMarker(); + _selectionMarker.graphics.beginFill(0x0095f7,0.3); + + tri = snap.getTextRunInfo(searchIndex,searchIndex+text.length-1); + if(tri.length>0){ + prevYsave = tri[0].matrix_ty; + drawCurrentSelection(0x0095f7,_selectionMarker,tri); + } + + if(prevYsave>0){ + _selectionMarker.graphics.endFill(); + _adjGotoPage = (ViewMode==ViewModeEnum.PORTRAIT)?(prevYsave) * _scale - 50:0; + gotoPage(searchPageIndex); + } + + searchIndex = searchIndex + text.length; + }else{ + if(searchPageIndex+1<=numPages){ + searchPageIndex++; + searchIndex = -1; + + searchTextByService(prevSearchText); + }else{ + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + } + }else{ + if(searchPageIndex+1<=numPages){ + searchPageIndex++; + searchIndex = -1; + + searchTextByService(prevSearchText); + }else{ + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + } + } + + private function searchByServiceResult(evt:ResultEvent):void { + var textExtract:String = evt.result.toString(); + _searchExtracts[searchPageIndex-1] = textExtract; + + searchTextByService(prevSearchText); + } + + private function searchByServiceFault(evt:FaultEvent):void{ + dispatchEvent(new Event("onNoMoreSearchResults")); + } + + public function searchText(text:String, clearmarklist:Boolean=true):void{ + if(text==null){return;} + + if(text.length==0){return;} + text = text.toLowerCase(); + + if(_docLoader.PagesSplit&&SearchServiceUrl!=null&&SearchServiceUrl.length>0) + return searchTextByService(text); + + var tri:Array; + + if(prevSearchText != text){ + searchIndex = -1; + prevSearchIndexList = new Array(); + prevSearchText = text; + + if(SearchMatchAll){ + var spi:int = 1; + var si:int = -1; + + if(clearmarklist){ + if(_markList!=null){ + for(var i:int=0;i<_markList.length;i++){ + if(_markList[i]!=null && _markList[i].parent !=null){ + _markList[i].parent.removeChild(_markList[i]); + } + } + } + + _markList = new Array(numPages); + } + + if(text.indexOf("|")>0){ + var phrases:Array = text.split("|"); + for(var sf:int=0;sf0){ + var sm:ShapeMarker = new ShapeMarker(); + sm.PageIndex = spi; + + tri = snap.getTextRunInfo(si,si+text.length-1); + drawCurrentSelection(0x0095f7,sm,tri,false,0.25); + + + if( _markList[spi-1] == null){ + _markList[spi-1] = new UIComponent(); + } + + _markList[spi-1].addChild(sm); + + } + + if(si==-1) + spi++; + else + si++; + } + } + } + + + if(_selectionMarker!=null && _selectionMarker.parent != null){_selectionMarker.parent.removeChild(_selectionMarker);} + + // start searching from the current page + if(searchPageIndex == -1){ + searchPageIndex = currPage; + }else{ + var sio:Object = new Object(); + sio.searchIndex = searchIndex; + sio.searchPageIndex = searchPageIndex; + + prevSearchIndexList.push(sio); + searchIndex = searchIndex + text.length; + } + + _libMC.gotoAndStop(searchPageIndex); + + while((searchPageIndex -1) < numPagesLoaded){ + snap = _libMC.textSnapshot; + searchIndex = snap.findText((searchIndex==-1?0:searchIndex),adjustSearchTerm(text),false); + //searchIndex = TextMapUtil.checkUnicodeIntegrity(snap.getText(0,snap.charCount),text,_libMC).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); + //searchIndex = snap.getText(0,snap.charCount).toLowerCase().indexOf(text,(searchIndex==-1?0:searchIndex)); + //searchIndex = searchString(snap.getText(0,snap.charCount),text,searchIndex); + + if(searchIndex > 0){ // found a new match + _selectionMarker = new ShapeMarker(); + _selectionMarker.graphics.beginFill(0x0095f7,0.3); + + tri = snap.getTextRunInfo(searchIndex,searchIndex+text.length-1); + if(tri.length>0){ + prevYsave = tri[0].matrix_ty; + drawCurrentSelection(0x0095f7,_selectionMarker,tri); + } + + if(prevYsave>0){ + _selectionMarker.graphics.endFill(); + _adjGotoPage = (ViewMode==ViewModeEnum.PORTRAIT)?(prevYsave) * _scale - 50:0; + gotoPage(searchPageIndex); + break; + } + + } + + searchPageIndex++; + searchIndex = -1; + _libMC.gotoAndStop(searchPageIndex); + } + + if(searchIndex == -1){ // searched the end of the doc. + dispatchEvent(new Event("onNoMoreSearchResults")); + searchPageIndex = 1; + } + } + + public function nextSearchMatch(s:String):void{ + if(s!=prevSearchText){ + searchText(s); + }else{ + searchIndex = searchIndex + prevSearchText.length; + searchText(prevSearchText); + } + } + + public function prevSearchMatch():void{ + if(prevSearchText!=null&&prevSearchText.length>0){ + prevSearchIndexList.pop(); + + var sio:Object = prevSearchIndexList.pop(); + if(sio != null){ + searchIndex = sio.searchIndex - 1; + searchPageIndex = sio.searchPageIndex; + searchText(prevSearchText); + }else{ + searchIndex = 0; + searchPageIndex = 1; + searchText(prevSearchText); + } + } + } + + private function adjustSearchTerm(searchtxt:String):String{ + if(ResourceManager.getInstance().localeChain[0] == 'he_IL'){ + searchtxt = reverseString(searchtxt); + } + + return searchtxt; + } + + private function reverseString(string:String):String + { + var reversed:String = new String(); + for(var i:int = string.length -1; i >= 0; i--) + reversed += string.charAt(i); + return reversed; + } + + public function highlight(url:String):void{ + var serve:HTTPService = new HTTPService(); + serve.method = "GET"; + serve.url = url; + serve.resultFormat = "e4x" + serve.addEventListener("result",highlightResult); + serve.send(); + } + + private function highlightResult(evt:ResultEvent):void { + try{ + + for(var i:int=0;i<_markList.length;i++){ + if(_markList[i]!=null && _markList[i].parent !=null){ + _markList[i].parent.removeChild(_markList[i]); + } + } + + _markList = new Array(numPages); + + var highlightXML:XML = new XML(evt.result); + var pg:Number=0; + var pos:Number=-1; + var len:Number=-1; + var tri:Array; + var color:uint = 0x0095f7; + var text:String; + color = uint("0x" + String(highlightXML.Body.@color).substring(1, String(highlightXML.Body.@color).length)); + + for each (var item:XML in highlightXML.Body.Highlight.loc){ + pg = Number(item.@pg); + pos = Number(item.@pos); + len = Number(item.@len); + + _libMC.gotoAndStop(pg+1); + snap = _libMC.textSnapshot; + + var sm:ShapeMarker = new ShapeMarker(); + sm.PageIndex = pg+1; + + text = snap.getText(0,pos,false); + + for(var ci:int=0;ci 10000){ + pos = pos -1 ; + } + } + + tri = snap.getTextRunInfo(pos,pos+len); + + drawCurrentSelection(color,sm,tri,false,0.25); + + if( _markList[pg] == null){ + _markList[pg] = new UIComponent(); + } + + _markList[pg].addChild(sm); + } + + repositionPapers(); + + }catch (e:*) {} + } + + private function createPaper(index:int, w:Number, h:Number):void { + var di:DupImage = new DupImage(); + di.scaleX = di.scaleY = _scale; + di.dupIndex = index; + di.width = w; + di.height = h; + di.init(); + //di.mouseChildren = false; + di.addEventListener(MouseEvent.MOUSE_OVER,dupImageMoverHandler,false,0,true); + di.addEventListener(MouseEvent.MOUSE_OUT,dupImageMoutHandler,false,0,true); + di.addEventListener(MouseEvent.CLICK,dupImageClickHandler,false,0,true); + di.addEventListener(MouseEvent.MOUSE_DOWN,textSelectorMouseDownHandler,false,0,true); + + if(_pluginList!=null) + for(var pl:int=0;pl<_pluginList.length;pl++) + _pluginList[pl].bindPaperEventHandler(di); + + _pageList[index-1] = di; + + _pageList[index-1].resetPage(_libMC.width,_libMC.height,_scale); + } + + private function textSelectorMouseDownHandler(event:MouseEvent):void{ + if(!TextSelectEnabled){return;} + if(_selectionMarker!=null&&_selectionMarker.parent!=null){_selectionMarker.parent.removeChild(_selectionMarker);_selectionMarker=null;} + + try{ + if(!(event.target.content is MovieClip)){ + if(!(event.target is MovieClip)){ + return; + }else{ + _selectionMc = (event.target as MovieClip); + } + }else{ + _selectionMc = (event.target.content as MovieClip); + } + }catch (e:*) {return;} + + _currentlySelectedText = ""; + _firstHitIndex = -1; + _lastHitIndex = -1; + _currentSelectionPage = -1; + snap = _selectionMc.textSnapshot; + + systemManager.addEventListener( + MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true,0,true); + + systemManager.addEventListener( + MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true,0,true); + + systemManager.stage.removeEventListener( + Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); + } + + private var _firstHitIndex:int = -1; + private var _lastHitIndex:int = -1; + private var _currentlySelectedText:String = ""; + private var _tri:Array; + private var _currentSelectionPage:int = -1; + private var _selectionMc:MovieClip + private var _selecting:Boolean = false; + public static var DefaultMarkerColor:uint = 0xb5deff; + private var _markerColor:uint = 0xb5deff; + public static var DefaultSelectionColor:uint = 0x0095f7; + private var _selectionColor:uint = 0x0095f7; + + public function get MarkerColor():uint { + return _markerColor; + } + + public function set MarkerColor(c:uint):void { + _markerColor = c; + } + + public function get SelectionColor():uint { + return _selectionColor; + } + + public function set SelectionColor(c:uint):void { + _selectionColor = c; + } + + public function get CurrentSelectionPage():int { + return _currentSelectionPage; + } + + public function get FirstHitIndex():int { + return _firstHitIndex; + } + + public function get LastHitIndex():int { + return _lastHitIndex; + } + + public function get TextRunInfo():Array { + return _tri; + } + + public function set TextRunInfo(a:Array):void { + _tri = a; + } + + private function textSelectorMoveHandler(event:MouseEvent):void{ + event.stopImmediatePropagation(); + + var hitIndex:int = snap.hitTestTextNearPos(event.target.parent.mouseX,event.target.parent.mouseY,10)+((_firstHitIndex==-1)?0:1); + + if(hitIndex==_lastHitIndex||hitIndex<0){return;} + if(!(event.target is DupLoader)){return;} + + if(_firstHitIndex==-1){_firstHitIndex=hitIndex;} + + if(_docLoader.PagesSplit) + _currentSelectionPage = (_selectionMc.parent as DupLoader).pageStartIndex; + else + _currentSelectionPage = _selectionMc.currentFrame; + + snap.setSelectColor(_markerColor); + snap.setSelected(0,snap.charCount,false); + + if(_firstHitIndex<=hitIndex){ + snap.setSelected(_firstHitIndex,hitIndex,true); + }else{ + snap.setSelected(hitIndex,_firstHitIndex,true); + } + + if(_selectionMarker!=null&&_selectionMarker.parent!=null){_selectionMarker.parent.removeChild(_selectionMarker);} + + if(_docLoader.PagesSplit) + searchPageIndex = (_selectionMc.parent as DupLoader).pageStartIndex; + else + searchPageIndex = _selectionMc.currentFrame; + + _lastHitIndex = hitIndex; + } + + public function drawCurrentSelection(color:uint, shape:Sprite, tri:Array, strikeout:Boolean=false, alpha:Number=0.3):void{ + var ly:Number=-1; + var li:int;var lx:int; + var miny:int=-1; + var minx:int=-1; + var maxy:int=-1; + var maxx:int=-1; + snap.setSelected(1,snap.charCount,false); + + shape.graphics.beginFill(color,(strikeout)?0.5:alpha); + var rect_commands:Vector.; + rect_commands = new Vector.((tri.length) * 5, true); + + var rect_coords:Vector.; + rect_coords = new Vector.((tri.length) * 10, true); + + for(var i:int=0;itri[i].corner1y){miny=tri[i].corner1y;} + if(minx==-1||minx>tri[li].corner3x){minx=tri[li].corner3x;} + if(maxy==-1||maxytri[li].corner3x) + rect_coords[i*10 + 2] = rect_coords[i * 10] + tri[i].corner1x-tri[li].corner3x; + else if(i==tri.length-2 && tri[i+1].corner1x > tri[li].corner3x) + rect_coords[i*10 + 2] = rect_coords[i * 10] + tri[i+1].corner1x-tri[li].corner3x; + else if(i==tri.length-2 && tri[i+1].corner1x < tri[li].corner3x){ + rect_coords[i*10 + 2] = rect_coords[i * 10] + tri[li].corner1x-tri[li].corner3x; + rect_coords[i*10] = tri[li].corner3x; + + /* add an extra struct for the last char*/ + rect_commands[(i+1)*5] = 1; + rect_commands[(i+1)*5 + 1] = 2; + rect_commands[(i+1)*5 + 2] = 2; + rect_commands[(i+1)*5 + 3] = 2; + rect_commands[(i+1)*5 + 4] = 2; + + rect_coords[(i+1)*10] = tri[(i+1)].corner3x; + rect_coords[(i+1)*10 + 1] = tri[(i+1)].corner1y; + rect_coords[(i+1)*10 + 2] = rect_coords[(i+1) * 10] + tri[i+1].corner1x-tri[i+1].corner3x; + rect_coords[(i+1)*10 + 3] = rect_coords[(i+1)*10 + 1]; + rect_coords[(i+1)*10 + 4] = rect_coords[(i+1)*10 + 2]; + rect_coords[(i+1)*10 + 5] = rect_coords[(i+1)*10 + 1] + tri[i+1].corner3y-tri[i+1].corner1y; + rect_coords[(i+1)*10 + 6] = rect_coords[(i+1)*10]; + rect_coords[(i+1)*10 + 7] = rect_coords[(i+1)*10 + 5]; + rect_coords[(i+1)*10 + 8] = rect_coords[(i+1)*10]; + rect_coords[(i+1)*10 + 9] = rect_coords[(i+1)*10 + 1]; + } + + rect_coords[i*10 + 3] = rect_coords[i*10 + 1]; + rect_coords[i*10 + 4] = rect_coords[i*10 + 2]; + rect_coords[i*10 + 6] = rect_coords[i*10]; + rect_coords[i*10 + 7] = rect_coords[i*10 + 5]; + rect_coords[i*10 + 8] = rect_coords[i*10]; + rect_coords[i*10 + 9] = rect_coords[i*10 + 1]; + + ly=tri[i+1].corner1y;lx=tri[i+1].corner3x;li=i+1; + } + shape.graphics.drawPath(rect_commands,rect_coords,"nonZero"); + shape.graphics.endFill(); + + // draw a transparent box covering the whole area to increase hitTest accuracy on mousedown + shape.graphics.beginFill(0xffffff,0); + shape.graphics.drawRect(minx,miny,maxx-minx,maxy-miny); + shape.graphics.endFill(); + } + + private function textSelectorMouseUpHandler(event:MouseEvent):void{ + stopSelecting(); + } + + private function textSelectorMouseLeaveHandler(event:MouseEvent):void{ + stopSelecting(); + } + + private function stopSelecting():void{ + systemManager.removeEventListener( + MouseEvent.MOUSE_MOVE, textSelectorMoveHandler, true); + + systemManager.removeEventListener( + MouseEvent.MOUSE_UP, textSelectorMouseUpHandler, true); + + systemManager.stage.removeEventListener( + Event.MOUSE_LEAVE, textSelectorMouseLeaveHandler); + + var rev:int; + if(_firstHitIndex>_lastHitIndex){rev=_firstHitIndex;_firstHitIndex=_lastHitIndex;_lastHitIndex=rev;} + + //var totaltext:String = snap.getText(0,snap.charCount,false); + + if(_firstHitIndex>=0 && _lastHitIndex>0) + _currentlySelectedText = snap.getText(_firstHitIndex,_lastHitIndex-1,false); + else + _currentlySelectedText = ""; + + + if(_currentlySelectedText.length==0 && _firstHitIndex>=0 && _lastHitIndex>0){ + _currentlySelectedText = snap.getText(_firstHitIndex,_lastHitIndex-1,true); + } + + _currentlySelectedText = TextMapUtil.checkUnicodeIntegrity(_currentlySelectedText,null,_libMC); + + /* trace(_currentlySelectedText.charCodeAt(0)+"|"); + trace(_currentlySelectedText.charCodeAt(1)+"|"); + trace(_currentlySelectedText.charCodeAt(2)+"|"); + trace(_currentlySelectedText.charCodeAt(3)+"|"); + */ + + + _tri = snap.getTextRunInfo(_firstHitIndex,_lastHitIndex-1); + + if(_currentSelectionPage>0){ + if(_selectionMarker!=null&&_selectionMarker.parent!=null){_selectionMarker.parent.removeChild(_selectionMarker);} + + _selectionMarker = new ShapeMarker(); + _selectionMarker.PageIndex = _currentSelectionPage; + drawCurrentSelection(_selectionColor,_selectionMarker,_tri); + snap.setSelected(_firstHitIndex,_lastHitIndex,false); + _pageList[_currentSelectionPage-1].addChildAt(_selectionMarker,_pageList[_selectionMc.currentFrame-1].numChildren); + } + + dispatchEvent(new SelectionCreatedEvent(SelectionCreatedEvent.SELECTION_CREATED,_currentlySelectedText)); + + _selectionMc = null; + } + + private function dupImageClickHandler(event:MouseEvent):void{ + stage.stageFocusRect = false; + stage.focus = event.target as InteractiveObject; + + if((_viewMode == ViewModeEnum.TILE) && event.target != null && event.target is DupImage){ + ViewMode = 'Portrait'; + _scrollToPage = (event.target as DupImage).dupIndex; + }else{ + _dupImageClicked = true; + var t:Timer = new Timer(100,1); + t.addEventListener("timer", resetClickHandler,false,0,true); + t.start(); + + if(event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("http")>=0){ + dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, + (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("http")))); + }else if(event.target is SimpleButton && (event.target as SimpleButton).name.indexOf("url:")>=0){ + dispatchEvent(new ExternalLinkClickedEvent(ExternalLinkClickedEvent.EXTERNALLINK_CLICKED, + (event.target as SimpleButton).name.substring((event.target as SimpleButton).name.indexOf("url:")))); + } + + } + } + + private function resetClickHandler(e:Event):void { + _dupImageClicked = false; + } + + private function dupImageMoverHandler(event:MouseEvent):void{ + + if(_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage){ + addGlowFilter(event.target as DupImage); + }else{ + if(event.target is flash.display.SimpleButton || event.target is SpriteAsset || (event.target is IFlexPaperPluginControl) || (event.target.parent !=null && event.target.parent.parent !=null && event.target.parent.parent is IFlexPaperPluginControl)){ + CursorManager.removeAllCursors(); + }else{ + if(TextSelectEnabled && CursorsEnabled){ + _grabCursorID = CursorManager.setCursor(MenuIcons.TEXT_SELECT_CURSOR); + }else if(CursorsEnabled){ + resetCursor(); + } + } + } + } + + public function resetCursor():void{ + if(CursorsEnabled) + _grabCursorID = CursorManager.setCursor(MenuIcons.GRAB); + } + + private function dupImageMoutHandler(event:MouseEvent):void{ + if(_viewMode == ViewModeEnum.TILE && event.target != null && event.target is DupImage){ + (event.target as DupImage).filters = null; + (event.target as DupImage).addDropShadow(); + } + } + + private function addPages():void{ + for(var pi:int=0;pi<_pageList.length;pi++){ + if(!UsingExtViewMode) + _displayContainer.addChild(_pageList[pi]); + else + CurrExtViewMode.addChild(pi,_pageList[pi]); + } + } + + private var _splitpj:PrintJob; + private var _splitpjoptions:PrintJobOptions = new PrintJobOptions(); + private var _splitpjloading:Boolean=false; + private var _splitpjprinted:int = 0; + private var _splitpageNumList:Array; + + private function printSplitPaper(start:Boolean=false,range:String=""):void{ + if(start){ + _splitpj = new PrintJob(); + _loaderptr = new Loader(); + _loaderptr.contentLoaderInfo.addEventListener(Event.COMPLETE, printSplitPaperLoaded,false,0,true); + + if(range.length>0){ + if(range == "Current"){ + _splitpageNumList = new Array(); + _splitpageNumList[currPage] = true; + } + else{ + _splitpageNumList = range.split(","); + for(var i:int=0;i<_splitpageNumList.length;i++){ + if(_splitpageNumList[i].toString().indexOf("-")>-1){ + var rs:int = Number(_splitpageNumList[i].toString().substr(0,_splitpageNumList[i].toString().indexOf("-"))); + var re:int = Number(_splitpageNumList[i].toString().substr(_splitpageNumList[i].toString().indexOf("-")+1)); + for(var irs:int=rs;irs0) + (_swfContainer.getChildAt(0) as UIComponent).removeChildAt(0); + + (_swfContainer.getChildAt(0) as UIComponent).addChild(pageToPrint); + + _splitpj.addPage(_swfContainer,null,_splitpjoptions); + _splitpjloading = false; + _splitpjprinted++; + printSplitPaper(); + } + + public function printPaper():void{ + if(_docLoader.PagesSplit) + return printSplitPaper(true); + + if(_libMC.parent is DupImage){(_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument());} + _libMC.alpha = 1; + + var pj:PrintJob = new PrintJob(); + if(pj.start()){ + _libMC.stop(); + + if((pj.pageHeight/_libMC.height) < 1 && (pj.pageHeight/_libMC.height) < (pj.pageWidth/_libMC.width)) + _libMC.scaleX = _libMC.scaleY = (pj.pageHeight/_libMC.height); + else if((pj.pageWidth/_libMC.width) < 1) + _libMC.scaleX = _libMC.scaleY = (pj.pageWidth/_libMC.width); + + var options:PrintJobOptions = new PrintJobOptions(); + //options.printAsBitmap = true; + + var i:int=0; + _libMC.gotoAndStop(i+1); + while(_libMC.totalFrames > _libMC.currentFrame){ + if(_libMC.currentFrame==i+1){ + pj.addPage(_swfContainer,null,options); + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame+1); + } + pj.addPage(_swfContainer,null,options); + pj.send(); + } + + _libMC.scaleX = _libMC.scaleY = 1; + _libMC.alpha = 0; + + dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); + } + + public function printPaperRange(range:String):void{ + if(_docLoader.PagesSplit) + return printSplitPaper(true,range); + + if(_libMC.parent is DupImage){(_swfContainer.getChildAt(0) as UIComponent).addChild(_libMC.getDocument());} + _libMC.alpha = 1; + + var pageNumList:Array = new Array(); + + if(range == "Current"){ + pageNumList[currPage] = true; + }else{ + var splitPageNumList:Array = range.split(","); + for(var i:int=0;i-1){ + var rs:int = Number(splitPageNumList[i].toString().substr(0,splitPageNumList[i].toString().indexOf("-"))); + var re:int = Number(splitPageNumList[i].toString().substr(splitPageNumList[i].toString().indexOf("-")+1)); + for(var irs:int=rs;irs _libMC.currentFrame){ + if(_libMC.currentFrame==i+1){ + if(pageNumList[i+1] != null) + pj.addPage(_swfContainer,null,options); + + i++; + } + + _libMC.gotoAndStop(_libMC.currentFrame+1); + } + + if(pageNumList[_libMC.totalFrames] != null) + pj.addPage(_swfContainer,null,options); + + pj.send(); + + } + + _libMC.scaleX = _libMC.scaleY = 1; + _libMC.alpha = 0; + + dispatchEvent(new DocumentPrintedEvent(DocumentPrintedEvent.DOCUMENT_PRINTED)); + } + + private function addGlowFilter(img:Image):void{ + var filter : flash.filters.GlowFilter = new flash.filters.GlowFilter(0x111111, 1, 5, 5, 2, 1, false, false); + img.filters = [ filter ]; + } + + private function addDropShadow(img:Image):void + { + var filter : DropShadowFilter = new DropShadowFilter(); + filter.blurX = 4; + filter.blurY = 4; + filter.quality = 2; + filter.alpha = 0.5; + filter.angle = 45; + filter.color = 0x202020; + filter.distance = 6; + filter.inner = false; + img.filters = [ filter ]; + } + + } } diff --git a/docviewerflex/src/com/devaldi/controls/flexpaper/styles/default.css b/docviewerflex/src/com/devaldi/controls/flexpaper/styles/default.css index 3c1c5ba..e54c58d 100644 --- a/docviewerflex/src/com/devaldi/controls/flexpaper/styles/default.css +++ b/docviewerflex/src/com/devaldi/controls/flexpaper/styles/default.css @@ -4,10 +4,11 @@ fillColors: #e6e6e6, #fdfdfd; fillAlphas: 1, 1; borderColor: #8a8a8a; + backgroundColor: #EDEDED; } .viewerBackground { - backgroundImage: ClassReference("com.devaldi.skinning.GradientBackground"); + backgroundImage: ClassReference("com.devaldi.skinning.GradientBackground"); backgroundSize: "100%"; fillColors: #aab3b3, #d5dddd; fillAlphas: 1, 1; @@ -35,11 +36,11 @@ } .circles { - spinner-type: circles; + spinner-type: circles; } .lines { spinner-type: lines; spinner-highlight-color: #000000; spinner-color: #808080; - } + } diff --git a/docviewerflex/src/com/devaldi/streaming/AVM2Loader.as b/docviewerflex/src/com/devaldi/streaming/AVM2Loader.as index a71427a..5764cd3 100644 --- a/docviewerflex/src/com/devaldi/streaming/AVM2Loader.as +++ b/docviewerflex/src/com/devaldi/streaming/AVM2Loader.as @@ -1,409 +1,413 @@ /* - Copyright 2009 Erik Engström - - This file is part of FlexPaper. - - FlexPaper 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, version 3 of the License. - - FlexPaper 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 FlexPaper. If not, see . - - Inspired by the ForcibleLoader class by - BeInteractive! (www.be-interactive.org) - */ - -package com.devaldi.streaming { - -import com.devaldi.events.SwfLoadedEvent; - -import flash.display.DisplayObject; -import flash.display.Loader; -import flash.errors.EOFError; -import flash.events.ErrorEvent; -import flash.events.Event; -import flash.events.EventDispatcher; -import flash.events.IEventDispatcher; -import flash.events.IOErrorEvent; -import flash.events.ProgressEvent; -import flash.events.SecurityErrorEvent; -import flash.net.URLRequest; -import flash.net.URLStream; -import flash.system.LoaderContext; -import flash.utils.ByteArray; -import flash.utils.Endian; - - -/** - * Usage: - *
- * var loader:Loader = Loader(addChild(new Loader()));
- * var fLoader:ForcibleLoader = new ForcibleLoader(loader);
- * fLoader.load(new URLRequest('swf7.swf'));
- * 
- */ - -[Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] -[Event(name="onLoadersLoaded", type="flash.events.Event")] -[Event(name="onSwfLoaded", type="com.devaldi.events.SwfLoadedEvent")] - -public class AVM2Loader implements IDocumentLoader { - private var dispatcher:IEventDispatcher = new EventDispatcher(); - private var _loader:Loader = new Loader(); - private var _stream:URLStream; - private var _inputBytes:ByteArray; - private var _loaderCtx:LoaderContext; - private var _resigned:Boolean = false; - private var _bytesPending:uint = 0; - private var _prevLength:uint = 0; - private var _attempts:Number = 0; - private var _doretry:Boolean = true; - private var _request:URLRequest; - public var version:uint = 0; - private var _progressive:Boolean = false; - private var _loaderList:Array; - private var _pagesSplit:Boolean = false; - - public function AVM2Loader(loaderCtx:LoaderContext, progressive:Boolean) { - _loaderCtx = loaderCtx; - _progressive = progressive; - resetURLStream(); - } - - public function resetURLStream():void { - - if (_stream != null) { - try { - if (stream.connected) { - _stream.close(); +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . + +Inspired by the ForcibleLoader class by +BeInteractive! (www.be-interactive.org) +*/ + +package com.devaldi.streaming +{ + import com.devaldi.events.SwfLoadedEvent; + + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.errors.EOFError; + import flash.events.ErrorEvent; + import flash.events.Event; + import flash.events.EventDispatcher; + import flash.events.IEventDispatcher; + import flash.events.IOErrorEvent; + import flash.events.ProgressEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLStream; + import flash.system.LoaderContext; + import flash.utils.ByteArray; + import flash.utils.Endian; + + /** + * Usage: + *
+         * var loader:Loader = Loader(addChild(new Loader()));
+         * var fLoader:ForcibleLoader = new ForcibleLoader(loader);
+         * fLoader.load(new URLRequest('swf7.swf'));
+         * 
+ */ + + [Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] + [Event(name="onLoadersLoaded", type="flash.events.Event")] + [Event(name="onSwfLoaded", type="com.devaldi.events.SwfLoadedEvent")] + + public class AVM2Loader implements IDocumentLoader + { + private var dispatcher:IEventDispatcher = new EventDispatcher(); + private var _loader:Loader = new Loader(); + private var _stream:URLStream; + private var _inputBytes:ByteArray; + private var _loaderCtx:LoaderContext; + private var _resigned:Boolean = false; + private var _bytesPending:uint = 0; + private var _prevLength:uint = 0; + private var _attempts:Number = 0; + private var _doretry:Boolean = true; + private var _request:URLRequest; + public var version:uint = 0; + private var numframes:int = -1; + private var _progressive:Boolean = false; + private var _loaderList:Array; + private var _pagesSplit:Boolean = false; + + public function AVM2Loader(loaderCtx:LoaderContext, progressive:Boolean) + { + _loaderCtx = loaderCtx; + _progressive = progressive; + resetURLStream(); + } + + public function resetURLStream():void{ + + if(_stream!=null){ + try{if(stream.connected){_stream.close();} + }catch(e:Error){} + + if(!_progressive){ + _stream.removeEventListener(Event.COMPLETE, completeHandler); + _stream.removeEventListener(ProgressEvent.PROGRESS , nonProgressiveProgress); + }else{ + _stream.removeEventListener(ProgressEvent.PROGRESS , streamProgressHandler); + _stream.removeEventListener(Event.COMPLETE, streamCompleteHandler); + } + + _stream.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + + _loader.unloadAndStop(true); + _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderComplete); + _loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + _loader = new Loader(); + + } + + _stream = new URLStream(); + + if(!_progressive){ + _stream.addEventListener(Event.COMPLETE, completeHandler,false,0,true); + _stream.addEventListener(ProgressEvent.PROGRESS , nonProgressiveProgress,false,0,true); + }else{ + _stream.addEventListener(ProgressEvent.PROGRESS , streamProgressHandler,false,0,true); + _stream.addEventListener(Event.COMPLETE, streamCompleteHandler,false,0,true); + } + + _stream.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + _stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete); + _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function loaderComplete(event:Event):void{ + dispatchEvent(new SwfLoadedEvent(SwfLoadedEvent.SWFLOADED,event.currentTarget)); + } + + public function get PagesSplit():Boolean{ + return _pagesSplit; + } + + public function set PagesSplit(b:Boolean):void{ + _pagesSplit = b; + } + + public function get LoaderList():Array{ + return _loaderList; + } + + public function set LoaderList(v:Array):void{ + _loaderList = v; + } + + public function get Resigned():Boolean{ + return _resigned; } - } catch(e:Error) { - } - - if (!_progressive) { - _stream.removeEventListener(Event.COMPLETE, completeHandler); - _stream.removeEventListener(ProgressEvent.PROGRESS, nonProgressiveProgress); - } else { - _stream.removeEventListener(ProgressEvent.PROGRESS, streamProgressHandler); - _stream.removeEventListener(Event.COMPLETE, streamCompleteHandler); - } - - _stream.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); - - _loader.unloadAndStop(true); - _loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderComplete); - _loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); - _loader = new Loader(); - - } - - _stream = new URLStream(); - - if (!_progressive) { - _stream.addEventListener(Event.COMPLETE, completeHandler, false, 0, true); - _stream.addEventListener(ProgressEvent.PROGRESS, nonProgressiveProgress, false, 0, true); - } else { - _stream.addEventListener(ProgressEvent.PROGRESS, streamProgressHandler, false, 0, true); - _stream.addEventListener(Event.COMPLETE, streamCompleteHandler, false, 0, true); - } - - _stream.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); - _stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); - - _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderComplete); - _loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); - } - - private function loaderComplete(event:Event):void { - dispatchEvent(new SwfLoadedEvent(SwfLoadedEvent.SWFLOADED, event.currentTarget)); - } - - public function get IsSplit():Boolean { - return _pagesSplit; - } - - public function set IsSplit(b:Boolean):void { - _pagesSplit = b; - } - - public function get LoaderList():Array { - return _loaderList; - } - - public function set LoaderList(v:Array):void { - _loaderList = v; - } - - public function get Resigned():Boolean { - return _resigned; - } - - public function get DocumentContainer():DisplayObject { - return _loader; - } - - public function get InputBytes():ByteArray { - return _inputBytes; - } - - public function set InputBytes(b:ByteArray):void { - _inputBytes = b; - } - - public function get stream():URLStream { - return _stream; - } - - public function get loader():Loader { - return _loader; - } - - public function set loader(value:Loader):void { - _loader = value; - } - - public function loadFromBytes(bytes:ByteArray):void { - _inputBytes = bytes; - - confirmBytesLoaded(); - } - - public function load(request:URLRequest, loaderCtx:LoaderContext):void { - //resetURLStream(); - - _attempts++; - _request = request; - _stream.load(request); - _inputBytes = new ByteArray(); - - // wait with this one.. seems a bit dodgy - //flash.utils.setTimeout(retry,7000); - } - - private function retry():void { - if (_attempts < 4 && _doretry) { - _attempts++; - _stream.load(_request); - flash.utils.setTimeout(retry, 7000); - } - } - - private function streamCompleteHandler(event:Event):void { - flash.utils.setTimeout(confirmBytesLoaded, 500); - _stream.close(); - } - - private function confirmBytesLoaded():void { - try { - _stream.readBytes(_inputBytes, _inputBytes.length); - _loader.unloadAndStop(true); - _loader.loadBytes(_inputBytes, _loaderCtx); - } - catch(e:Error) { // on error try again, version 9 of flash player sometimes fails. - _loader.unloadAndStop(true); - _loader.loadBytes(_inputBytes, _loaderCtx); - } - } - - private function nonProgressiveProgress(event:ProgressEvent):void { - _doretry = (_loader.contentLoaderInfo == null || _loader.contentLoaderInfo.bytesLoaded < 2000); - } - - private function streamProgressHandler(event:ProgressEvent):void { - //if there are no bytes do nothing - _stream.readBytes(_inputBytes, _inputBytes.length); - _bytesPending = _inputBytes.length - _prevLength; - - if (_inputBytes.length > 4) { - version = uint(_inputBytes[3]); - - if (version <= 9) { - updateVersion(9, _inputBytes); - } - } - - if (_bytesPending > (event.bytesTotal / 10) || (_loader.contentLoaderInfo != null && event.bytesTotal == _bytesPending + _loader.contentLoaderInfo.bytesLoaded)) { - _bytesPending = 0; - _prevLength = _inputBytes.length; - try { - _loader.unloadAndStop(true); - _loader.loadBytes(_inputBytes, _loaderCtx); - } - catch(e:Error) { // on error try again, version 9 of flash player sometimes fails. - _loader.unloadAndStop(true); - _loader.loadBytes(_inputBytes, _loaderCtx); - } - } - - _doretry = (_loader.contentLoaderInfo == null || _loader.contentLoaderInfo.bytesLoaded < 2000); - } - - private function completeHandler(event:Event):void { - _inputBytes = new ByteArray(); - _stream.readBytes(_inputBytes); - _stream.close(); - _inputBytes.endian = Endian.LITTLE_ENDIAN; - - if (isCompressed(_inputBytes)) { - uncompress(_inputBytes); - } - - version = uint(_inputBytes[3]); - - if (version <= 9) { - if (version == 8 || version == 9) { - flagSWF9Bit(_inputBytes); - } else if (version <= 7) { - insertFileAttributesTag(_inputBytes); - } - updateVersion(9, _inputBytes); - } - - loader.unloadAndStop(true); - loader.loadBytes(_inputBytes, _loaderCtx); - } - - public function isCompressed(bytes:ByteArray):Boolean { - return bytes[0] == 0x43; - } - - private function uncompress(bytes:ByteArray):void { - var cBytes:ByteArray = new ByteArray(); - cBytes.writeBytes(bytes, 8); - bytes.length = 8; - bytes.position = 8; - cBytes.uncompress(); - bytes.writeBytes(cBytes); - bytes[0] = 0x46; - cBytes.length = 0; - } - - private function getBodyPosition(bytes:ByteArray):uint { - var result:uint = 0; - - result += 3; // FWS/CWS - result += 1; // version(byte) - result += 4; // length(32bit-uint) - - var rectNBits:uint = bytes[result] >>> 3; - result += (5 + rectNBits * 4) / 8; // stage(rect) - - result += 2; - - result += 1; // frameRate(byte) - result += 2; // totalFrames(16bit-uint) - - return result; - } - - private function findFileAttributesPosition(offset:uint, bytes:ByteArray):int { - bytes.position = offset; - try { - for (; ;) { - var byte:uint = bytes.readShort(); - var tag:uint = byte >>> 6; - if (tag == 69) { - return bytes.position - 2; + public function get DocumentContainer():DisplayObject{ + return _loader; + } + + public function get InputBytes():ByteArray { + return _inputBytes; + } + + public function set InputBytes(b:ByteArray):void { + _inputBytes = b; + } + + public function get stream():URLStream + { + return _stream; } - var length:uint = byte & 0x3f; - if (length == 0x3f) { - length = bytes.readInt(); + + public function get loader():Loader + { + return _loader; + } + + public function set loader(value:Loader):void + { + _loader = value; + } + + public function load(request:URLRequest, loaderCtx:LoaderContext):void + { + //resetURLStream(); + + _attempts++; + _request = request; + _stream.load(request); + _inputBytes = new ByteArray(); + + // wait with this one.. seems a bit dodgy + //flash.utils.setTimeout(retry,7000); + } + + private function retry():void{ + if(_attempts<4 && _doretry){ + _attempts++; + _stream.load(_request); + flash.utils.setTimeout(retry,7000); + } + } + + private function streamCompleteHandler(event:Event):void{ + flash.utils.setTimeout(confirmBytesLoaded,500); + _stream.close(); + } + + private function confirmBytesLoaded():void{ + try{ + _stream.readBytes(_inputBytes,_inputBytes.length); + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes,_loaderCtx); + } + catch(e:Error){ // on error try again, version 9 of flash player sometimes fails. + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes,_loaderCtx); + } + } + + private function nonProgressiveProgress(event:ProgressEvent):void{ + _doretry = (_loader.contentLoaderInfo==null || _loader.contentLoaderInfo.bytesLoaded<2000); + } + + private function streamProgressHandler(event:ProgressEvent):void{ + //if there are no bytes do nothing + _stream.readBytes(_inputBytes,_inputBytes.length);_bytesPending = _inputBytes.length - _prevLength; + + if(_inputBytes.length>4){ + version = uint(_inputBytes[3]); + + if (version <= 9) { + updateVersion(9,_inputBytes); + } + } + + if(_bytesPending > (event.bytesTotal / 10) || (_loader.contentLoaderInfo != null && event.bytesTotal == _bytesPending + _loader.contentLoaderInfo.bytesLoaded)) { + _bytesPending = 0; + _prevLength = _inputBytes.length; + try{ + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes,_loaderCtx);} + catch(e:Error){ // on error try again, version 9 of flash player sometimes fails. + _loader.unloadAndStop(true); + _loader.loadBytes(_inputBytes,_loaderCtx); + } + } + + _doretry = (_loader.contentLoaderInfo==null || _loader.contentLoaderInfo.bytesLoaded<2000); + } + + private function completeHandler(event:Event):void + { + _inputBytes = new ByteArray(); + _stream.readBytes(_inputBytes); + _stream.close(); + _inputBytes.endian = Endian.LITTLE_ENDIAN; + + if (isCompressed(_inputBytes)) { + uncompress(_inputBytes); + } + + version = uint(_inputBytes[3]); + + if (version <= 9) { + if (version == 8 || version == 9) { + flagSWF9Bit(_inputBytes); + }else if (version <= 7) { + insertFileAttributesTag(_inputBytes); + } + updateVersion(9,_inputBytes); + } + + loader.unloadAndStop(true); + loader.loadBytes(_inputBytes,_loaderCtx); + } + + public function isCompressed(bytes:ByteArray):Boolean + { + return bytes[0] == 0x43; + } + + private function uncompress(bytes:ByteArray):void + { + var cBytes:ByteArray = new ByteArray(); + cBytes.writeBytes(bytes, 8); + bytes.length = 8; + bytes.position = 8; + cBytes.uncompress(); + bytes.writeBytes(cBytes); + bytes[0] = 0x46; + cBytes.length = 0; } - bytes.position += length; - } - } - catch (e:EOFError) { - } - - return -1; - } - - public function postProcessBytes(bytes:ByteArray):void { - flagSWF9Bit(bytes); - } - - public function flagSWF9Bit(bytes:ByteArray):void { - var pos:int = findFileAttributesPosition(getBodyPosition(bytes), bytes); - - if (pos != -1) { - bytes[pos + 2] |= 0x08; - } - else { - insertFileAttributesTag(bytes); - } - } - - public function signFileHeader(bytes:ByteArray, ldr:Loader = null):void { - _resigned = true; - insertFileAttributesTag(bytes); - if (ldr != null) { - ldr.unloadAndStop(true); - ldr.loadBytes(bytes, _loaderCtx); - } - else { - _loader.unloadAndStop(true); - _loader.loadBytes(bytes, _loaderCtx); + private function getBodyPosition(bytes:ByteArray):uint + { + var result:uint = 0; + + result += 3; // FWS/CWS + result += 1; // version(byte) + result += 4; // length(32bit-uint) + + var rectNBits:uint = bytes[result] >>> 3; + result += (5 + rectNBits * 4) / 8; // stage(rect) + + result += 2; + + result += 1; // frameRate(byte) + result += 2; // totalFrames(16bit-uint) + + return result; + } + + private function findFileAttributesPosition(offset:uint, bytes:ByteArray):int + { + bytes.position = offset; + + try { + for (;;) { + var byte:uint = bytes.readShort(); + var tag:uint = byte >>> 6; + if (tag == 69) { + return bytes.position - 2; + } + var length:uint = byte & 0x3f; + if (length == 0x3f) { + length = bytes.readInt(); + } + bytes.position += length; + } + } + catch (e:EOFError) { + } + + return -1; + } + + public function postProcessBytes(bytes:ByteArray):void{ + flagSWF9Bit(bytes); + } + + public function flagSWF9Bit(bytes:ByteArray):void + { + var pos:int = findFileAttributesPosition(getBodyPosition(bytes), bytes); + + if (pos != -1) { + bytes[pos + 2] |= 0x08; + } + else { + insertFileAttributesTag(bytes); + } + } + + public function signFileHeader(bytes:ByteArray, ldr:Loader=null):void{ + _resigned=true; + insertFileAttributesTag(bytes); + + if(ldr!=null) + { + ldr.unloadAndStop(true); + ldr.loadBytes(bytes,_loaderCtx); + } + else{ + _loader.unloadAndStop(true); + _loader.loadBytes(bytes,_loaderCtx); + } + } + + private function insertFileAttributesTag(bytes:ByteArray):void + { + var pos:uint = getBodyPosition(bytes); + var afterBytes:ByteArray = new ByteArray(); + afterBytes.writeBytes(bytes, pos); + bytes.length = pos; + bytes.position = pos; + bytes.writeByte(0x44); + bytes.writeByte(0x11); + bytes.writeByte(0x08); + bytes.writeByte(0x00); + bytes.writeByte(0x00); + bytes.writeByte(0x00); + bytes.writeBytes(afterBytes); + afterBytes.length = 0; + } + + public function updateVersion(version:uint, b:ByteArray):void + { + b[3] = version; + } + + public function dispatchEvent(event:Event):Boolean { + return dispatcher.dispatchEvent(event); + } + + public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { + dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); + } + + public function hasEventListener(type:String):Boolean { + return dispatcher.hasEventListener(type); + } + + public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { + dispatcher.removeEventListener(type, listener, useCapture); + } + + public function willTrigger(type:String):Boolean { + return dispatcher.willTrigger(type); + } + + private function ioErrorHandler(event:IOErrorEvent):void + { + var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); + evt.text = event.text; + dispatchEvent(evt); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void + { + var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); + evt.text = event.text; + dispatchEvent(evt); + } } - } - - private function insertFileAttributesTag(bytes:ByteArray):void { - var pos:uint = getBodyPosition(bytes); - var afterBytes:ByteArray = new ByteArray(); - afterBytes.writeBytes(bytes, pos); - bytes.length = pos; - bytes.position = pos; - bytes.writeByte(0x44); - bytes.writeByte(0x11); - bytes.writeByte(0x08); - bytes.writeByte(0x00); - bytes.writeByte(0x00); - bytes.writeByte(0x00); - bytes.writeBytes(afterBytes); - afterBytes.length = 0; - } - - public function updateVersion(version:uint, b:ByteArray):void { - b[3] = version; - } - - public function dispatchEvent(event:Event):Boolean { - return dispatcher.dispatchEvent(event); - } - - public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { - dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); - } - - public function hasEventListener(type:String):Boolean { - return dispatcher.hasEventListener(type); - } - - public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { - dispatcher.removeEventListener(type, listener, useCapture); - } - - public function willTrigger(type:String):Boolean { - return dispatcher.willTrigger(type); - } - - private function ioErrorHandler(event:IOErrorEvent):void { - var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); - evt.text = event.text; - dispatchEvent(evt); - } - - private function securityErrorHandler(event:SecurityErrorEvent):void { - var evt:ErrorEvent = new ErrorEvent("onDocumentLoadedError"); - evt.text = event.text; - dispatchEvent(evt); - } -} } diff --git a/docviewerflex/src/com/devaldi/streaming/DupImage.as b/docviewerflex/src/com/devaldi/streaming/DupImage.as index f913d28..ad6a130 100644 --- a/docviewerflex/src/com/devaldi/streaming/DupImage.as +++ b/docviewerflex/src/com/devaldi/streaming/DupImage.as @@ -19,7 +19,7 @@ along with FlexPaper. If not, see . package com.devaldi.streaming { import com.devaldi.controls.Spinner; - import com.devaldi.controls.flexpaper.resources.MenuIcons; + import com.log4ic.resources.MenuIcons; import flash.display.Bitmap; import flash.display.BitmapData; @@ -36,19 +36,16 @@ package com.devaldi.streaming public class DupImage extends Image { public var dupIndex:int = 0; - //public var dupScale:Number = 0; - //public var scaleWidth:int; - //public var scaleHeight:int; + public var dupScale:Number = 0; + public var scaleWidth:int; + public var scaleHeight:int; public var loadedIndex:int = -1; public var _paperRotation:int = 0; public var doAddDropShadow:Boolean = true; public var doAddGlowFilter:Boolean = false; public var glowFilterColor:uint = 0x000000; - public var NeedsFitting:Boolean = false; - public var RoleModelWidth:Number = 0; - public var RoleModelHeight:Number = 0; public static var paperSource:DisplayObject; - //private var _skinImgl:Bitmap = new MenuIcons.LOGO_SMALL(); + private var _skinImgl:Bitmap = new MenuIcons.LOGO_SMALL(); private var loadImg:Bitmap; private var loadSpinner:Spinner; @@ -56,7 +53,7 @@ package com.devaldi.streaming public function init():void{ loadImg = new Bitmap(); - //loadImg.bitmapData = _skinImgl.bitmapData; + loadImg.bitmapData = _skinImgl.bitmapData; loadImg.smoothing = true; loadSpinner = new Spinner(50,50); @@ -157,14 +154,6 @@ package com.devaldi.streaming //flash.utils.setTimeout(addDropShadow,200); super.addChildAt(child,0); - if(child is DupLoader && NeedsFitting){ - if((child as DupLoader).content!=null && ((child as DupLoader).content.width != RoleModelWidth || (child as DupLoader).content.height != RoleModelHeight)){ - this.width = (child as DupLoader).content.width * scaleX; - this.height = (child as DupLoader).content.height * scaleY; - } - NeedsFitting = false; - } - while(numChildren >= 2) delete(removeChildAt(1)); @@ -205,7 +194,6 @@ package com.devaldi.streaming } public function resetPage(width:Number,height:Number,scale:Number,showSpinner:Boolean=false):void{ - loadedIndex = -1; if(loadImg.parent != this) { @@ -224,6 +212,7 @@ package com.devaldi.streaming scaleX = scaleY = scale; addBlankChildAt(loadSpinner,numChildren); } + } } } \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/streaming/IDocumentLoader.as b/docviewerflex/src/com/devaldi/streaming/IDocumentLoader.as index 9573418..3b3f8ba 100644 --- a/docviewerflex/src/com/devaldi/streaming/IDocumentLoader.as +++ b/docviewerflex/src/com/devaldi/streaming/IDocumentLoader.as @@ -32,14 +32,13 @@ package com.devaldi.streaming function set LoaderList(v:Array):void; function postProcessBytes(b:ByteArray):void; function load(request:URLRequest, loaderCtx:LoaderContext):void; - function loadFromBytes(bytes:ByteArray):void; function resetURLStream():void; function signFileHeader(bytes:ByteArray, ldr:Loader=null):void; function get InputBytes():ByteArray; function set InputBytes(b:ByteArray):void; function get Resigned():Boolean; function get stream():URLStream; - function get IsSplit():Boolean; - function set IsSplit(b:Boolean):void; + function get PagesSplit():Boolean; + function set PagesSplit(b:Boolean):void; } } \ No newline at end of file diff --git a/docviewerflex/src/com/devaldi/streaming/SwfDocument.as b/docviewerflex/src/com/devaldi/streaming/SwfDocument.as index a0a9b53..e6c0ecd 100644 --- a/docviewerflex/src/com/devaldi/streaming/SwfDocument.as +++ b/docviewerflex/src/com/devaldi/streaming/SwfDocument.as @@ -1,94 +1,94 @@ /* - Copyright 2009 Erik Engström - - This file is part of FlexPaper. - - FlexPaper 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, version 3 of the License. - - FlexPaper 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 FlexPaper. If not, see . - */ -package com.devaldi.streaming { -import flash.display.Bitmap; -import flash.display.DisplayObject; -import flash.display.LoaderInfo; -import flash.display.MovieClip; -import flash.text.TextSnapshot; - - -public class SwfDocument implements IGenericDocument { - private var _mc:MovieClip; - - public function SwfDocument(mc:DisplayObject) { - if (mc is MovieClip) - _mc = mc as MovieClip; - else if (mc is Bitmap) { - _mc = new MovieClip(); - _mc.addChild(mc); - } - } - - public function gotoAndStop(pagNumber:int):void { - _mc.gotoAndStop(pagNumber); - } - - public function stop():void { - _mc.stop(); - } - - public function getDocument():DisplayObject { - return _mc; - } - - public function get parent():DisplayObject { - return _mc.parent; - } - - public function get totalFrames():int { - return _mc.totalFrames; - } - - public function get framesLoaded():int { - return _mc.framesLoaded; - } - - public function get textSnapshot():TextSnapshot { - return _mc.textSnapshot; - } - - public function set alpha(value:Number):void { - _mc.alpha = value; - } - - public function get currentFrame():int { - return _mc.currentFrame; - } - - public function get height():Number { - return _mc.height; - } - - public function get width():Number { - return _mc.width; - } - - public function get loaderInfo():LoaderInfo { - return _mc.loaderInfo; - } - - public function set scaleX(n:Number):void { - _mc.scaleX = n; - } - - public function set scaleY(n:Number):void { - _mc.scaleY = n; - } -} +Copyright 2009 Erik Engström + +This file is part of FlexPaper. + +FlexPaper 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, version 3 of the License. + +FlexPaper 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 FlexPaper. If not, see . +*/ +package com.devaldi.streaming +{ + import flash.display.Bitmap; + import flash.display.DisplayObject; + import flash.display.LoaderInfo; + import flash.display.MovieClip; + import flash.text.TextSnapshot; + + public class SwfDocument implements IGenericDocument{ + private var _mc:MovieClip; + + public function SwfDocument(mc:DisplayObject){ + if(mc is MovieClip) + _mc = mc as MovieClip; + else if(mc is Bitmap){ + _mc = new MovieClip(); + _mc.addChild(mc); + } + } + + public function gotoAndStop(pagNumber:int):void{ + _mc.gotoAndStop(pagNumber); + } + + public function stop():void{ + _mc.stop(); + } + + public function getDocument():DisplayObject{ + return _mc; + } + + public function get parent():DisplayObject{ + return _mc.parent; + } + + public function get totalFrames():int{ + return _mc.totalFrames; + } + + public function get framesLoaded():int{ + return _mc.framesLoaded; + } + + public function get textSnapshot():TextSnapshot{ + return _mc.textSnapshot; + } + + public function set alpha(value:Number):void{ + _mc.alpha = value; + } + + public function get currentFrame():int{ + return _mc.currentFrame; + } + + public function get height():Number{ + return _mc.height; + } + + public function get width():Number{ + return _mc.width; + } + + public function get loaderInfo():LoaderInfo{ + return _mc.loaderInfo; + } + + public function set scaleX(n:Number):void{ + _mc.scaleX = n; + } + + public function set scaleY(n:Number):void{ + _mc.scaleY = n; + } + } } \ No newline at end of file diff --git a/docviewerflex/src/com/log4ic/.svn/all-wcprops b/docviewerflex/src/com/log4ic/.svn/all-wcprops new file mode 100644 index 0000000..8c0a1c8 --- /dev/null +++ b/docviewerflex/src/com/log4ic/.svn/all-wcprops @@ -0,0 +1,5 @@ +K 25 +svn:wc:ra_dav:version-url +V 46 +/svn/!svn/ver/507/trunk/FlexPaper_SDK4/src/com +END diff --git a/docviewerflex/src/com/log4ic/.svn/entries b/docviewerflex/src/com/log4ic/.svn/entries new file mode 100644 index 0000000..0c2f1c7 --- /dev/null +++ b/docviewerflex/src/com/log4ic/.svn/entries @@ -0,0 +1,31 @@ +10 + +dir +515 +http://flexpaper.googlecode.com/svn/trunk/FlexPaper_SDK4/src/com +http://flexpaper.googlecode.com/svn + + + +2011-05-25T22:48:03.870074Z +507 +erik.engstroem@gmail.com + + + + + + + + + + + + + + +480254ca-d54f-11de-a63d-2763023b5f98 + +devaldi +dir + diff --git a/docviewerflex/src/com/log4ic/resources/MenuIcons.as b/docviewerflex/src/com/log4ic/resources/MenuIcons.as new file mode 100644 index 0000000..51b0631 --- /dev/null +++ b/docviewerflex/src/com/log4ic/resources/MenuIcons.as @@ -0,0 +1,59 @@ +/** + * @author: 张立鑫 + * @version: 1 + * @date: 11-10-28 上午11:08 + */ +package com.log4ic.resources { +public class MenuIcons { + public function MenuIcons():*{} + + [Embed("/../resources/pagefit.gif")] + static public const PAGE_FIT:Class; + [Embed("/../resources/fullscreen.gif")] + static public const FULLSCREEN:Class; + + [Embed("/../resources/fit.gif")] + static public const PAGE_FITWIDTH:Class; + [Embed("/../resources/sliderdot.gif")] + static public const SLIDER_DOT:Class; + [Embed("/../resources/grabbing.gif")] + static public const GRABBING:Class; + [Embed("/../resources/textselect.gif")] + static public const TEXT_SELECT:Class; + [Embed("/../resources/twopage.gif")] + static public const TWO_PAGE:Class; + + [Embed("/../resources/logosmall.png")] + static public const LOGO_SMALL:Class; + [Embed("/../resources/grab.gif")] + static public const GRAB:Class; + [Embed("/../resources/icon-arrow-left.gif")] + static public const ARROW_LEFT:Class; + [Embed("/../resources/logosmall-trans.png")] + static public const SMALL_TRANSPARENT:Class; + [Embed("/../resources/logosmall-transc.png")] + static public const SMALL_TRANSPARENT_COLOR:Class; + + [Embed("/../resources/textselectcursor.gif")] + static public const TEXT_SELECT_CURSOR:Class; + [Embed("/../resources/print-icon.gif")] + static public const PRINT_ICON:Class; + [Embed("/../resources/thumbs.gif")] + static public const THUMBS:Class; + [Embed("/../resources/hand2.gif")] + static public const HAND:Class; + [Embed("/../resources/bar.gif")] + static public const BAR:Class; + + + [Embed("/../resources/icon-arrow-right.gif")] + static public const ARROW_RIGHT:Class; + [Embed("/../resources/find.gif")] + static public const FIND:Class; + [Embed("/../resources/logosmallgray.png")] + static public const SMALL_GRAY:Class; + [Embed("/../resources/singlepage.gif")] + static public const SINGLE_PAGE:Class; +} + +} diff --git a/docviewerflex/src/com/log4ic/streaming/EncryptedLoader.as b/docviewerflex/src/com/log4ic/streaming/EncryptedLoader.as new file mode 100644 index 0000000..38c0092 --- /dev/null +++ b/docviewerflex/src/com/log4ic/streaming/EncryptedLoader.as @@ -0,0 +1,45 @@ +/** + * @author: 张立鑫 + * @version: 1 + */ +package com.log4ic.streaming { +import com.devaldi.streaming.DupLoader; +import com.log4ic.utils.security.XXTEA; + +import flash.system.LoaderContext; + +import flash.utils.ByteArray; + +import mx.controls.Alert; + +[Event(name="onDocumentLoadedError", type="flash.events.ErrorEvent")] +[Event(name="onLoadersLoaded", type="flash.events.Event")] +[Event(name="onSwfLoaded", type="com.devaldi.events.SwfLoadedEvent")] + +public class EncryptedLoader extends DupLoader { + private static var secretKey:ByteArray = null; + private static var _secretKey:String = null; + + public static function set SecretKey(key:String):void{ + if (key) { + _secretKey = key; + secretKey = new ByteArray(); + secretKey.writeUTFBytes(key); + } + } + + public static function get SecretKey():String{ + return _secretKey; + } + + + + override public function loadBytes(bytes:ByteArray, context:LoaderContext = null):void { + if (secretKey) { + bytes = XXTEA.decrypt(bytes, secretKey); + Alert.show(secretKey.toString()); + } + super.loadBytes(bytes, context); + } +} +} diff --git a/docviewerflex/src/com/log4ic/utils/StringUtils.as b/docviewerflex/src/com/log4ic/utils/StringUtils.as new file mode 100644 index 0000000..e6bb299 --- /dev/null +++ b/docviewerflex/src/com/log4ic/utils/StringUtils.as @@ -0,0 +1,274 @@ +/** + * @author: 张立鑫 + * @version: 1 + */ +package com.log4ic.utils { +public class StringUtils { + //忽略大小字母比较字符是否相等; + public static function equalsIgnoreCase(char1:String, char2:String):Boolean { + return char1.toLowerCase() == char2.toLowerCase(); + } + + //比较字符是否相等; + public static function equals(char1:String, char2:String):Boolean { + return char1 == char2; + } + + //是否为Email地址; + public static function isEmail(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /(\w|[_.\-])+@((\w|-)+\.)+\w{2,4}+/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //是否是数值字符串; + public static function isNumber(char:String):Boolean { + if (char == null) { + return false; + } + return !(isNaN(Number(char))) + } + + //是否为Double型数据; + public static function isDouble(char:String):Boolean { + char = trim(char); + var pattern:RegExp = /^[-\+]?\d+(\.\d+)?$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //Integer; + public static function isInteger(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /^[-\+]?\d+$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //English; + public static function isEnglish(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /^[A-Za-z]+$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //中文; + public static function isChinese(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /^[\u0391-\uFFE5]+$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //双字节 + public static function isDoubleChar(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /^[^\x00-\xff]+$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //含有中文字符 + public static function hasChineseChar(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char); + var pattern:RegExp = /[^\x00-\xff]/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //注册字符; + public static function hasAccountChar(char:String, len:uint = 15):Boolean { + if (char == null) { + return false; + } + if (len < 10) { + len = 15; + } + char = trim(char); + var pattern:RegExp = new RegExp("^[a-zA-Z0-9][a-zA-Z0-9_-]{0," + len + "}$", ""); + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + //URL地址; + public static function isURL(char:String):Boolean { + if (char == null) { + return false; + } + char = trim(char).toLowerCase(); + var pattern:RegExp = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/; + var result:Object = pattern.exec(char); + if (result == null) { + return false; + } + return true; + } + + // 是否为空白; + public static function isWhitespace(char:String):Boolean { + switch (char) { + case " ": + case "\t": + case "\r": + case "\n": + case "\f": + return true; + default: + return false; + } + } + + //去左右空格; + public static function trim(char:String):String { + if (char == null) { + return null; + } + return rtrim(ltrim(char)); + } + + //去左空格; + public static function ltrim(char:String):String { + if (char == null) { + return null; + } + var pattern:RegExp = /^\s*/; + return char.replace(pattern, ""); + } + + //去右空格; + public static function rtrim(char:String):String { + if (char == null) { + return null; + } + var pattern:RegExp = /\s*$/; + return char.replace(pattern, ""); + } + + //是否为前缀字符串; + public static function beginsWith(char:String, prefix:String):Boolean { + return (prefix == char.substring(0, prefix.length)); + } + + //是否为后缀字符串; + public static function endsWith(char:String, suffix:String):Boolean { + return (suffix == char.substring(char.length - suffix.length)); + } + + //去除指定字符串; + public static function remove(char:String, remove:String):String { + return replace(char, remove, ""); + } + + //字符串替换; + public static function replace(char:String, replace:String, replaceWith:String):String { + return char.split(replace).join(replaceWith); + } + + //utf16转utf8编码; + public static function utf16to8(char:String):String { + var out:Array = new Array(); + var len:uint = char.length; + for (var i:uint = 0; i < len; i++) { + var c:int = char.charCodeAt(i); + if (c >= 0x0001 && c <= 0x007F) { + out[i] = char.charAt(i); + } else if (c > 0x07FF) { + out[i] = String.fromCharCode(0xE0 | ((c >> 12) & 0x0F), + 0x80 | ((c >> 6) & 0x3F), + 0x80 | ((c >> 0) & 0x3F)); + } else { + out[i] = String.fromCharCode(0xC0 | ((c >> 6) & 0x1F), + 0x80 | ((c >> 0) & 0x3F)); + } + } + return out.join(''); + } + + //utf8转utf16编码; + public static function utf8to16(char:String):String { + var out:Array = new Array(); + var len:uint = char.length; + var i:uint = 0; + while (i < len) { + var c:int = char.charCodeAt(i++); + switch (c >> 4) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + // 0xxxxxxx + out[out.length] = char.charAt(i - 1); + break; + case 12: + case 13: + // 110x xxxx 10xx xxxx + var char2:int = char.charCodeAt(i++); + out[out.length] = String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + var char2:int = char.charCodeAt(i++); + var char3:int = char.charCodeAt(i++); + out[out.length] = String.fromCharCode(((c & 0x0F) << 12) | + ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); + break; + } + } + return out.join(''); + } + + + function StringUtils() { + throw new Error("StringUtil class is static container only"); + } + +} +} diff --git a/docviewerflex/src/com/log4ic/utils/security/XXTEA.as b/docviewerflex/src/com/log4ic/utils/security/XXTEA.as new file mode 100644 index 0000000..17ac3d8 --- /dev/null +++ b/docviewerflex/src/com/log4ic/utils/security/XXTEA.as @@ -0,0 +1,121 @@ +/** + * @author: 张立鑫 + * @version: 1 + */ +package com.log4ic.utils.security { + +import flash.utils.ByteArray; +import flash.utils.Endian; + +public class XXTEA { + private static const delta:uint = uint(0x9E3779B9); + + private static function LongArrayToByteArray(data:Array, includeLength:Boolean):ByteArray { + var length:uint = data.length; + var n:uint = (length - 1) << 2; + if (includeLength) { + var m:uint = data[length - 1]; + if ((m < n - 3) || (m > n)) { + return null; + } + n = m; + } + var result:ByteArray = new ByteArray(); + result.endian = Endian.LITTLE_ENDIAN; + for (var i:uint = 0; i < length; i++) { + result.writeUnsignedInt(data[i]); + } + if (includeLength) { + result.length = n; + return result; + } + else { + return result; + } + } + + private static function ByteArrayToLongArray(data:ByteArray, includeLength:Boolean):Array { + var length:uint = data.length; + var n:uint = length >> 2; + if (length % 4 > 0) { + n++; + data.length += (4 - (length % 4)); + } + data.endian = Endian.LITTLE_ENDIAN; + data.position = 0; + var result:Array = []; + for (var i:uint = 0; i < n; i++) { + result[i] = data.readUnsignedInt(); + } + if (includeLength) { + result[n] = length; + } + data.length = length; + return result; + } + + public static function encrypt(data:ByteArray, key:ByteArray):ByteArray { + if (data.length == 0) { + return new ByteArray(); + } + var v:Array = ByteArrayToLongArray(data, true); + var k:Array = ByteArrayToLongArray(key, false); + if (k.length < 4) { + k.length = 4; + } + var n:uint = v.length - 1; + var z:uint = v[n]; + var y:uint = v[0]; + var mx:uint; + var e:uint; + var p:uint; + var q:uint = uint(6 + 52 / (n + 1)); + var sum:uint = 0; + while (0 < q--) { + sum = sum + delta; + e = sum >>> 2 & 3; + for (p = 0; p < n; p++) { + y = v[p + 1]; + mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); + z = v[p] = v[p] + mx; + } + y = v[0]; + mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); + z = v[n] = v[n] + mx; + } + return LongArrayToByteArray(v, false); + } + + public static function decrypt(data:ByteArray, key:ByteArray):ByteArray { + if (data.length == 0) { + return new ByteArray(); + } + var v:Array = ByteArrayToLongArray(data, false); + var k:Array = ByteArrayToLongArray(key, false); + if (k.length < 4) { + k.length = 4; + } + var n:uint = v.length - 1; + var z:uint = v[n - 1]; + var y:uint = v[0]; + var mx:uint; + var e:uint; + var p:uint; + var q:uint = uint(6 + 52 / (n + 1)); + var sum:uint = q * delta; + while (sum != 0) { + e = sum >>> 2 & 3; + for (p = n; p > 0; p--) { + z = v[p - 1]; + mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); + y = v[p] = v[p] - mx; + } + z = v[n]; + mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); + y = v[0] = v[0] - mx; + sum = sum - delta; + } + return LongArrayToByteArray(v, true); + } +} +} diff --git a/docviewerflex/src/com/sinitek/log4ic/utils/security/Security.as b/docviewerflex/src/com/sinitek/log4ic/utils/security/Security.as deleted file mode 100644 index 4aa6650..0000000 --- a/docviewerflex/src/com/sinitek/log4ic/utils/security/Security.as +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @author: 张立鑫 - * @version: 1 - */ -package com.sinitek.log4ic.utils.security { -import com.sinitek.log4ic.streaming.EncryptedLoader; - -import flash.events.Event; -import flash.events.ProgressEvent; -import flash.events.TimerEvent; -import flash.net.URLLoader; -import flash.net.URLLoaderDataFormat; -import flash.net.URLRequest; -import flash.utils.ByteArray; -import flash.utils.Dictionary; -import flash.utils.Timer; -import flash.utils.clearTimeout; -import flash.utils.setTimeout; - -import mx.controls.Alert; - -public class Security { - - private static var loaderMap:Dictionary = new Dictionary(); - - - public static function loadEncryptedFile(url:URLRequest, key:String, onComplete:Function, onProgress:Function):void { - - var loader:EncryptedLoader = loaderMap[url.url]; - - if (loader) { - loader.removeEventListener(Event.COMPLETE, onComplete); - loader.addEventListener(Event.COMPLETE, onComplete); - if (loader.loaded) { - loader.dispatchEvent(new Event(Event.COMPLETE)); - } - return; - } - var keyBytes:ByteArray = null; - if (key) { - keyBytes = new ByteArray(); - keyBytes.writeUTFBytes(key); - } - - var urlLoader:EncryptedLoader = new EncryptedLoader(keyBytes); - - urlLoader.addEventListener(Event.COMPLETE, onComplete); - if (onProgress) { - urlLoader.addEventListener(ProgressEvent.PROGRESS, onProgress); - } - - loaderMap[url.url] = urlLoader; - - urlLoader.load(url); - } - - public static function isLoaded(url:URLRequest) { - return !!loaderMap[url]; - } -} -} diff --git a/lib/common/antlr-2.7.4.jar b/lib/common/antlr-2.7.4.jar new file mode 100644 index 0000000..45e45b5 Binary files /dev/null and b/lib/common/antlr-2.7.4.jar differ diff --git a/lib/common/chardet-1.0.jar b/lib/common/chardet-1.0.jar new file mode 100644 index 0000000..2e84a8d Binary files /dev/null and b/lib/common/chardet-1.0.jar differ diff --git a/lib/common/commons-fileupload-1.2.2.jar b/lib/common/commons-fileupload-1.2.2.jar new file mode 100644 index 0000000..131f192 Binary files /dev/null and b/lib/common/commons-fileupload-1.2.2.jar differ diff --git a/lib/common/cpdetector_1.0.10.jar b/lib/common/cpdetector_1.0.10.jar new file mode 100644 index 0000000..47329f2 Binary files /dev/null and b/lib/common/cpdetector_1.0.10.jar differ diff --git a/lib/common/jargs-1.0.jar b/lib/common/jargs-1.0.jar new file mode 100644 index 0000000..92d9b9b Binary files /dev/null and b/lib/common/jargs-1.0.jar differ diff --git a/lib/common/javolution-5.5.1.jar b/lib/common/javolution-5.5.1.jar new file mode 100755 index 0000000..7ac80ea Binary files /dev/null and b/lib/common/javolution-5.5.1.jar differ diff --git a/lib/j2ee1.4/.svn/entries b/lib/j2ee1.4/.svn/entries deleted file mode 100644 index 8ec0826..0000000 --- a/lib/j2ee1.4/.svn/entries +++ /dev/null @@ -1,96 +0,0 @@ -10 - -dir -9168 -https://192.168.20.160/svn/xn-sirm/xn-sirm/lib/J2EE1.4 -https://192.168.20.160/svn/xn-sirm - - - -2011-03-18T02:48:22.796875Z -21 -pandq - - - - - - - - - - - - - - -c358651b-13a4-9f43-a4ae-1fe8d8f71035 - -servlet-api.jar -file - - - - -2011-06-24T02:47:54.000000Z -532510e56fbe17402c763cc632f5eb0f -2011-03-18T02:48:22.796875Z -21 -pandq -has-props - - - - - - - - - - - - - - - - - - - - -97703 - -jsp-api.jar -file - - - - -2011-06-24T02:47:54.000000Z -bae35866373aa1ba25023a9bb383adfb -2011-03-18T02:48:22.796875Z -21 -pandq -has-props - - - - - - - - - - - - - - - - - - - - -50501 - diff --git a/lib/j2ee1.4/.svn/prop-base/jsp-api.jar.svn-base b/lib/j2ee1.4/.svn/prop-base/jsp-api.jar.svn-base deleted file mode 100644 index 5e9587e..0000000 --- a/lib/j2ee1.4/.svn/prop-base/jsp-api.jar.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 13 -svn:mime-type -V 24 -application/octet-stream -END diff --git a/lib/j2ee1.4/.svn/prop-base/servlet-api.jar.svn-base b/lib/j2ee1.4/.svn/prop-base/servlet-api.jar.svn-base deleted file mode 100644 index 5e9587e..0000000 --- a/lib/j2ee1.4/.svn/prop-base/servlet-api.jar.svn-base +++ /dev/null @@ -1,5 +0,0 @@ -K 13 -svn:mime-type -V 24 -application/octet-stream -END diff --git a/lib/j2ee1.4/.svn/text-base/jsp-api.jar.svn-base b/lib/j2ee1.4/.svn/text-base/jsp-api.jar.svn-base deleted file mode 100644 index be5b565..0000000 Binary files a/lib/j2ee1.4/.svn/text-base/jsp-api.jar.svn-base and /dev/null differ diff --git a/lib/j2ee1.4/.svn/text-base/servlet-api.jar.svn-base b/lib/j2ee1.4/.svn/text-base/servlet-api.jar.svn-base deleted file mode 100644 index 93186f6..0000000 Binary files a/lib/j2ee1.4/.svn/text-base/servlet-api.jar.svn-base and /dev/null differ diff --git a/lib/j2ee1.4/jsp-api.jar b/lib/j2ee1.4/jsp-api.jar deleted file mode 100644 index be5b565..0000000 Binary files a/lib/j2ee1.4/jsp-api.jar and /dev/null differ diff --git a/lib/j2ee1.4/servlet-api.jar b/lib/j2ee1.4/servlet-api.jar deleted file mode 100644 index 93186f6..0000000 Binary files a/lib/j2ee1.4/servlet-api.jar and /dev/null differ diff --git a/lib/j2ee6/javax.persistence.jar b/lib/j2ee6/javax.persistence.jar new file mode 100644 index 0000000..21d80e0 Binary files /dev/null and b/lib/j2ee6/javax.persistence.jar differ diff --git a/lib/j2ee6/javax.servlet.jar b/lib/j2ee6/javax.servlet.jar new file mode 100644 index 0000000..0519e4a Binary files /dev/null and b/lib/j2ee6/javax.servlet.jar differ diff --git a/lib/j2ee6/javax.servlet.jsp.jar b/lib/j2ee6/javax.servlet.jsp.jar new file mode 100644 index 0000000..9c0631c Binary files /dev/null and b/lib/j2ee6/javax.servlet.jsp.jar differ